scalingX commited on
Commit
5b60fc2
·
verified ·
1 Parent(s): 4418548

Add 10000 GitHub Trending pr_diff environments

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. README.md +318 -0
  2. manifest.json +0 -0
  3. tasks/1sdv__TripStar-15/environment/Dockerfile +37 -0
  4. tasks/1sdv__TripStar-15/instruction.md +19 -0
  5. tasks/1sdv__TripStar-15/solution/patch.diff +285 -0
  6. tasks/1sdv__TripStar-15/solution/solve.sh +6 -0
  7. tasks/1sdv__TripStar-15/task.toml +71 -0
  8. tasks/1sdv__TripStar-15/tests/capture.py +96 -0
  9. tasks/1sdv__TripStar-15/tests/instruction.md +19 -0
  10. tasks/1sdv__TripStar-15/tests/oracle.patch +285 -0
  11. tasks/1sdv__TripStar-15/tests/test.sh +25 -0
  12. tasks/1sdv__TripStar-15/tests/verifier.py +737 -0
  13. tasks/1sdv__TripStar-20/environment/Dockerfile +37 -0
  14. tasks/1sdv__TripStar-20/instruction.md +44 -0
  15. tasks/1sdv__TripStar-20/solution/patch.diff +77 -0
  16. tasks/1sdv__TripStar-20/solution/solve.sh +6 -0
  17. tasks/1sdv__TripStar-20/task.toml +69 -0
  18. tasks/1sdv__TripStar-20/tests/capture.py +96 -0
  19. tasks/1sdv__TripStar-20/tests/instruction.md +44 -0
  20. tasks/1sdv__TripStar-20/tests/oracle.patch +77 -0
  21. tasks/1sdv__TripStar-20/tests/test.sh +25 -0
  22. tasks/1sdv__TripStar-20/tests/verifier.py +737 -0
  23. tasks/1sdv__TripStar-21/environment/Dockerfile +37 -0
  24. tasks/1sdv__TripStar-21/instruction.md +30 -0
  25. tasks/1sdv__TripStar-21/solution/patch.diff +115 -0
  26. tasks/1sdv__TripStar-21/solution/solve.sh +6 -0
  27. tasks/1sdv__TripStar-21/task.toml +72 -0
  28. tasks/1sdv__TripStar-21/tests/capture.py +96 -0
  29. tasks/1sdv__TripStar-21/tests/instruction.md +30 -0
  30. tasks/1sdv__TripStar-21/tests/oracle.patch +115 -0
  31. tasks/1sdv__TripStar-21/tests/test.sh +25 -0
  32. tasks/1sdv__TripStar-21/tests/verifier.py +737 -0
  33. tasks/1sdv__TripStar-46/environment/Dockerfile +37 -0
  34. tasks/1sdv__TripStar-46/instruction.md +59 -0
  35. tasks/1sdv__TripStar-46/solution/patch.diff +306 -0
  36. tasks/1sdv__TripStar-46/solution/solve.sh +6 -0
  37. tasks/1sdv__TripStar-46/task.toml +71 -0
  38. tasks/1sdv__TripStar-46/tests/capture.py +96 -0
  39. tasks/1sdv__TripStar-46/tests/instruction.md +59 -0
  40. tasks/1sdv__TripStar-46/tests/oracle.patch +306 -0
  41. tasks/1sdv__TripStar-46/tests/test.sh +25 -0
  42. tasks/1sdv__TripStar-46/tests/verifier.py +737 -0
  43. tasks/1sdv__TripStar-49/environment/Dockerfile +37 -0
  44. tasks/1sdv__TripStar-49/instruction.md +44 -0
  45. tasks/1sdv__TripStar-49/solution/patch.diff +495 -0
  46. tasks/1sdv__TripStar-49/solution/solve.sh +6 -0
  47. tasks/1sdv__TripStar-49/task.toml +71 -0
  48. tasks/1sdv__TripStar-49/tests/capture.py +96 -0
  49. tasks/1sdv__TripStar-49/tests/instruction.md +44 -0
  50. tasks/1sdv__TripStar-49/tests/oracle.patch +495 -0
README.md ADDED
@@ -0,0 +1,318 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ language:
4
+ - en
5
+ size_categories:
6
+ - n<1K
7
+ tags:
8
+ - reinforcement-learning
9
+ - code
10
+ - llm
11
+ - swe-rl
12
+ - harbor
13
+ - pr_diff
14
+ ---
15
+
16
+ [![View tasks in Harbor Visualiser](https://img.shields.io/badge/🤗%20Harbor%20Visualiser-View%20tasks-FFD21F?style=for-the-badge)](https://huggingface.co/spaces/HuggingFaceH4/harbor-visualiser?dataset=scalingX/github-trending-environments-10k)
17
+
18
+ # github-trending-environments-10k
19
+
20
+ Generated by [**Repo2RLEnv**](https://github.com/huggingface/Repo2RLEnv) — turning real GitHub repositories into verifiable RL environments.
21
+
22
+ > 💡 **Browse this dataset in your browser** — click the badge above or open
23
+ > [`HuggingFaceH4/harbor-visualiser`](https://huggingface.co/spaces/HuggingFaceH4/harbor-visualiser?dataset=scalingX/github-trending-environments-10k)
24
+ > to inspect every task's spec, instruction, oracle patch, test script, and Dockerfile.
25
+
26
+ - **Source repos** (217):
27
+ - [`1sdv/TripStar`](https://github.com/1sdv/TripStar)
28
+ - [`233boy/sing-box`](https://github.com/233boy/sing-box)
29
+ - [`666ghj/MiroFish`](https://github.com/666ghj/MiroFish)
30
+ - [`AeneasVerif/aeneas`](https://github.com/AeneasVerif/aeneas)
31
+ - [`AgriciDaniel/claude-seo`](https://github.com/AgriciDaniel/claude-seo)
32
+ - [`AhmadIbrahiim/Website-downloader`](https://github.com/AhmadIbrahiim/Website-downloader)
33
+ - [`Aidoku/Aidoku`](https://github.com/Aidoku/Aidoku)
34
+ - [`Alinto/sogo`](https://github.com/Alinto/sogo)
35
+ - [`Anil-matcha/Open-Generative-AI`](https://github.com/Anil-matcha/Open-Generative-AI)
36
+ - [`Anxcye/anx-reader`](https://github.com/Anxcye/anx-reader)
37
+ - [`AppFlowy-IO/AppFlowy`](https://github.com/AppFlowy-IO/AppFlowy)
38
+ - [`AstrBotDevs/AstrBot`](https://github.com/AstrBotDevs/AstrBot)
39
+ - [`Atlas-OS/Atlas`](https://github.com/Atlas-OS/Atlas)
40
+ - [`BLAKE3-team/BLAKE3`](https://github.com/BLAKE3-team/BLAKE3)
41
+ - [`BetterCrypto/Applied-Crypto-Hardening`](https://github.com/BetterCrypto/Applied-Crypto-Hardening)
42
+ - [`CapSoftware/Cap`](https://github.com/CapSoftware/Cap)
43
+ - [`ChrisTitusTech/winutil`](https://github.com/ChrisTitusTech/winutil)
44
+ - [`CorentinTh/it-tools`](https://github.com/CorentinTh/it-tools)
45
+ - [`CorsixTH/CorsixTH`](https://github.com/CorsixTH/CorsixTH)
46
+ - [`Cpasjuste/pemu`](https://github.com/Cpasjuste/pemu)
47
+ - [`CyrilPeng/Venera-Next`](https://github.com/CyrilPeng/Venera-Next)
48
+ - [`D4Vinci/Scrapling`](https://github.com/D4Vinci/Scrapling)
49
+ - [`DarkFlippers/unleashed-firmware`](https://github.com/DarkFlippers/unleashed-firmware)
50
+ - [`DeanChensj/jiangshan-map`](https://github.com/DeanChensj/jiangshan-map)
51
+ - [`DependencyTrack/dependency-track`](https://github.com/DependencyTrack/dependency-track)
52
+ - [`Difegue/LANraragi`](https://github.com/Difegue/LANraragi)
53
+ - [`Dolibarr/dolibarr`](https://github.com/Dolibarr/dolibarr)
54
+ - [`DrKLO/Telegram`](https://github.com/DrKLO/Telegram)
55
+ - [`E3SM-Project/E3SM`](https://github.com/E3SM-Project/E3SM)
56
+ - [`EC-CUBE/ec-cube`](https://github.com/EC-CUBE/ec-cube)
57
+ - [`ESCOMP/CTSM`](https://github.com/ESCOMP/CTSM)
58
+ - [`Ebullioscopic/Atoll`](https://github.com/Ebullioscopic/Atoll)
59
+ - [`ElemeFE/element`](https://github.com/ElemeFE/element)
60
+ - [`EllesmereGaming/EllesmereUI`](https://github.com/EllesmereGaming/EllesmereUI)
61
+ - [`ElmerCSC/elmerfem`](https://github.com/ElmerCSC/elmerfem)
62
+ - [`Euro-Office/DesktopEditors`](https://github.com/Euro-Office/DesktopEditors)
63
+ - [`Fincept-Corporation/FinceptTerminal`](https://github.com/Fincept-Corporation/FinceptTerminal)
64
+ - [`FreeCAD/FreeCAD`](https://github.com/FreeCAD/FreeCAD)
65
+ - [`Freika/dawarich`](https://github.com/Freika/dawarich)
66
+ - [`GTFOBins/GTFOBins.github.io`](https://github.com/GTFOBins/GTFOBins.github.io)
67
+ - [`Genymobile/scrcpy`](https://github.com/Genymobile/scrcpy)
68
+ - [`GokuMohandas/Made-With-ML`](https://github.com/GokuMohandas/Made-With-ML)
69
+ - [`GoogleChrome/modern-web-guidance-src`](https://github.com/GoogleChrome/modern-web-guidance-src)
70
+ - [`HD838A/remote-mic-app`](https://github.com/HD838A/remote-mic-app)
71
+ - [`HKUDS/DeepTutor`](https://github.com/HKUDS/DeepTutor)
72
+ - [`HKUDS/Vibe-Trading`](https://github.com/HKUDS/Vibe-Trading)
73
+ - [`HMCL-dev/HMCL`](https://github.com/HMCL-dev/HMCL)
74
+ - [`HapeLee/legado-with-MD3`](https://github.com/HapeLee/legado-with-MD3)
75
+ - [`HarbourMasters/Shipwright`](https://github.com/HarbourMasters/Shipwright)
76
+ - [`Helldez/BigMoeOnEdge`](https://github.com/Helldez/BigMoeOnEdge)
77
+ - [`Homebrew/brew`](https://github.com/Homebrew/brew)
78
+ - [`HuskerMinion/techo5`](https://github.com/HuskerMinion/techo5)
79
+ - [`ImranR98/Obtainium`](https://github.com/ImranR98/Obtainium)
80
+ - [`IntersectMBO/cardano-node`](https://github.com/IntersectMBO/cardano-node)
81
+ - [`InvoiceShelf/InvoiceShelf`](https://github.com/InvoiceShelf/InvoiceShelf)
82
+ - [`JetBrains/thinkrail`](https://github.com/JetBrains/thinkrail)
83
+ - [`JuliusBrussee/caveman`](https://github.com/JuliusBrussee/caveman)
84
+ - [`JustVugg/colibri`](https://github.com/JustVugg/colibri)
85
+ - [`KiCad/kicad-footprints`](https://github.com/KiCad/kicad-footprints)
86
+ - [`LSPosed/LSPosed`](https://github.com/LSPosed/LSPosed)
87
+ - [`LawnchairLauncher/lawnchair`](https://github.com/LawnchairLauncher/lawnchair)
88
+ - [`LazyVim/LazyVim`](https://github.com/LazyVim/LazyVim)
89
+ - [`Leantime/leantime`](https://github.com/Leantime/leantime)
90
+ - [`Leonxlnx/taste-skill`](https://github.com/Leonxlnx/taste-skill)
91
+ - [`LibreELEC/LibreELEC.tv`](https://github.com/LibreELEC/LibreELEC.tv)
92
+ - [`Loongphy/codex-auth`](https://github.com/Loongphy/codex-auth)
93
+ - [`MPAS-Dev/MPAS-Model`](https://github.com/MPAS-Dev/MPAS-Model)
94
+ - [`Manavarya09/design-extract`](https://github.com/Manavarya09/design-extract)
95
+ - [`MeanderingProgrammer/render-markdown.nvim`](https://github.com/MeanderingProgrammer/render-markdown.nvim)
96
+ - [`Mesh-LLM/mesh-llm`](https://github.com/Mesh-LLM/mesh-llm)
97
+ - [`MetOffice/jules`](https://github.com/MetOffice/jules)
98
+ - [`MetOffice/lfric_apps`](https://github.com/MetOffice/lfric_apps)
99
+ - [`MetOffice/lfric_core`](https://github.com/MetOffice/lfric_core)
100
+ - [`NVIDIA/SkillSpector`](https://github.com/NVIDIA/SkillSpector)
101
+ - [`NVIDIA/accelerated-computing-hub`](https://github.com/NVIDIA/accelerated-computing-hub)
102
+ - [`NVIDIA/cudf-spark`](https://github.com/NVIDIA/cudf-spark)
103
+ - [`NationalSecurityAgency/ghidra`](https://github.com/NationalSecurityAgency/ghidra)
104
+ - [`NirDiamant/RAG_Techniques`](https://github.com/NirDiamant/RAG_Techniques)
105
+ - [`OAI/OpenAPI-Specification`](https://github.com/OAI/OpenAPI-Specification)
106
+ - [`OpenKore/openkore`](https://github.com/OpenKore/openkore)
107
+ - [`OpenXiangShan/XiangShan`](https://github.com/OpenXiangShan/XiangShan)
108
+ - [`OpenZeppelin/openzeppelin-contracts`](https://github.com/OpenZeppelin/openzeppelin-contracts)
109
+ - [`Owl-Listener/designer-skills`](https://github.com/Owl-Listener/designer-skills)
110
+ - [`PHPMailer/PHPMailer`](https://github.com/PHPMailer/PHPMailer)
111
+ - [`PartialVolume/shredos.x86_64`](https://github.com/PartialVolume/shredos.x86_64)
112
+ - [`PathOfBuildingCommunity/PathOfBuilding`](https://github.com/PathOfBuildingCommunity/PathOfBuilding)
113
+ - [`PathOfBuildingCommunity/PathOfBuilding-PoE2`](https://github.com/PathOfBuildingCommunity/PathOfBuilding-PoE2)
114
+ - [`Perl/perl5`](https://github.com/Perl/perl5)
115
+ - [`PimpinPumpkin/Vela`](https://github.com/PimpinPumpkin/Vela)
116
+ - [`PostgREST/postgrest`](https://github.com/PostgREST/postgrest)
117
+ - [`Predidit/Kazumi`](https://github.com/Predidit/Kazumi)
118
+ - [`Predidit/KazumiRules`](https://github.com/Predidit/KazumiRules)
119
+ - [`PrestaShop/PrestaShop`](https://github.com/PrestaShop/PrestaShop)
120
+ - [`Questie/Questie`](https://github.com/Questie/Questie)
121
+ - [`QwenLM/qwen-code`](https://github.com/QwenLM/qwen-code)
122
+ - [`ROCKNIX/distribution`](https://github.com/ROCKNIX/distribution)
123
+ - [`ROCm/rocm-libraries`](https://github.com/ROCm/rocm-libraries)
124
+ - [`Rangi42/polishedcrystal`](https://github.com/Rangi42/polishedcrystal)
125
+ - [`Raphire/Win11Debloat`](https://github.com/Raphire/Win11Debloat)
126
+ - [`Rdatatable/data.table`](https://github.com/Rdatatable/data.table)
127
+ - [`RestedXP/RXPGuides`](https://github.com/RestedXP/RXPGuides)
128
+ - [`Rhizomatica/mercury`](https://github.com/Rhizomatica/mercury)
129
+ - [`RikkaApps/Shizuku`](https://github.com/RikkaApps/Shizuku)
130
+ - [`RotherOSS/otobo`](https://github.com/RotherOSS/otobo)
131
+ - [`SDWebImage/SDWebImage`](https://github.com/SDWebImage/SDWebImage)
132
+ - [`SDWebImage/SDWebImageSVGCoder`](https://github.com/SDWebImage/SDWebImageSVGCoder)
133
+ - [`SDWebImage/SDWebImageWebPCoder`](https://github.com/SDWebImage/SDWebImageWebPCoder)
134
+ - [`Seafoam-Labs/Shelly-ALPM`](https://github.com/Seafoam-Labs/Shelly-ALPM)
135
+ - [`Sketchware-Pro/Sketchware-Pro`](https://github.com/Sketchware-Pro/Sketchware-Pro)
136
+ - [`Smaug6739/Alexandrie`](https://github.com/Smaug6739/Alexandrie)
137
+ - [`Spectral-Finance/lux`](https://github.com/Spectral-Finance/lux)
138
+ - [`SukiSU-Nova/SukiSU-Nova`](https://github.com/SukiSU-Nova/SukiSU-Nova)
139
+ - [`SunshineStream/Sunshine`](https://github.com/SunshineStream/Sunshine)
140
+ - [`TNT-Likely/BeeCount`](https://github.com/TNT-Likely/BeeCount)
141
+ - [`The-PR-Agent/pr-agent`](https://github.com/The-PR-Agent/pr-agent)
142
+ - [`TheHive-Project/TheHive`](https://github.com/TheHive-Project/TheHive)
143
+ - [`TimOliver/TOCropViewController`](https://github.com/TimOliver/TOCropViewController)
144
+ - [`UnboundTechCo/defyxVPN`](https://github.com/UnboundTechCo/defyxVPN)
145
+ - [`Unstructured-IO/unstructured`](https://github.com/Unstructured-IO/unstructured)
146
+ - [`VSCodium/vscodium`](https://github.com/VSCodium/vscodium)
147
+ - [`Vectorized/solady`](https://github.com/Vectorized/solady)
148
+ - [`VictoriaMetrics/VictoriaMetrics`](https://github.com/VictoriaMetrics/VictoriaMetrics)
149
+ - [`Vincentwei1021/video-shotcraft`](https://github.com/Vincentwei1021/video-shotcraft)
150
+ - [`VueTorrent/VueTorrent`](https://github.com/VueTorrent/VueTorrent)
151
+ - [`ZhuLinsen/daily_stock_analysis`](https://github.com/ZhuLinsen/daily_stock_analysis)
152
+ - [`aardappel/goose`](https://github.com/aardappel/goose)
153
+ - [`abue-ammar/tinycast`](https://github.com/abue-ammar/tinycast)
154
+ - [`actions/runner-images`](https://github.com/actions/runner-images)
155
+ - [`addyosmani/agent-skills`](https://github.com/addyosmani/agent-skills)
156
+ - [`adrienverge/openfortivpn`](https://github.com/adrienverge/openfortivpn)
157
+ - [`affaan-m/ECC`](https://github.com/affaan-m/ECC)
158
+ - [`ag-ui-protocol/ag-ui`](https://github.com/ag-ui-protocol/ag-ui)
159
+ - [`aistra0528/Hail`](https://github.com/aistra0528/Hail)
160
+ - [`akitaonrails/ai-memory`](https://github.com/akitaonrails/ai-memory)
161
+ - [`algerkong/AlgerMusicPlayer`](https://github.com/algerkong/AlgerMusicPlayer)
162
+ - [`altic-dev/FluidVoice`](https://github.com/altic-dev/FluidVoice)
163
+ - [`amir1376/ab-download-manager`](https://github.com/amir1376/ab-download-manager)
164
+ - [`andreknieriem/open-headunit`](https://github.com/andreknieriem/open-headunit)
165
+ - [`angular/angular`](https://github.com/angular/angular)
166
+ - [`animate-css/animate.css`](https://github.com/animate-css/animate.css)
167
+ - [`aniyomiorg/aniyomi-website`](https://github.com/aniyomiorg/aniyomi-website)
168
+ - [`anomalyco/opencode`](https://github.com/anomalyco/opencode)
169
+ - [`anthropics/knowledge-work-plugins`](https://github.com/anthropics/knowledge-work-plugins)
170
+ - [`anthropics/sandbox-runtime`](https://github.com/anthropics/sandbox-runtime)
171
+ - [`apache/arrow-go`](https://github.com/apache/arrow-go)
172
+ - [`apache/texera`](https://github.com/apache/texera)
173
+ - [`appdevforall/CodeOnTheGo`](https://github.com/appdevforall/CodeOnTheGo)
174
+ - [`argoproj/argo-cd`](https://github.com/argoproj/argo-cd)
175
+ - [`ash-project/ash`](https://github.com/ash-project/ash)
176
+ - [`ashhart/TensorFold`](https://github.com/ashhart/TensorFold)
177
+ - [`astral-sh/ruff`](https://github.com/astral-sh/ruff)
178
+ - [`astral-sh/uv`](https://github.com/astral-sh/uv)
179
+ - [`autowarefoundation/autoware`](https://github.com/autowarefoundation/autoware)
180
+ - [`aws/aws-lc`](https://github.com/aws/aws-lc)
181
+ - [`axios/axios`](https://github.com/axios/axios)
182
+ - [`azahar-emu/azahar`](https://github.com/azahar-emu/azahar)
183
+ - [`bcpierce00/unison`](https://github.com/bcpierce00/unison)
184
+ - [`bggRGjQaUbCoE/PiliPlus`](https://github.com/bggRGjQaUbCoE/PiliPlus)
185
+ - [`biomejs/biome`](https://github.com/biomejs/biome)
186
+ - [`blackboardsh/electrobun`](https://github.com/blackboardsh/electrobun)
187
+ - [`block/buzz`](https://github.com/block/buzz)
188
+ - [`chipsalliance/rocket-chip`](https://github.com/chipsalliance/rocket-chip)
189
+ - [`cmderdev/cmder`](https://github.com/cmderdev/cmder)
190
+ - [`composer/composer`](https://github.com/composer/composer)
191
+ - [`corrosion-rs/corrosion`](https://github.com/corrosion-rs/corrosion)
192
+ - [`ed-donner/agents`](https://github.com/ed-donner/agents)
193
+ - [`expressjs/express`](https://github.com/expressjs/express)
194
+ - [`fatih/vim-go`](https://github.com/fatih/vim-go)
195
+ - [`folke/snacks.nvim`](https://github.com/folke/snacks.nvim)
196
+ - [`freqtrade/frequi`](https://github.com/freqtrade/frequi)
197
+ - [`ghostty-org/ghostty`](https://github.com/ghostty-org/ghostty)
198
+ - [`gitleaks/gitleaks`](https://github.com/gitleaks/gitleaks)
199
+ - [`gitroomhq/postiz-app`](https://github.com/gitroomhq/postiz-app)
200
+ - [`gnacho/netpulse`](https://github.com/gnacho/netpulse)
201
+ - [`google/gtm-session-fetcher`](https://github.com/google/gtm-session-fetcher)
202
+ - [`grimme-lab/xtb`](https://github.com/grimme-lab/xtb)
203
+ - [`hadolint/hadolint`](https://github.com/hadolint/hadolint)
204
+ - [`henrygd/beszel`](https://github.com/henrygd/beszel)
205
+ - [`huginn/huginn`](https://github.com/huginn/huginn)
206
+ - [`iBotPeaches/Apktool`](https://github.com/iBotPeaches/Apktool)
207
+ - [`ibhagwan/fzf-lua`](https://github.com/ibhagwan/fzf-lua)
208
+ - [`jenkinsci/jenkins`](https://github.com/jenkinsci/jenkins)
209
+ - [`junegunn/vim-plug`](https://github.com/junegunn/vim-plug)
210
+ - [`laravel/framework`](https://github.com/laravel/framework)
211
+ - [`lite-xl/lite-xl`](https://github.com/lite-xl/lite-xl)
212
+ - [`livewire/livewire`](https://github.com/livewire/livewire)
213
+ - [`mailcow/mailcow-dockerized`](https://github.com/mailcow/mailcow-dockerized)
214
+ - [`mason-org/mason-lspconfig.nvim`](https://github.com/mason-org/mason-lspconfig.nvim)
215
+ - [`mdn/browser-compat-data`](https://github.com/mdn/browser-compat-data)
216
+ - [`monicahq/monica`](https://github.com/monicahq/monica)
217
+ - [`neovim/nvim-lspconfig`](https://github.com/neovim/nvim-lspconfig)
218
+ - [`netdisco/netdisco`](https://github.com/netdisco/netdisco)
219
+ - [`nextcloud/all-in-one`](https://github.com/nextcloud/all-in-one)
220
+ - [`nothings/stb`](https://github.com/nothings/stb)
221
+ - [`nvim-neo-tree/neo-tree.nvim`](https://github.com/nvim-neo-tree/neo-tree.nvim)
222
+ - [`ohmyzsh/ohmyzsh`](https://github.com/ohmyzsh/ohmyzsh)
223
+ - [`open-telemetry/opentelemetry-proto`](https://github.com/open-telemetry/opentelemetry-proto)
224
+ - [`openai/tart`](https://github.com/openai/tart)
225
+ - [`openwrt/packages`](https://github.com/openwrt/packages)
226
+ - [`orbeon/orbeon-forms`](https://github.com/orbeon/orbeon-forms)
227
+ - [`phoenixframework/phoenix`](https://github.com/phoenixframework/phoenix)
228
+ - [`phoenixframework/phoenix_live_view`](https://github.com/phoenixframework/phoenix_live_view)
229
+ - [`pi-hole/pi-hole`](https://github.com/pi-hole/pi-hole)
230
+ - [`playframework/playframework`](https://github.com/playframework/playframework)
231
+ - [`preservim/nerdtree`](https://github.com/preservim/nerdtree)
232
+ - [`primefaces/primevue`](https://github.com/primefaces/primevue)
233
+ - [`pterodactyl/panel`](https://github.com/pterodactyl/panel)
234
+ - [`riscv-software-src/riscv-tests`](https://github.com/riscv-software-src/riscv-tests)
235
+ - [`rustdesk/rustdesk`](https://github.com/rustdesk/rustdesk)
236
+ - [`sherlock-project/sherlock`](https://github.com/sherlock-project/sherlock)
237
+ - [`sp00nznet/ps3recomp`](https://github.com/sp00nznet/ps3recomp)
238
+ - [`spring-projects/spring-boot`](https://github.com/spring-projects/spring-boot)
239
+ - [`stashapp/CommunityScrapers`](https://github.com/stashapp/CommunityScrapers)
240
+ - [`termux/termux-x11`](https://github.com/termux/termux-x11)
241
+ - [`traccar/traccar`](https://github.com/traccar/traccar)
242
+ - [`ublue-os/bazzite`](https://github.com/ublue-os/bazzite)
243
+ - [`vim-airline/vim-airline`](https://github.com/vim-airline/vim-airline)
244
+ - **Pipeline**: [`pr_diff`](https://github.com/huggingface/Repo2RLEnv/blob/main/docs/pipelines/pr_diff.md)
245
+ - **Tasks**: 10000
246
+ - **Visibility**: public
247
+ - **Spec**: Harbor task format with the `[metadata.repo2env]` extension
248
+
249
+ ## How it was generated
250
+
251
+ Each task in this dataset was produced by the [`pr_diff` pipeline](https://github.com/huggingface/Repo2RLEnv/blob/main/docs/pipelines/pr_diff.md). The pipeline mines real merged pull requests / commits from the source repo(s), applies quality filters, strips information-leakage from the instruction text, and emits a [Harbor](https://github.com/harbor-framework/harbor)-shaped task directory with the gold patch as the oracle.
252
+
253
+ Reproduce locally:
254
+
255
+ ```bash
256
+ pip install repo2rlenv
257
+ repo2rlenv generate \
258
+ --repo <owner>/<repo> \
259
+ --pipeline pr_diff \
260
+ --pipeline-opt limit=10 \
261
+ --out ./datasets/my-pr_diff
262
+ ```
263
+
264
+ See the [pipeline docs](https://github.com/huggingface/Repo2RLEnv/blob/main/docs/pipelines/pr_diff.md) for the full option list + reward design.
265
+
266
+ ## Run with Harbor
267
+
268
+ Each task ships a `environment/Dockerfile` and `tests/test.sh`, so you can
269
+ score patches end-to-end:
270
+
271
+ ```bash
272
+ # Pull the dataset locally
273
+ repo2rlenv pull scalingX/github-trending-environments-10k /tmp/github-trending-environments-10k
274
+
275
+ # Confirm structural soundness — oracle adapter applies the gold patch
276
+ # and must score reward = 1.000
277
+ harbor run -p /tmp/github-trending-environments-10k -a oracle --env docker
278
+
279
+ # Score an agent (claude-code + Sonnet 4.6)
280
+ harbor run \
281
+ -p /tmp/github-trending-environments-10k \
282
+ -a claude-code -m anthropic/claude-sonnet-4-6 \
283
+ --ak max_budget_usd=2.00 \
284
+ --ae ANTHROPIC_API_KEY=$ANTHROPIC_API_KEY \
285
+ --env docker
286
+ ```
287
+ The reward is a **6-component diff-similarity** score (format / size / file-targeting / region-overlap / changes-only similarity / LLM-judge). The `--ve ANTHROPIC_API_KEY=...` verifier-env pass enables the LLM-judge component (or `--ve R2E_JUDGE_ENDPOINT=...` plus `--ve R2E_JUDGE_MODEL=...` to use a self-hosted judge); without either, the current verifier marks the run `ungraded`, writes no reward file (Harbor reports `VERIFIER_FAILED`, so RL consumers drop it) and keeps `diagnostic_similarity` for inspection. Older task bundles may still renormalize weights; inspect their embedded verifier. Full breakdown in `/logs/verifier/reward-details.json`.
288
+
289
+ ## Reward signal
290
+
291
+ The reward function is part of the task itself (`tests/test.sh` + the
292
+ verifier code baked into the image). The full per-task breakdown is
293
+ written to `/logs/verifier/reward-details.json` at run time — useful for slicing
294
+ training data by component.
295
+
296
+ See the [pipeline doc](https://github.com/huggingface/Repo2RLEnv/blob/main/docs/pipelines/pr_diff.md#multi-component-reward) for the component-by-component design.
297
+
298
+ ## Layout
299
+
300
+ ```
301
+ tasks/
302
+ └── <task-id>/
303
+ ├── task.toml # Harbor task with [metadata.repo2env]
304
+ ├── instruction.md # natural-language prompt
305
+ ├── solution/
306
+ │ ├── patch.diff # oracle (gold) diff
307
+ │ └── solve.sh # oracle adapter applies patch.diff
308
+ ├── environment/
309
+ │ └── Dockerfile # builds the task's container
310
+ └── tests/
311
+ └── test.sh # verifier — writes /logs/verifier/reward.txt
312
+ ```
313
+
314
+ ## License
315
+
316
+ Apache-2.0 — same as Repo2RLEnv itself. The original PR contents remain
317
+ under their respective source-repo licenses; this dataset redistributes
318
+ public commits under fair-use for ML research / training-data purposes.
manifest.json ADDED
The diff for this file is too large to render. See raw diff
 
tasks/1sdv__TripStar-15/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/1sdv/TripStar.git /workspace; \
16
+ else \
17
+ git clone --filter=blob:none https://github.com/1sdv/TripStar.git /workspace; \
18
+ fi \
19
+ && git -C /workspace remote set-url origin https://github.com/1sdv/TripStar.git
20
+ WORKDIR /workspace
21
+ RUN git fetch --depth 1 origin 41560f7b2b0525ff366e33bf8c807f11a7cd7762 2>/dev/null \
22
+ || git fetch --unshallow origin 2>/dev/null || true
23
+ RUN git reset --hard 41560f7b2b0525ff366e33bf8c807f11a7cd7762 \
24
+ && git clean -fdx -e .venv -e venv -e __pycache__
25
+ RUN git checkout -q -B base 41560f7b2b0525ff366e33bf8c807f11a7cd7762 \
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/1sdv__TripStar-15/instruction.md ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Issue
2
+
3
+ **Title:** fix: optimize poi photo loading
4
+
5
+ ## Description
6
+
7
+ ## Summary
8
+ - switch Unsplash photo fetching to async `httpx` requests
9
+ - reuse a long-lived HTTP client with lightweight query caching
10
+ - close the shared client during FastAPI shutdown
11
+ - de-duplicate attraction photo requests on the result page and limit client-side concurrency
12
+
13
+ ## Verification
14
+ - `python3 -m compileall backend/app`
15
+ - `npm run build` currently fails because of pre-existing unused variables in `frontend/src/App.vue` (`year`, `isLandingRoute`)
16
+
17
+ ## Task
18
+
19
+ Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `41560f7b2b05`. Edit files 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/1sdv__TripStar-15/solution/patch.diff ADDED
@@ -0,0 +1,285 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/backend/app/api/main.py b/backend/app/api/main.py
2
+ index a263028..563900f 100644
3
+ --- a/backend/app/api/main.py
4
+ +++ b/backend/app/api/main.py
5
+ @@ -7,6 +7,7 @@
6
+ from fastapi.staticfiles import StaticFiles
7
+ from fastapi.responses import FileResponse
8
+ from ..config import get_settings, validate_config, print_config
9
+ +from ..services.unsplash_service import close_unsplash_service
10
+ from .routes import trip, poi, map as map_routes, chat
11
+
12
+ # 获取配置
13
+ @@ -65,6 +66,7 @@ async def startup_event():
14
+ @app.on_event("shutdown")
15
+ async def shutdown_event():
16
+ """应用关闭事件"""
17
+ + await close_unsplash_service()
18
+ print("\n" + "="*60)
19
+ print("👋 应用正在关闭...")
20
+ print("="*60 + "\n")
21
+ @@ -121,4 +123,3 @@ async def serve_spa(full_path: str):
22
+ port=settings.port,
23
+ reload=True
24
+ )
25
+ -
26
+ diff --git a/backend/app/api/routes/poi.py b/backend/app/api/routes/poi.py
27
+ index d000506..5838557 100644
28
+ --- a/backend/app/api/routes/poi.py
29
+ +++ b/backend/app/api/routes/poi.py
30
+ @@ -113,7 +113,7 @@ async def get_attraction_photo(name: str, city: Optional[str] = None):
31
+
32
+ # 尝试 1: 景点拼音 + China
33
+ query_attraction = f"{pinyin_name} China"
34
+ - photo_url = unsplash_service.get_photo_url(query_attraction)
35
+ + photo_url = await unsplash_service.get_photo_url(query_attraction)
36
+
37
+ if not photo_url:
38
+ # 尝试 2: 如果有城市参数,使用真实的城市拼音做兜底
39
+ @@ -127,11 +127,11 @@ async def get_attraction_photo(name: str, city: Optional[str] = None):
40
+ city_pinyin = "".join([p[0] for p in city_pinyin_list])
41
+
42
+ query_city = f"{city_pinyin} China landmark"
43
+ - photo_url = unsplash_service.get_photo_url(query_city, randomize=True)
44
+ + photo_url = await unsplash_service.get_photo_url(query_city, randomize=True)
45
+
46
+ if not photo_url:
47
+ # 尝试 3: 最泛的兜底,保证一定有图
48
+ - photo_url = unsplash_service.get_photo_url("beautiful ancient architecture China", randomize=True)
49
+ + photo_url = await unsplash_service.get_photo_url("beautiful ancient architecture China", randomize=True)
50
+
51
+ return {
52
+ "success": True,
53
+ @@ -148,4 +148,3 @@ async def get_attraction_photo(name: str, city: Optional[str] = None):
54
+ status_code=500,
55
+ detail=f"获取景点图片失败: {str(e)}"
56
+ )
57
+ -
58
+ diff --git a/backend/app/services/unsplash_service.py b/backend/app/services/unsplash_service.py
59
+ index e905a68..0e0f87d 100644
60
+ --- a/backend/app/services/unsplash_service.py
61
+ +++ b/backend/app/services/unsplash_service.py
62
+ @@ -1,43 +1,84 @@
63
+ """Unsplash图片服务"""
64
+
65
+ -import requests
66
+ -from typing import List, Optional
67
+ +import asyncio
68
+ +import random
69
+ +import time
70
+ +from typing import Dict, List, Optional, Tuple
71
+ +
72
+ +import httpx
73
+ +
74
+ from ..config import get_settings
75
+
76
+ class UnsplashService:
77
+ """Unsplash图片服务类"""
78
+ -
79
+ +
80
+ def __init__(self):
81
+ """初始化服务"""
82
+ settings = get_settings()
83
+ self.access_key = settings.unsplash_access_key
84
+ self.base_url = "https://api.unsplash.com"
85
+ -
86
+ - def search_photos(self, query: str, per_page: int = 5) -> List[dict]:
87
+ + self.timeout = 10.0
88
+ + self.cache_ttl_seconds = 900.0
89
+ + self._search_cache: Dict[Tuple[str, int], Tuple[float, List[dict]]] = {}
90
+ + self._request_semaphore = asyncio.Semaphore(5)
91
+ + self._cache_lock = asyncio.Lock()
92
+ + self._client = httpx.AsyncClient(timeout=self.timeout)
93
+ +
94
+ + async def _get_cached_search(self, cache_key: Tuple[str, int]) -> Optional[List[dict]]:
95
+ + async with self._cache_lock:
96
+ + cached = self._search_cache.get(cache_key)
97
+ + if not cached:
98
+ + return None
99
+ +
100
+ + expires_at, data = cached
101
+ + if expires_at <= time.monotonic():
102
+ + self._search_cache.pop(cache_key, None)
103
+ + return None
104
+ +
105
+ + return [dict(photo) for photo in data]
106
+ +
107
+ + async def _set_cached_search(self, cache_key: Tuple[str, int], photos: List[dict]) -> None:
108
+ + async with self._cache_lock:
109
+ + self._search_cache[cache_key] = (
110
+ + time.monotonic() + self.cache_ttl_seconds,
111
+ + [dict(photo) for photo in photos],
112
+ + )
113
+ +
114
+ + async def search_photos(self, query: str, per_page: int = 5) -> List[dict]:
115
+ """
116
+ 搜索图片
117
+ -
118
+ +
119
+ Args:
120
+ query: 搜索关键词
121
+ per_page: 每页数量
122
+ -
123
+ +
124
+ Returns:
125
+ 图片列表
126
+ """
127
+ + normalized_query = query.strip()
128
+ + if not normalized_query or not self.access_key:
129
+ + return []
130
+ +
131
+ + cache_key = (normalized_query.lower(), per_page)
132
+ + cached = await self._get_cached_search(cache_key)
133
+ + if cached is not None:
134
+ + return cached
135
+ +
136
+ try:
137
+ url = f"{self.base_url}/search/photos"
138
+ params = {
139
+ - "query": query,
140
+ + "query": normalized_query,
141
+ "per_page": per_page,
142
+ "client_id": self.access_key
143
+ }
144
+ -
145
+ - response = requests.get(url, params=params, timeout=10)
146
+ - response.raise_for_status()
147
+ -
148
+ - data = response.json()
149
+ +
150
+ + async with self._request_semaphore:
151
+ + response = await self._client.get(url, params=params)
152
+ + response.raise_for_status()
153
+ + data = response.json()
154
+ +
155
+ results = data.get("results", [])
156
+ -
157
+ +
158
+ # 提取图片URL
159
+ photos = []
160
+ for photo in results:
161
+ @@ -48,14 +89,15 @@ def search_photos(self, query: str, per_page: int = 5) -> List[dict]:
162
+ "description": photo.get("description") or photo.get("alt_description"),
163
+ "photographer": photo.get("user", {}).get("name")
164
+ })
165
+ -
166
+ +
167
+ + await self._set_cached_search(cache_key, photos)
168
+ return photos
169
+ -
170
+ +
171
+ except Exception as e:
172
+ print(f"❌ Unsplash搜索失败: {str(e)}")
173
+ return []
174
+ -
175
+ - def get_photo_url(self, query: str, randomize: bool = False) -> Optional[str]:
176
+ +
177
+ + async def get_photo_url(self, query: str, randomize: bool = False) -> Optional[str]:
178
+ """
179
+ 获取单张图片URL
180
+
181
+ @@ -66,14 +108,17 @@ def get_photo_url(self, query: str, randomize: bool = False) -> Optional[str]:
182
+ Returns:
183
+ 图片URL
184
+ """
185
+ - import random
186
+ - photos = self.search_photos(query, per_page=10 if randomize else 1)
187
+ + photos = await self.search_photos(query, per_page=10 if randomize else 1)
188
+ if photos:
189
+ if randomize:
190
+ return random.choice(photos).get("url")
191
+ return photos[0].get("url")
192
+ return None
193
+
194
+ + async def close(self) -> None:
195
+ + """关闭底层HTTP客户端"""
196
+ + await self._client.aclose()
197
+ +
198
+
199
+ # 全局服务实例
200
+ _unsplash_service = None
201
+ @@ -88,3 +133,11 @@ def get_unsplash_service() -> UnsplashService:
202
+
203
+ return _unsplash_service
204
+
205
+ +
206
+ +async def close_unsplash_service() -> None:
207
+ + """关闭Unsplash服务实例"""
208
+ + global _unsplash_service
209
+ +
210
+ + if _unsplash_service is not None:
211
+ + await _unsplash_service.close()
212
+ + _unsplash_service = None
213
+ diff --git a/frontend/src/views/Result.vue b/frontend/src/views/Result.vue
214
+ index 6a79da5..3ff8c0a 100644
215
+ --- a/frontend/src/views/Result.vue
216
+ +++ b/frontend/src/views/Result.vue
217
+ @@ -1673,27 +1673,44 @@ const restoreBudgetItem = (pendingItem: BudgetRestoreItem) => {
218
+ const loadAttractionPhotos = async () => {
219
+ if (!tripPlan.value) return
220
+
221
+ - const promises: Promise<void>[] = []
222
+ const apiBase = import.meta.env.VITE_API_BASE_URL ?? ''
223
+ + const city = tripPlan.value.city
224
+ + const uniqueNames = Array.from(
225
+ + new Set(
226
+ + tripPlan.value.days.flatMap((day) => day.attractions.map((attraction) => attraction.name))
227
+ + )
228
+ + ).filter((name) => name && !attractionPhotos.value[name])
229
+ +
230
+ + if (uniqueNames.length === 0) return
231
+ +
232
+ + const concurrencyLimit = 4
233
+ + let currentIndex = 0
234
+ +
235
+ + const loadNextPhoto = async () => {
236
+ + while (currentIndex < uniqueNames.length) {
237
+ + const index = currentIndex
238
+ + currentIndex += 1
239
+ + const name = uniqueNames[index]
240
+ +
241
+ + try {
242
+ + const response = await fetch(
243
+ + `${apiBase}/api/poi/photo?name=${encodeURIComponent(name)}&city=${encodeURIComponent(city)}`
244
+ + )
245
+ + const data = await response.json()
246
+ + if (data.success && data.data.photo_url) {
247
+ + attractionPhotos.value[name] = data.data.photo_url
248
+ + }
249
+ + } catch (err) {
250
+ + console.error(`获取${name}图片失败:`, err)
251
+ + }
252
+ + }
253
+ + }
254
+
255
+ - tripPlan.value.days.forEach(day => {
256
+ - day.attractions.forEach(attraction => {
257
+ - const promise = fetch(`${apiBase}/api/poi/photo?name=${encodeURIComponent(attraction.name)}&city=${encodeURIComponent(tripPlan.value.city)}`)
258
+ - .then(res => res.json())
259
+ - .then(data => {
260
+ - if (data.success && data.data.photo_url) {
261
+ - attractionPhotos.value[attraction.name] = data.data.photo_url
262
+ - }
263
+ - })
264
+ - .catch(err => {
265
+ - console.error(`获取${attraction.name}图片失败:`, err)
266
+ - })
267
+ -
268
+ - promises.push(promise)
269
+ - })
270
+ - })
271
+ -
272
+ - await Promise.all(promises)
273
+ + const workers = Array.from(
274
+ + { length: Math.min(concurrencyLimit, uniqueNames.length) },
275
+ + () => loadNextPhoto()
276
+ + )
277
+ + await Promise.all(workers)
278
+ }
279
+
280
+ // 获取景点图片
281
+ @@ -4170,4 +4187,3 @@ const drawRoutes = async (AMap: any, attractions: any[]): Promise<any[]> => {
282
+ display: none !important;
283
+ }
284
+ </style>
285
+ -
tasks/1sdv__TripStar-15/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/1sdv__TripStar-15/task.toml ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version = "1.0"
2
+
3
+ [task]
4
+ name = "trending/1sdv__TripStar-15"
5
+ description = "fix: optimize poi photo loading"
6
+
7
+ [metadata]
8
+ difficulty = "large"
9
+ category = "bugfix"
10
+ keywords = [
11
+ "TripStar",
12
+ "pr_diff",
13
+ ]
14
+
15
+ [metadata.repo2env]
16
+ pipeline = "pr_diff"
17
+ pipeline_version = "0.3.0"
18
+ repo = "1sdv/TripStar"
19
+ ref = "41560f7b2b0525ff366e33bf8c807f11a7cd7762"
20
+ reference = "https://github.com/1sdv/TripStar/pull/15"
21
+ source_access = "auto"
22
+ built_at = "2026-11-16T16:09:43.785111+00:00"
23
+ reward_kinds = [
24
+ "diff_similarity",
25
+ ]
26
+ spec_version = "0.2.0"
27
+ content_hash = "sha256:32b17713074f3e95230b3c0b6b5dfd0998c5daec48f15d2f3d693bfe2420f690"
28
+
29
+ [metadata.repo2env.pr_diff]
30
+ pr_merged_at = "2026-03-30T06:27:32Z"
31
+ diff_format = "unified"
32
+ context_files = [
33
+ "backend/app/api/main.py",
34
+ "backend/app/api/routes/poi.py",
35
+ "backend/app/services/unsplash_service.py",
36
+ "frontend/src/views/Result.vue",
37
+ ]
38
+ bootstrap_image = "python:3.12-slim"
39
+
40
+ [metadata.repo2env.reward_calibration]
41
+ baseline_reward = 0.0
42
+ loc_changed = 159
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:19:57.788236+00:00"
62
+ pushed_by = "scalingX"
63
+ inline_recipe_sha256 = "sha256:a922c76a977e8e6fac250e4942f2383cf6737befcd542a56574f496b332aeeb5"
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/1sdv__TripStar-15/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/1sdv__TripStar-15/tests/instruction.md ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Issue
2
+
3
+ **Title:** fix: optimize poi photo loading
4
+
5
+ ## Description
6
+
7
+ ## Summary
8
+ - switch Unsplash photo fetching to async `httpx` requests
9
+ - reuse a long-lived HTTP client with lightweight query caching
10
+ - close the shared client during FastAPI shutdown
11
+ - de-duplicate attraction photo requests on the result page and limit client-side concurrency
12
+
13
+ ## Verification
14
+ - `python3 -m compileall backend/app`
15
+ - `npm run build` currently fails because of pre-existing unused variables in `frontend/src/App.vue` (`year`, `isLandingRoute`)
16
+
17
+ ## Task
18
+
19
+ Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `41560f7b2b05`. Edit files 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/1sdv__TripStar-15/tests/oracle.patch ADDED
@@ -0,0 +1,285 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/backend/app/api/main.py b/backend/app/api/main.py
2
+ index a263028..563900f 100644
3
+ --- a/backend/app/api/main.py
4
+ +++ b/backend/app/api/main.py
5
+ @@ -7,6 +7,7 @@
6
+ from fastapi.staticfiles import StaticFiles
7
+ from fastapi.responses import FileResponse
8
+ from ..config import get_settings, validate_config, print_config
9
+ +from ..services.unsplash_service import close_unsplash_service
10
+ from .routes import trip, poi, map as map_routes, chat
11
+
12
+ # 获取配置
13
+ @@ -65,6 +66,7 @@ async def startup_event():
14
+ @app.on_event("shutdown")
15
+ async def shutdown_event():
16
+ """应用关闭事件"""
17
+ + await close_unsplash_service()
18
+ print("\n" + "="*60)
19
+ print("👋 应用正在关闭...")
20
+ print("="*60 + "\n")
21
+ @@ -121,4 +123,3 @@ async def serve_spa(full_path: str):
22
+ port=settings.port,
23
+ reload=True
24
+ )
25
+ -
26
+ diff --git a/backend/app/api/routes/poi.py b/backend/app/api/routes/poi.py
27
+ index d000506..5838557 100644
28
+ --- a/backend/app/api/routes/poi.py
29
+ +++ b/backend/app/api/routes/poi.py
30
+ @@ -113,7 +113,7 @@ async def get_attraction_photo(name: str, city: Optional[str] = None):
31
+
32
+ # 尝试 1: 景点拼音 + China
33
+ query_attraction = f"{pinyin_name} China"
34
+ - photo_url = unsplash_service.get_photo_url(query_attraction)
35
+ + photo_url = await unsplash_service.get_photo_url(query_attraction)
36
+
37
+ if not photo_url:
38
+ # 尝试 2: 如果有城市参数,使用真实的城市拼音做兜底
39
+ @@ -127,11 +127,11 @@ async def get_attraction_photo(name: str, city: Optional[str] = None):
40
+ city_pinyin = "".join([p[0] for p in city_pinyin_list])
41
+
42
+ query_city = f"{city_pinyin} China landmark"
43
+ - photo_url = unsplash_service.get_photo_url(query_city, randomize=True)
44
+ + photo_url = await unsplash_service.get_photo_url(query_city, randomize=True)
45
+
46
+ if not photo_url:
47
+ # 尝试 3: 最泛的兜底,保证一定有图
48
+ - photo_url = unsplash_service.get_photo_url("beautiful ancient architecture China", randomize=True)
49
+ + photo_url = await unsplash_service.get_photo_url("beautiful ancient architecture China", randomize=True)
50
+
51
+ return {
52
+ "success": True,
53
+ @@ -148,4 +148,3 @@ async def get_attraction_photo(name: str, city: Optional[str] = None):
54
+ status_code=500,
55
+ detail=f"获取景点图片失败: {str(e)}"
56
+ )
57
+ -
58
+ diff --git a/backend/app/services/unsplash_service.py b/backend/app/services/unsplash_service.py
59
+ index e905a68..0e0f87d 100644
60
+ --- a/backend/app/services/unsplash_service.py
61
+ +++ b/backend/app/services/unsplash_service.py
62
+ @@ -1,43 +1,84 @@
63
+ """Unsplash图片服务"""
64
+
65
+ -import requests
66
+ -from typing import List, Optional
67
+ +import asyncio
68
+ +import random
69
+ +import time
70
+ +from typing import Dict, List, Optional, Tuple
71
+ +
72
+ +import httpx
73
+ +
74
+ from ..config import get_settings
75
+
76
+ class UnsplashService:
77
+ """Unsplash图片服务类"""
78
+ -
79
+ +
80
+ def __init__(self):
81
+ """初始化服务"""
82
+ settings = get_settings()
83
+ self.access_key = settings.unsplash_access_key
84
+ self.base_url = "https://api.unsplash.com"
85
+ -
86
+ - def search_photos(self, query: str, per_page: int = 5) -> List[dict]:
87
+ + self.timeout = 10.0
88
+ + self.cache_ttl_seconds = 900.0
89
+ + self._search_cache: Dict[Tuple[str, int], Tuple[float, List[dict]]] = {}
90
+ + self._request_semaphore = asyncio.Semaphore(5)
91
+ + self._cache_lock = asyncio.Lock()
92
+ + self._client = httpx.AsyncClient(timeout=self.timeout)
93
+ +
94
+ + async def _get_cached_search(self, cache_key: Tuple[str, int]) -> Optional[List[dict]]:
95
+ + async with self._cache_lock:
96
+ + cached = self._search_cache.get(cache_key)
97
+ + if not cached:
98
+ + return None
99
+ +
100
+ + expires_at, data = cached
101
+ + if expires_at <= time.monotonic():
102
+ + self._search_cache.pop(cache_key, None)
103
+ + return None
104
+ +
105
+ + return [dict(photo) for photo in data]
106
+ +
107
+ + async def _set_cached_search(self, cache_key: Tuple[str, int], photos: List[dict]) -> None:
108
+ + async with self._cache_lock:
109
+ + self._search_cache[cache_key] = (
110
+ + time.monotonic() + self.cache_ttl_seconds,
111
+ + [dict(photo) for photo in photos],
112
+ + )
113
+ +
114
+ + async def search_photos(self, query: str, per_page: int = 5) -> List[dict]:
115
+ """
116
+ 搜索图片
117
+ -
118
+ +
119
+ Args:
120
+ query: 搜索关键词
121
+ per_page: 每页数量
122
+ -
123
+ +
124
+ Returns:
125
+ 图片列表
126
+ """
127
+ + normalized_query = query.strip()
128
+ + if not normalized_query or not self.access_key:
129
+ + return []
130
+ +
131
+ + cache_key = (normalized_query.lower(), per_page)
132
+ + cached = await self._get_cached_search(cache_key)
133
+ + if cached is not None:
134
+ + return cached
135
+ +
136
+ try:
137
+ url = f"{self.base_url}/search/photos"
138
+ params = {
139
+ - "query": query,
140
+ + "query": normalized_query,
141
+ "per_page": per_page,
142
+ "client_id": self.access_key
143
+ }
144
+ -
145
+ - response = requests.get(url, params=params, timeout=10)
146
+ - response.raise_for_status()
147
+ -
148
+ - data = response.json()
149
+ +
150
+ + async with self._request_semaphore:
151
+ + response = await self._client.get(url, params=params)
152
+ + response.raise_for_status()
153
+ + data = response.json()
154
+ +
155
+ results = data.get("results", [])
156
+ -
157
+ +
158
+ # 提取图片URL
159
+ photos = []
160
+ for photo in results:
161
+ @@ -48,14 +89,15 @@ def search_photos(self, query: str, per_page: int = 5) -> List[dict]:
162
+ "description": photo.get("description") or photo.get("alt_description"),
163
+ "photographer": photo.get("user", {}).get("name")
164
+ })
165
+ -
166
+ +
167
+ + await self._set_cached_search(cache_key, photos)
168
+ return photos
169
+ -
170
+ +
171
+ except Exception as e:
172
+ print(f"❌ Unsplash搜索失败: {str(e)}")
173
+ return []
174
+ -
175
+ - def get_photo_url(self, query: str, randomize: bool = False) -> Optional[str]:
176
+ +
177
+ + async def get_photo_url(self, query: str, randomize: bool = False) -> Optional[str]:
178
+ """
179
+ 获取单张图片URL
180
+
181
+ @@ -66,14 +108,17 @@ def get_photo_url(self, query: str, randomize: bool = False) -> Optional[str]:
182
+ Returns:
183
+ 图片URL
184
+ """
185
+ - import random
186
+ - photos = self.search_photos(query, per_page=10 if randomize else 1)
187
+ + photos = await self.search_photos(query, per_page=10 if randomize else 1)
188
+ if photos:
189
+ if randomize:
190
+ return random.choice(photos).get("url")
191
+ return photos[0].get("url")
192
+ return None
193
+
194
+ + async def close(self) -> None:
195
+ + """关闭底层HTTP客户端"""
196
+ + await self._client.aclose()
197
+ +
198
+
199
+ # 全局服务实例
200
+ _unsplash_service = None
201
+ @@ -88,3 +133,11 @@ def get_unsplash_service() -> UnsplashService:
202
+
203
+ return _unsplash_service
204
+
205
+ +
206
+ +async def close_unsplash_service() -> None:
207
+ + """关闭Unsplash服务实例"""
208
+ + global _unsplash_service
209
+ +
210
+ + if _unsplash_service is not None:
211
+ + await _unsplash_service.close()
212
+ + _unsplash_service = None
213
+ diff --git a/frontend/src/views/Result.vue b/frontend/src/views/Result.vue
214
+ index 6a79da5..3ff8c0a 100644
215
+ --- a/frontend/src/views/Result.vue
216
+ +++ b/frontend/src/views/Result.vue
217
+ @@ -1673,27 +1673,44 @@ const restoreBudgetItem = (pendingItem: BudgetRestoreItem) => {
218
+ const loadAttractionPhotos = async () => {
219
+ if (!tripPlan.value) return
220
+
221
+ - const promises: Promise<void>[] = []
222
+ const apiBase = import.meta.env.VITE_API_BASE_URL ?? ''
223
+ + const city = tripPlan.value.city
224
+ + const uniqueNames = Array.from(
225
+ + new Set(
226
+ + tripPlan.value.days.flatMap((day) => day.attractions.map((attraction) => attraction.name))
227
+ + )
228
+ + ).filter((name) => name && !attractionPhotos.value[name])
229
+ +
230
+ + if (uniqueNames.length === 0) return
231
+ +
232
+ + const concurrencyLimit = 4
233
+ + let currentIndex = 0
234
+ +
235
+ + const loadNextPhoto = async () => {
236
+ + while (currentIndex < uniqueNames.length) {
237
+ + const index = currentIndex
238
+ + currentIndex += 1
239
+ + const name = uniqueNames[index]
240
+ +
241
+ + try {
242
+ + const response = await fetch(
243
+ + `${apiBase}/api/poi/photo?name=${encodeURIComponent(name)}&city=${encodeURIComponent(city)}`
244
+ + )
245
+ + const data = await response.json()
246
+ + if (data.success && data.data.photo_url) {
247
+ + attractionPhotos.value[name] = data.data.photo_url
248
+ + }
249
+ + } catch (err) {
250
+ + console.error(`获取${name}图片失败:`, err)
251
+ + }
252
+ + }
253
+ + }
254
+
255
+ - tripPlan.value.days.forEach(day => {
256
+ - day.attractions.forEach(attraction => {
257
+ - const promise = fetch(`${apiBase}/api/poi/photo?name=${encodeURIComponent(attraction.name)}&city=${encodeURIComponent(tripPlan.value.city)}`)
258
+ - .then(res => res.json())
259
+ - .then(data => {
260
+ - if (data.success && data.data.photo_url) {
261
+ - attractionPhotos.value[attraction.name] = data.data.photo_url
262
+ - }
263
+ - })
264
+ - .catch(err => {
265
+ - console.error(`获取${attraction.name}图片失败:`, err)
266
+ - })
267
+ -
268
+ - promises.push(promise)
269
+ - })
270
+ - })
271
+ -
272
+ - await Promise.all(promises)
273
+ + const workers = Array.from(
274
+ + { length: Math.min(concurrencyLimit, uniqueNames.length) },
275
+ + () => loadNextPhoto()
276
+ + )
277
+ + await Promise.all(workers)
278
+ }
279
+
280
+ // 获取景点图片
281
+ @@ -4170,4 +4187,3 @@ const drawRoutes = async (AMap: any, attractions: any[]): Promise<any[]> => {
282
+ display: none !important;
283
+ }
284
+ </style>
285
+ -
tasks/1sdv__TripStar-15/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 41560f7b2b0525ff366e33bf8c807f11a7cd7762 > "$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/1sdv__TripStar-15/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/1sdv__TripStar-20/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/1sdv/TripStar.git /workspace; \
16
+ else \
17
+ git clone --filter=blob:none https://github.com/1sdv/TripStar.git /workspace; \
18
+ fi \
19
+ && git -C /workspace remote set-url origin https://github.com/1sdv/TripStar.git
20
+ WORKDIR /workspace
21
+ RUN git fetch --depth 1 origin cd910a4a6bcedfd12dfd98c67462f67c0b122f1c 2>/dev/null \
22
+ || git fetch --unshallow origin 2>/dev/null || true
23
+ RUN git reset --hard cd910a4a6bcedfd12dfd98c67462f67c0b122f1c \
24
+ && git clean -fdx -e .venv -e venv -e __pycache__
25
+ RUN git checkout -q -B base cd910a4a6bcedfd12dfd98c67462f67c0b122f1c \
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/1sdv__TripStar-20/instruction.md ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Issue
2
+
3
+ **Title:** feat(xhs/cookie): 支持用户填写 Json 格式的 Cookie
4
+
5
+ ## Description
6
+
7
+ ## What does this PR do?
8
+
9
+ Json 格式 Cookie 也能正常使用了
10
+
11
+ ## Why is this change needed?
12
+
13
+ 用户通过插件导出通常是 Json 格式,更方便
14
+
15
+ ## Related Issues
16
+
17
+ 无
18
+
19
+ ## Type of Change
20
+
21
+ - [x] Feature
22
+ - [ ] Bug fix
23
+ - [ ] Documentation
24
+ - [ ] Refactor
25
+ - [ ] Other
26
+
27
+ ## Testing
28
+
29
+ 人工测试通过
30
+
31
+ ## Screenshots (if applicable)
32
+
33
+ 无
34
+
35
+ ## Checklist
36
+
37
+ - [x] Code follows project style guidelines
38
+ - [x] Tests pass locally
39
+ - [x] Documentation updated (if needed)
40
+ - [x] No breaking changes introduced
41
+
42
+ ## Task
43
+
44
+ Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `cd910a4a6bce`. Edit files 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/1sdv__TripStar-20/solution/patch.diff ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/backend/.env.example b/backend/.env.example
2
+ index 0d11e26..237f290 100644
3
+ --- a/backend/.env.example
4
+ +++ b/backend/.env.example
5
+ @@ -22,8 +22,11 @@ CORS_ORIGINS=http://localhost:5173,http://localhost:3000
6
+ # 日志级别
7
+ LOG_LEVEL=INFO
8
+
9
+ -#小红薯Cookie
10
+ +# 小红书 Cookie
11
+ +# 直接填浏览器请求头中的 Cookie 字符串,例如:
12
+ +# XHS_COOKIE="a1=xxx; web_session=xxx; webId=xxx"
13
+ +# 也兼容浏览器导出的 JSON Cookie 列表/对象串,程序会自动转换。
14
+ XHS_COOKIE="这里填写您网页端登录小红书复制来的 Cookie"
15
+
16
+ # 高德地图API配置
17
+ -VITE_AMAP_WEB_KEY=your_amap_api_key_here
18
+
19
+ +VITE_AMAP_WEB_KEY=your_amap_api_key_here
20
+ diff --git a/backend/app/services/xhs_service.py b/backend/app/services/xhs_service.py
21
+ index 6748b88..9f0482c 100644
22
+ --- a/backend/app/services/xhs_service.py
23
+ +++ b/backend/app/services/xhs_service.py
24
+ @@ -19,6 +19,42 @@ class XHSCookieExpiredError(Exception):
25
+ """小红书 Cookie 过期致命异常,用于向前端报警"""
26
+ pass
27
+
28
+ +def normalize_xhs_cookie(cookie: str) -> str:
29
+ + """兼容 Cookie 请求头字符串和浏览器导出的 JSON Cookie 列表。"""
30
+ + normalized = cookie.strip()
31
+ + if not normalized:
32
+ + return normalized
33
+ +
34
+ + if len(normalized) >= 2 and normalized[0] == normalized[-1] and normalized[0] in {"'", '"'}:
35
+ + normalized = normalized[1:-1].strip()
36
+ +
37
+ + cookie_items = None
38
+ + if normalized.startswith("[") and normalized.endswith("]"):
39
+ + try:
40
+ + cookie_items = json.loads(normalized)
41
+ + except json.JSONDecodeError:
42
+ + cookie_items = None
43
+ + elif normalized.startswith("{") and '"name"' in normalized and '"value"' in normalized:
44
+ + try:
45
+ + cookie_items = json.loads(f"[{normalized}]")
46
+ + except json.JSONDecodeError:
47
+ + cookie_items = None
48
+ +
49
+ + if isinstance(cookie_items, list):
50
+ + pairs = []
51
+ + for item in cookie_items:
52
+ + if not isinstance(item, dict):
53
+ + continue
54
+ + name = str(item.get("name", "")).strip()
55
+ + value = str(item.get("value", "")).strip()
56
+ + if name:
57
+ + pairs.append(f"{name}={value}")
58
+ + if pairs:
59
+ + print("已将 JSON 格式的小红书 Cookie 转换为请求头字符串格式。")
60
+ + return "; ".join(pairs)
61
+ +
62
+ + return normalized
63
+ +
64
+ def get_xhs_client() -> XhsClient:
65
+ """初始化并验证小红书客户端"""
66
+ settings = get_settings()
67
+ @@ -28,8 +64,8 @@ def get_xhs_client() -> XhsClient:
68
+ # 添加一个空白签名函数以避免 xhs 包在没有设置签名函数时抛出 NoneType object is not callable
69
+ def dummy_sign(uri, data=None, a1="", web_session=""):
70
+ return {"x-s": "", "x-t": ""}
71
+ -
72
+ - client = XhsClient(settings.xhs_cookie, sign=dummy_sign)
73
+ +
74
+ + client = XhsClient(normalize_xhs_cookie(settings.xhs_cookie), sign=dummy_sign)
75
+ # 简单测试一下客户端有效性(调用不敏感的接口)
76
+ return client
77
+ except Exception as e:
tasks/1sdv__TripStar-20/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/1sdv__TripStar-20/task.toml ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version = "1.0"
2
+
3
+ [task]
4
+ name = "trending/1sdv__TripStar-20"
5
+ description = "feat(xhs/cookie): 支持用户填写 Json 格式的 Cookie"
6
+
7
+ [metadata]
8
+ difficulty = "medium"
9
+ category = "bugfix"
10
+ keywords = [
11
+ "TripStar",
12
+ "pr_diff",
13
+ ]
14
+
15
+ [metadata.repo2env]
16
+ pipeline = "pr_diff"
17
+ pipeline_version = "0.3.0"
18
+ repo = "1sdv/TripStar"
19
+ ref = "cd910a4a6bcedfd12dfd98c67462f67c0b122f1c"
20
+ reference = "https://github.com/1sdv/TripStar/pull/20"
21
+ source_access = "auto"
22
+ built_at = "2026-11-16T16:09:43.783544+00:00"
23
+ reward_kinds = [
24
+ "diff_similarity",
25
+ ]
26
+ spec_version = "0.2.0"
27
+ content_hash = "sha256:ca5b22d6813194cd475f2f94fd31888a8347284e2ec4e6306ba22172fa599364"
28
+
29
+ [metadata.repo2env.pr_diff]
30
+ pr_merged_at = "2026-04-05T00:19:49Z"
31
+ diff_format = "unified"
32
+ context_files = [
33
+ "backend/.env.example",
34
+ "backend/app/services/xhs_service.py",
35
+ ]
36
+ bootstrap_image = "python:3.12-slim"
37
+
38
+ [metadata.repo2env.reward_calibration]
39
+ baseline_reward = 0.0
40
+ loc_changed = 47
41
+ difficulty = "medium"
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:19:57.788940+00:00"
60
+ pushed_by = "scalingX"
61
+ inline_recipe_sha256 = "sha256:d0475f0786c1e0b4fb13a8966d50d6b29fd7b0b9997fe47c50c0a8a40b0538f0"
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/1sdv__TripStar-20/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/1sdv__TripStar-20/tests/instruction.md ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Issue
2
+
3
+ **Title:** feat(xhs/cookie): 支持用户填写 Json 格式的 Cookie
4
+
5
+ ## Description
6
+
7
+ ## What does this PR do?
8
+
9
+ Json 格式 Cookie 也能正常使用了
10
+
11
+ ## Why is this change needed?
12
+
13
+ 用户通过插件导出通常是 Json 格式,更方便
14
+
15
+ ## Related Issues
16
+
17
+ 无
18
+
19
+ ## Type of Change
20
+
21
+ - [x] Feature
22
+ - [ ] Bug fix
23
+ - [ ] Documentation
24
+ - [ ] Refactor
25
+ - [ ] Other
26
+
27
+ ## Testing
28
+
29
+ 人工测试通过
30
+
31
+ ## Screenshots (if applicable)
32
+
33
+ 无
34
+
35
+ ## Checklist
36
+
37
+ - [x] Code follows project style guidelines
38
+ - [x] Tests pass locally
39
+ - [x] Documentation updated (if needed)
40
+ - [x] No breaking changes introduced
41
+
42
+ ## Task
43
+
44
+ Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `cd910a4a6bce`. Edit files 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/1sdv__TripStar-20/tests/oracle.patch ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/backend/.env.example b/backend/.env.example
2
+ index 0d11e26..237f290 100644
3
+ --- a/backend/.env.example
4
+ +++ b/backend/.env.example
5
+ @@ -22,8 +22,11 @@ CORS_ORIGINS=http://localhost:5173,http://localhost:3000
6
+ # 日志级别
7
+ LOG_LEVEL=INFO
8
+
9
+ -#小红薯Cookie
10
+ +# 小红书 Cookie
11
+ +# 直接填浏览器请求头中的 Cookie 字符串,例如:
12
+ +# XHS_COOKIE="a1=xxx; web_session=xxx; webId=xxx"
13
+ +# 也兼容浏览器导出的 JSON Cookie 列表/对象串,程序会自动转换。
14
+ XHS_COOKIE="这里填写您网页端登录小红书复制来的 Cookie"
15
+
16
+ # 高德地图API配置
17
+ -VITE_AMAP_WEB_KEY=your_amap_api_key_here
18
+
19
+ +VITE_AMAP_WEB_KEY=your_amap_api_key_here
20
+ diff --git a/backend/app/services/xhs_service.py b/backend/app/services/xhs_service.py
21
+ index 6748b88..9f0482c 100644
22
+ --- a/backend/app/services/xhs_service.py
23
+ +++ b/backend/app/services/xhs_service.py
24
+ @@ -19,6 +19,42 @@ class XHSCookieExpiredError(Exception):
25
+ """小红书 Cookie 过期致命异常,用于向前端报警"""
26
+ pass
27
+
28
+ +def normalize_xhs_cookie(cookie: str) -> str:
29
+ + """兼容 Cookie 请求头字符串和浏览器导出的 JSON Cookie 列表。"""
30
+ + normalized = cookie.strip()
31
+ + if not normalized:
32
+ + return normalized
33
+ +
34
+ + if len(normalized) >= 2 and normalized[0] == normalized[-1] and normalized[0] in {"'", '"'}:
35
+ + normalized = normalized[1:-1].strip()
36
+ +
37
+ + cookie_items = None
38
+ + if normalized.startswith("[") and normalized.endswith("]"):
39
+ + try:
40
+ + cookie_items = json.loads(normalized)
41
+ + except json.JSONDecodeError:
42
+ + cookie_items = None
43
+ + elif normalized.startswith("{") and '"name"' in normalized and '"value"' in normalized:
44
+ + try:
45
+ + cookie_items = json.loads(f"[{normalized}]")
46
+ + except json.JSONDecodeError:
47
+ + cookie_items = None
48
+ +
49
+ + if isinstance(cookie_items, list):
50
+ + pairs = []
51
+ + for item in cookie_items:
52
+ + if not isinstance(item, dict):
53
+ + continue
54
+ + name = str(item.get("name", "")).strip()
55
+ + value = str(item.get("value", "")).strip()
56
+ + if name:
57
+ + pairs.append(f"{name}={value}")
58
+ + if pairs:
59
+ + print("已将 JSON 格式的小红书 Cookie 转换为请求头字符串格式。")
60
+ + return "; ".join(pairs)
61
+ +
62
+ + return normalized
63
+ +
64
+ def get_xhs_client() -> XhsClient:
65
+ """初始化并验证小红书客户端"""
66
+ settings = get_settings()
67
+ @@ -28,8 +64,8 @@ def get_xhs_client() -> XhsClient:
68
+ # 添加一个空白签名函数以避免 xhs 包在没有设置签名函数时抛出 NoneType object is not callable
69
+ def dummy_sign(uri, data=None, a1="", web_session=""):
70
+ return {"x-s": "", "x-t": ""}
71
+ -
72
+ - client = XhsClient(settings.xhs_cookie, sign=dummy_sign)
73
+ +
74
+ + client = XhsClient(normalize_xhs_cookie(settings.xhs_cookie), sign=dummy_sign)
75
+ # 简单测试一下客户端有效性(调用不敏感的接口)
76
+ return client
77
+ except Exception as e:
tasks/1sdv__TripStar-20/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 cd910a4a6bcedfd12dfd98c67462f67c0b122f1c > "$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/1sdv__TripStar-20/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/1sdv__TripStar-21/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/1sdv/TripStar.git /workspace; \
16
+ else \
17
+ git clone --filter=blob:none https://github.com/1sdv/TripStar.git /workspace; \
18
+ fi \
19
+ && git -C /workspace remote set-url origin https://github.com/1sdv/TripStar.git
20
+ WORKDIR /workspace
21
+ RUN git fetch --depth 1 origin e2b62da04cb8ab41b4c681bcfeb29a6535fc68b3 2>/dev/null \
22
+ || git fetch --unshallow origin 2>/dev/null || true
23
+ RUN git reset --hard e2b62da04cb8ab41b4c681bcfeb29a6535fc68b3 \
24
+ && git clean -fdx -e .venv -e venv -e __pycache__
25
+ RUN git checkout -q -B base e2b62da04cb8ab41b4c681bcfeb29a6535fc68b3 \
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/1sdv__TripStar-21/instruction.md ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Issue
2
+
3
+ **Title:** feat(docker): 采用容器环境变量作为运行时配置
4
+
5
+ ## Description
6
+
7
+ ## 变更说明
8
+
9
+ Docker 部署采用容器环境变量作为后端运行时配置来源:
10
+
11
+ - 镜像构建时忽略 `backend/.env`、`frontend/.env` 等本地配置文件
12
+ - `docker-compose.yaml` 中的 `environment` 是配置入口
13
+ - 本地开发仍可使用 `.env` 文件
14
+
15
+ ## 文件变更
16
+
17
+ - `.dockerignore`: 忽略 .env 文件不打入镜像
18
+ - `README.md`: 添加 Docker/Compose 配置约定说明
19
+ - `backend/app/api/main.py`: 更新环境变量配置提示
20
+ - `backend/app/services/amap_service.py`: 更新 API Key 配置提示
21
+ - `start.sh`: 移除 .env 导出逻辑
22
+
23
+ ## 测试计划
24
+
25
+ - [x] 本地开发使用 .env 仍正常工作
26
+ - [ ] Docker 部署使用容器环境变量正常工作
27
+
28
+ ## Task
29
+
30
+ Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e2b62da04cb8`. Edit files 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/1sdv__TripStar-21/solution/patch.diff ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/.dockerignore b/.dockerignore
2
+ index c502ec8..7e58465 100644
3
+ --- a/.dockerignore
4
+ +++ b/.dockerignore
5
+ @@ -6,6 +6,9 @@ __pycache__
6
+ .git
7
+ .gitignore
8
+ .env
9
+ +backend/.env
10
+ +frontend/.env
11
+ +frontend/.env.*
12
+ *.md
13
+ MiroFish-main
14
+ .vscode
15
+ diff --git a/README.md b/README.md
16
+ index de9f0b0..16593df 100644
17
+ --- a/README.md
18
+ +++ b/README.md
19
+ @@ -137,7 +137,20 @@ graph TD
20
+ * 小红书Cookie([小红书](https://www.xiaohongshu.com/) 网页端登录后从浏览器开发者工具复制)
21
+ * 安装 `uv` 包管理器
22
+
23
+ -### 1. 后端启动
24
+ +### Docker / Compose 配置约定
25
+ +
26
+ +Docker 部署采用容器环境变量作为后端运行时配置来源:
27
+ +
28
+ +* 容器启动时不再读取项目目录里的 `backend/.env`
29
+ +* 镜像构建时会忽略 `backend/.env`、`frontend/.env`、`frontend/.env.*`
30
+ +* `docker-compose.yaml` 中显式列出的 `environment` 仍然是后端运行时配置入口
31
+ +* 前端构建期变量 `VITE_AMAP_WEB_JS_KEY` 继续通过 `build.args` 注入
32
+ +
33
+ +本地开发仍可按下面步骤使用 `backend/.env` 和 `frontend/.env`。
34
+ +
35
+ +### 本地开发
36
+ +
37
+ +#### 1. 后端启动
38
+
39
+ ```bash
40
+ # 进入后端主目录
41
+ @@ -164,7 +177,7 @@ uvicorn app.api.main:app --host 0.0.0.0 --port 8000 --reload
42
+
43
+ API 启动后,您可以访问 `http://localhost:8000/docs` 查看互动文档。
44
+
45
+ -### 2. 前端启动
46
+ +#### 2. 前端启动
47
+
48
+ ```bash
49
+ # 进入前端主目录
50
+ @@ -199,7 +212,7 @@ TripStar/
51
+ │ │ │ ├── llm_service.py # LLM 客户端封装
52
+ │ │ │ └── knowledge_graph_service.py # 知识图谱构建
53
+ │ │ └── models/ # Pydantic 类型定义 (schemas.py)
54
+ -│ └── .env # LLM 及系统环境变量载体
55
+ +│ └── .env # 本地开发环境变量载体(Docker 部署时不打进镜像)
56
+ │
57
+ ├── frontend/ # Vue 3 互动前端
58
+ │ ├── src/
59
+ @@ -207,6 +220,7 @@ TripStar/
60
+ │ │ ├── components/ # 独立复用的 UI / 背景组件
61
+ │ │ └── services/ # Axios 异步轮询及配置重试逻辑 (api.ts)
62
+ │ ├── index.html # 入口挂载及高德地图 SecurityKey 预设
63
+ +│ ├── .env # 本地前端开发环境变量(Docker 构建时忽略)
64
+ │ └── package.json
65
+ │
66
+ ├── Dockerfile # 通用生产发布容器脚本
67
+ diff --git a/backend/app/api/main.py b/backend/app/api/main.py
68
+ index 312e823..2698fb9 100644
69
+ --- a/backend/app/api/main.py
70
+ +++ b/backend/app/api/main.py
71
+ @@ -53,7 +53,7 @@ async def startup_event():
72
+ print("\n✅ 配置验证通过")
73
+ except ValueError as e:
74
+ print(f"\n❌ 配置验证失败:\n{e}")
75
+ - print("\n请检查.env文件并确保所有必要的配置项都已设置")
76
+ + print("\n请检查环境变量配置;本地开发可通过 .env 提供,Docker 部署请通过容器环境变量提供")
77
+ raise
78
+
79
+ print("\n" + "="*60)
80
+ diff --git a/backend/app/services/amap_service.py b/backend/app/services/amap_service.py
81
+ index b54b9cf..ebda571 100644
82
+ --- a/backend/app/services/amap_service.py
83
+ +++ b/backend/app/services/amap_service.py
84
+ @@ -22,7 +22,7 @@ def get_amap_mcp_tool() -> MCPTool:
85
+ settings = get_settings()
86
+
87
+ if not settings.vite_amap_web_key:
88
+ - raise ValueError("高德地图API Key未配置,请在.env文件中设置VITE_AMAP_WEB_KEY")
89
+ + raise ValueError("高德地图API Key未配置,请设置环境变量 VITE_AMAP_WEB_KEY(本地开发也可写入 .env)")
90
+
91
+ # 创建MCP工具
92
+ _amap_mcp_tool = MCPTool(
93
+ @@ -266,4 +266,3 @@ def get_amap_service() -> AmapService:
94
+ _amap_service = AmapService()
95
+
96
+ return _amap_service
97
+ -
98
+ diff --git a/start.sh b/start.sh
99
+ index 5726fba..e245154 100644
100
+ --- a/start.sh
101
+ +++ b/start.sh
102
+ @@ -2,13 +2,6 @@
103
+
104
+ cd /app
105
+
106
+ -# 导出环境变量(如果 .env 存在就加载)
107
+ -if [ -f backend/.env ]; then
108
+ - set -a
109
+ - source backend/.env
110
+ - set +a
111
+ -fi
112
+ -
113
+ # 获取服务端口和地址,默认为 0.0.0.0:7860
114
+ BIND_HOST=${HOST:-0.0.0.0}
115
+ BIND_PORT=${PORT:-7860}
tasks/1sdv__TripStar-21/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/1sdv__TripStar-21/task.toml ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version = "1.0"
2
+
3
+ [task]
4
+ name = "trending/1sdv__TripStar-21"
5
+ description = "feat(docker): 采用容器环境变量作为运行时配置"
6
+
7
+ [metadata]
8
+ difficulty = "medium"
9
+ category = "bugfix"
10
+ keywords = [
11
+ "TripStar",
12
+ "pr_diff",
13
+ ]
14
+
15
+ [metadata.repo2env]
16
+ pipeline = "pr_diff"
17
+ pipeline_version = "0.3.0"
18
+ repo = "1sdv/TripStar"
19
+ ref = "e2b62da04cb8ab41b4c681bcfeb29a6535fc68b3"
20
+ reference = "https://github.com/1sdv/TripStar/pull/21"
21
+ source_access = "auto"
22
+ built_at = "2026-11-16T16:09:43.782117+00:00"
23
+ reward_kinds = [
24
+ "diff_similarity",
25
+ ]
26
+ spec_version = "0.2.0"
27
+ content_hash = "sha256:545361fc18d42d59db23410e7cf66109d239d31ab8fb226e1e1b393d715076bf"
28
+
29
+ [metadata.repo2env.pr_diff]
30
+ pr_merged_at = "2026-04-05T04:40:52Z"
31
+ diff_format = "unified"
32
+ context_files = [
33
+ ".dockerignore",
34
+ "README.md",
35
+ "backend/app/api/main.py",
36
+ "backend/app/services/amap_service.py",
37
+ "start.sh",
38
+ ]
39
+ bootstrap_image = "python:3.12-slim"
40
+
41
+ [metadata.repo2env.reward_calibration]
42
+ baseline_reward = 0.0
43
+ loc_changed = 35
44
+ difficulty = "medium"
45
+
46
+ [metadata.repo2env.evaluation]
47
+ schema_version = "1"
48
+ status = "unverified"
49
+ stage = "generation"
50
+ reason_codes = [
51
+ "validation_not_run",
52
+ ]
53
+ detail = "Generated task; validation has not been established."
54
+ provenance = "unknown"
55
+ evidence = []
56
+
57
+ [metadata.repo2env.reproducibility]
58
+ mode = "inline_dockerfile"
59
+ image_ref = "python:3.12-slim"
60
+ image_tag = "python:3.12-slim"
61
+ image_visibility = "public"
62
+ pushed_at = "2026-11-16T16:19:57.789463+00:00"
63
+ pushed_by = "scalingX"
64
+ inline_recipe_sha256 = "sha256:d4b93f88202bbe5da1a47dbc91cb61c40bde60148e455b691fa578f2e169799c"
65
+ inline_recipe_lines = 37
66
+ inline_recipe_source = "user_dockerfile"
67
+
68
+ [agent]
69
+ timeout_sec = 1800.0
70
+
71
+ [verifier]
72
+ timeout_sec = 300.0
tasks/1sdv__TripStar-21/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/1sdv__TripStar-21/tests/instruction.md ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Issue
2
+
3
+ **Title:** feat(docker): 采用容器环境变量作为运行时配置
4
+
5
+ ## Description
6
+
7
+ ## 变更说明
8
+
9
+ Docker 部署采用容器环境变量作为后端运行时配置来源:
10
+
11
+ - 镜像构建时忽略 `backend/.env`、`frontend/.env` 等本地配置文件
12
+ - `docker-compose.yaml` 中的 `environment` 是配置入口
13
+ - 本地开发仍可使用 `.env` 文件
14
+
15
+ ## 文件变更
16
+
17
+ - `.dockerignore`: 忽略 .env 文件不打入镜像
18
+ - `README.md`: 添加 Docker/Compose 配置约定说明
19
+ - `backend/app/api/main.py`: 更新环境变量配置提示
20
+ - `backend/app/services/amap_service.py`: 更新 API Key 配置提示
21
+ - `start.sh`: 移除 .env 导出逻辑
22
+
23
+ ## 测试计划
24
+
25
+ - [x] 本地开发使用 .env 仍正常工作
26
+ - [ ] Docker 部署使用容器环境变量正常工作
27
+
28
+ ## Task
29
+
30
+ Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e2b62da04cb8`. Edit files 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/1sdv__TripStar-21/tests/oracle.patch ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/.dockerignore b/.dockerignore
2
+ index c502ec8..7e58465 100644
3
+ --- a/.dockerignore
4
+ +++ b/.dockerignore
5
+ @@ -6,6 +6,9 @@ __pycache__
6
+ .git
7
+ .gitignore
8
+ .env
9
+ +backend/.env
10
+ +frontend/.env
11
+ +frontend/.env.*
12
+ *.md
13
+ MiroFish-main
14
+ .vscode
15
+ diff --git a/README.md b/README.md
16
+ index de9f0b0..16593df 100644
17
+ --- a/README.md
18
+ +++ b/README.md
19
+ @@ -137,7 +137,20 @@ graph TD
20
+ * 小红书Cookie([小红书](https://www.xiaohongshu.com/) 网页端登录后从浏览器开发者工具复制)
21
+ * 安装 `uv` 包管理器
22
+
23
+ -### 1. 后端启动
24
+ +### Docker / Compose 配置约定
25
+ +
26
+ +Docker 部署采用容器环境变量作为后端运行时配置来源:
27
+ +
28
+ +* 容器启动时不再读取项目目录里的 `backend/.env`
29
+ +* 镜像构建时会忽略 `backend/.env`、`frontend/.env`、`frontend/.env.*`
30
+ +* `docker-compose.yaml` 中显式列出的 `environment` 仍然是后端运行时配置入口
31
+ +* 前端构建期变量 `VITE_AMAP_WEB_JS_KEY` 继续通过 `build.args` 注入
32
+ +
33
+ +本地开发仍可按下面步骤使用 `backend/.env` 和 `frontend/.env`。
34
+ +
35
+ +### 本地开发
36
+ +
37
+ +#### 1. 后端启动
38
+
39
+ ```bash
40
+ # 进入后端主目录
41
+ @@ -164,7 +177,7 @@ uvicorn app.api.main:app --host 0.0.0.0 --port 8000 --reload
42
+
43
+ API 启动后,您可以访问 `http://localhost:8000/docs` 查看互动文档。
44
+
45
+ -### 2. 前端启动
46
+ +#### 2. 前端启动
47
+
48
+ ```bash
49
+ # 进入前端主目录
50
+ @@ -199,7 +212,7 @@ TripStar/
51
+ │ │ │ ├── llm_service.py # LLM 客户端封装
52
+ │ │ │ └── knowledge_graph_service.py # 知识图谱构建
53
+ │ │ └── models/ # Pydantic 类型定义 (schemas.py)
54
+ -│ └── .env # LLM 及系统环境变量载体
55
+ +│ └── .env # 本地开发环境变量载体(Docker 部署时不打进镜像)
56
+ │
57
+ ├── frontend/ # Vue 3 互动前端
58
+ │ ├── src/
59
+ @@ -207,6 +220,7 @@ TripStar/
60
+ │ │ ├── components/ # 独立复用的 UI / 背景组件
61
+ │ │ └── services/ # Axios 异步轮询及配置重试逻辑 (api.ts)
62
+ │ ├── index.html # 入口挂载及高德地图 SecurityKey 预设
63
+ +│ ├── .env # 本地前端开发环境变量(Docker 构建时忽略)
64
+ │ └── package.json
65
+ │
66
+ ├── Dockerfile # 通用生产发布容器脚本
67
+ diff --git a/backend/app/api/main.py b/backend/app/api/main.py
68
+ index 312e823..2698fb9 100644
69
+ --- a/backend/app/api/main.py
70
+ +++ b/backend/app/api/main.py
71
+ @@ -53,7 +53,7 @@ async def startup_event():
72
+ print("\n✅ 配置验证通过")
73
+ except ValueError as e:
74
+ print(f"\n❌ 配置验证失败:\n{e}")
75
+ - print("\n请检查.env文件并确保所有必要的配置项都已设置")
76
+ + print("\n请检查环境变量配置;本地开发可通过 .env 提供,Docker 部署请通过容器环境变量提供")
77
+ raise
78
+
79
+ print("\n" + "="*60)
80
+ diff --git a/backend/app/services/amap_service.py b/backend/app/services/amap_service.py
81
+ index b54b9cf..ebda571 100644
82
+ --- a/backend/app/services/amap_service.py
83
+ +++ b/backend/app/services/amap_service.py
84
+ @@ -22,7 +22,7 @@ def get_amap_mcp_tool() -> MCPTool:
85
+ settings = get_settings()
86
+
87
+ if not settings.vite_amap_web_key:
88
+ - raise ValueError("高德地图API Key未配置,请在.env文件中设置VITE_AMAP_WEB_KEY")
89
+ + raise ValueError("高德地图API Key未配置,请设置环境变量 VITE_AMAP_WEB_KEY(本地开发也可写入 .env)")
90
+
91
+ # 创建MCP工具
92
+ _amap_mcp_tool = MCPTool(
93
+ @@ -266,4 +266,3 @@ def get_amap_service() -> AmapService:
94
+ _amap_service = AmapService()
95
+
96
+ return _amap_service
97
+ -
98
+ diff --git a/start.sh b/start.sh
99
+ index 5726fba..e245154 100644
100
+ --- a/start.sh
101
+ +++ b/start.sh
102
+ @@ -2,13 +2,6 @@
103
+
104
+ cd /app
105
+
106
+ -# 导出环境变量(如果 .env 存在就加载)
107
+ -if [ -f backend/.env ]; then
108
+ - set -a
109
+ - source backend/.env
110
+ - set +a
111
+ -fi
112
+ -
113
+ # 获取服务端口和地址,默认为 0.0.0.0:7860
114
+ BIND_HOST=${HOST:-0.0.0.0}
115
+ BIND_PORT=${PORT:-7860}
tasks/1sdv__TripStar-21/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 e2b62da04cb8ab41b4c681bcfeb29a6535fc68b3 > "$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/1sdv__TripStar-21/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/1sdv__TripStar-46/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/1sdv/TripStar.git /workspace; \
16
+ else \
17
+ git clone --filter=blob:none https://github.com/1sdv/TripStar.git /workspace; \
18
+ fi \
19
+ && git -C /workspace remote set-url origin https://github.com/1sdv/TripStar.git
20
+ WORKDIR /workspace
21
+ RUN git fetch --depth 1 origin 5a431e386612153bfdad19a9fcd35136a8f79d89 2>/dev/null \
22
+ || git fetch --unshallow origin 2>/dev/null || true
23
+ RUN git reset --hard 5a431e386612153bfdad19a9fcd35136a8f79d89 \
24
+ && git clean -fdx -e .venv -e venv -e __pycache__
25
+ RUN git checkout -q -B base 5a431e386612153bfdad19a9fcd35136a8f79d89 \
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/1sdv__TripStar-46/instruction.md ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Issue
2
+
3
+ **Title:** fix: 服务端代理小红书图片,修复非 localhost 部署图片 403 (issue #28)
4
+
5
+ ## Description
6
+
7
+ ## What does this PR do?
8
+
9
+ 图片改为由后端在拿到直链的瞬间立即代取落盘,前端只引用以**景点名**为键的本地稳定地址(URL 会过期,景点名不会):
10
+
11
+ - `GET /api/poi/image` 新增 `name` 取图方式:优先读关键词磁盘缓存(24h TTL),miss 时自动重搜新直链并立即下载,过期/重启全程自愈;`url` 方式保留用于代理行程数据中内嵌的稳定直链(域名白名单 `*.xiaohongshu.com` / `*.xhscdn.com`,防 SSRF)
12
+ - `GET /api/poi/photo` 取到新直链后立即预取图片字节并按关键词落盘,契约不变,旧前端完全兼容
13
+ - 前端 `Result.vue` 图片统一走同源代理地址,同时修复导出长图时跨域图片导致的画布污染
14
+
15
+ ## Why is this change needed?
16
+
17
+ 小红书图片 CDN 存在两层限制(均实测确认):
18
+
19
+ 1. **防盗链**:稳定格式直链(`sns-img-*`)校验请求 Referer,前端 `<img>` 直接引用时,局域网 IP / 域名部署全部 403(仅 localhost 正常);
20
+ 2. **时效签名**:搜索/详情接口返回的部分直链(`sns-webpic-*`)路径内嵌时间戳,生成约 1 分钟后即失效——即使服务端带正确 Referer 再取也 403。因此任何"把 URL 交给前端加载"的方案都注定间歇性失败。
21
+
22
+ close #28
23
+
24
+ ## Related Issues
25
+
26
+
27
+
28
+ ## Type of Change
29
+
30
+ - [x] Bug fix
31
+ - [ ] Feature
32
+ - [ ] Documentation
33
+ - [ ] Refactor
34
+ - [ ] Other
35
+
36
+ ## Testing
37
+
38
+ 真实 Cookie 环境实测:
39
+
40
+ - 直连(带外部 Referer)403 → 走代理 200(756KB 图片)
41
+ - 无缓存冷启动自动重搜重取:200(约 5s)
42
+ - 缓存命中:200(磁盘直读)
43
+ - 非白名单域名 / 非法协议:400;过期签名直链:502(前端回落占位图);月龄稳定格式旧链:200
44
+ - `vue-tsc` 类型检查通过
45
+
46
+ ## Screenshots (if applicable)
47
+
48
+ (本地环境景点图片已正常加载,可补图)
49
+
50
+ ## Checklist
51
+
52
+ - [x] Code follows project style guidelines
53
+ - [x] Tests pass locally
54
+ - [ ] Documentation updated (if needed)
55
+ - [x] No breaking changes introduced
56
+
57
+ ## Task
58
+
59
+ Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `5a431e386612`. Edit files 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/1sdv__TripStar-46/solution/patch.diff ADDED
@@ -0,0 +1,306 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/.gitignore b/.gitignore
2
+ index c774dde..9d18809 100644
3
+ --- a/.gitignore
4
+ +++ b/.gitignore
5
+ @@ -1,2 +1,3 @@
6
+ backend/runtime_settings.json
7
+ backend/data/trip_tasks
8
+ +backend/data/photo_cache
9
+ diff --git a/backend/app/api/routes/poi.py b/backend/app/api/routes/poi.py
10
+ index 84f1007..d076ef6 100644
11
+ --- a/backend/app/api/routes/poi.py
12
+ +++ b/backend/app/api/routes/poi.py
13
+ @@ -85,6 +85,58 @@ async def search_poi(keywords: str, city: str = "北京"):
14
+ )
15
+
16
+
17
+ +@router.get(
18
+ + "/image",
19
+ + summary="代理获取小红书图片",
20
+ + description="按景点名从缓存取图(miss 自动重搜新直链并立即下载),或代理白名单内的小红书稳定直链,规避 CDN 防盗链与时效签名(issue #28)"
21
+ +)
22
+ +async def proxy_attraction_image(name: Optional[str] = None, url: Optional[str] = None):
23
+ + """
24
+ + 代理小红书图片,二选一传参:
25
+ +
26
+ + - name: 景点名。优先读关键词磁盘缓存;miss 时自动重搜新直链并立即下载
27
+ + (搜索返回的直链约 1 分钟即失效,浏览器直接引用必然 403)。
28
+ + - url: 小红书稳定格式图片直链(仅限 *.xiaohongshu.com / *.xhscdn.com),
29
+ + 用于代理行程数据中内嵌的直链。
30
+ + """
31
+ + from fastapi.responses import Response
32
+ + from ...services.xhs_service import (
33
+ + XHSImageProxyError,
34
+ + fetch_xhs_image_bytes,
35
+ + get_photo_bytes_from_xhs,
36
+ + )
37
+ +
38
+ + if name:
39
+ + result = await get_photo_bytes_from_xhs(f"{name} 风景")
40
+ + if result is None:
41
+ + raise HTTPException(status_code=404, detail=f"未能获取 {name} 的景点图片")
42
+ + data, content_type = result
43
+ + return Response(
44
+ + content=data,
45
+ + media_type=content_type,
46
+ + headers={"Cache-Control": "public, max-age=86400"},
47
+ + )
48
+ +
49
+ + if url:
50
+ + try:
51
+ + data, content_type = fetch_xhs_image_bytes(url)
52
+ + except ValueError as e:
53
+ + raise HTTPException(status_code=400, detail=str(e))
54
+ + except XHSImageProxyError as e:
55
+ + print(f"❌ 图片代理失败: {e}")
56
+ + raise HTTPException(status_code=502, detail=str(e))
57
+ + except Exception as e:
58
+ + print(f"❌ 图片代理异常: {e}")
59
+ + raise HTTPException(status_code=502, detail=f"图片代理请求失败: {e}")
60
+ + return Response(
61
+ + content=data,
62
+ + media_type=content_type,
63
+ + headers={"Cache-Control": "public, max-age=86400"},
64
+ + )
65
+ +
66
+ + raise HTTPException(status_code=400, detail="必须提供 name 或 url 查询参数")
67
+ +
68
+ +
69
+ @router.get(
70
+ "/photo",
71
+ summary="获取景点图片",
72
+ diff --git a/backend/app/services/xhs_service.py b/backend/app/services/xhs_service.py
73
+ index f6d99ee..2d849da 100644
74
+ --- a/backend/app/services/xhs_service.py
75
+ +++ b/backend/app/services/xhs_service.py
76
+ @@ -13,6 +13,8 @@
77
+ import time
78
+ from collections import OrderedDict
79
+ from concurrent.futures import ThreadPoolExecutor
80
+ +from pathlib import Path
81
+ +from urllib.parse import urlparse
82
+ import requests
83
+ import httpx
84
+ from typing import List, Dict, Any, Optional
85
+ @@ -467,12 +469,23 @@ def _photo_cache_put(keyword: str, url: str) -> None:
86
+
87
+
88
+ def get_xhs_photo_sync(keyword: str) -> str:
89
+ - """带缓存的景点图片查询入口。"""
90
+ + """带缓存的景点图片直链查询入口(兼容旧调用方)。
91
+ +
92
+ + 搜索接口返回的直链带时效签名,必须拿到后立即预取字节落盘
93
+ + (按关键词缓存),否则前端稍后访问必然 403。
94
+ + """
95
+ cached = _photo_cache_get(keyword)
96
+ if cached is not None:
97
+ return cached
98
+
99
+ url = _fetch_xhs_photo(keyword)
100
+ + if url:
101
+ + try:
102
+ + _validate_image_url(url)
103
+ + content, content_type = _download_image(url)
104
+ + _write_image_cache("kw:" + keyword, content, content_type)
105
+ + except (XHSImageProxyError, ValueError) as e:
106
+ + print(f"⚠️ 预取图片字节失败(可稍后经 image 接口自动重试): {e}")
107
+ _photo_cache_put(keyword, url)
108
+ return url
109
+
110
+ @@ -563,3 +576,151 @@ async def get_photo_from_xhs(keyword: str) -> str:
111
+ """供异步环境调用的小红书图片搜索API"""
112
+ import asyncio
113
+ return await asyncio.to_thread(get_xhs_photo_sync, keyword)
114
+ +
115
+ +
116
+ +# ============ 图片代理(防盗链绕过 + 时效直链预取) ============
117
+ +# 小红书图片 CDN 有两层限制:
118
+ +# 1. 防盗链:稳定格式直链(sns-img-*.xhscdn.com)会校验请求 Referer,
119
+ +# 浏览器从非 localhost 站点直接引用会得到 403(issue #28);
120
+ +# 2. 时效签名:搜索/详情接口返回的部分直链(sns-webpic-*)路径内嵌时间戳,
121
+ +# 生成约 1 分钟后即失效,即使服务端带正确 Referer 再取也会 403。
122
+ +# 因此图片必须由后端在拿到直链的瞬间立即代取并落盘;磁盘缓存以搜索
123
+ +# 关键词为主键(而非 URL),缓存过期/丢失后可透明地重搜重取。
124
+ +
125
+ +_IMAGE_CACHE_DIR = Path(__file__).resolve().parents[2] / "data" / "photo_cache"
126
+ +_IMAGE_CACHE_TTL_SECONDS = 24 * 3600
127
+ +_IMAGE_MAX_SIZE_BYTES = 10 * 1024 * 1024
128
+ +_IMAGE_ALLOWED_HOST_SUFFIXES = (".xiaohongshu.com", ".xhscdn.com")
129
+ +_IMAGE_FETCH_HEADERS = {
130
+ + "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
131
+ + "Referer": "https://www.xiaohongshu.com/",
132
+ +}
133
+ +
134
+ +
135
+ +class XHSImageProxyError(Exception):
136
+ + """小红书图片代理抓取失败。"""
137
+ + pass
138
+ +
139
+ +
140
+ +def _validate_image_url(url: str) -> None:
141
+ + """校验图片 URL 必须指向小红书图片 CDN,防止代理被滥用于任意地址(SSRF)。"""
142
+ + parsed = urlparse(url)
143
+ + if parsed.scheme not in ("http", "https"):
144
+ + raise ValueError(f"不支持的图片 URL 协议: {parsed.scheme}")
145
+ + host = (parsed.hostname or "").lower()
146
+ + if not any(host == suffix.lstrip(".") or host.endswith(suffix) for suffix in _IMAGE_ALLOWED_HOST_SUFFIXES):
147
+ + raise ValueError(f"仅允许代理小红书图片域名,收到: {host}")
148
+ +
149
+ +
150
+ +def _image_cache_paths(cache_key: str) -> tuple:
151
+ + """磁盘缓存文件路径(.img 内容 + .meta Content-Type),键已含命名空间。"""
152
+ + import hashlib
153
+ + digest = hashlib.sha256(cache_key.encode("utf-8")).hexdigest()
154
+ + return _IMAGE_CACHE_DIR / f"{digest}.img", _IMAGE_CACHE_DIR / f"{digest}.meta"
155
+ +
156
+ +
157
+ +def _read_image_cache(cache_key: str) -> Optional[tuple]:
158
+ + """读取未过期的缓存图片,返回 (bytes, content_type) 或 None。"""
159
+ + cache_img, cache_meta = _image_cache_paths(cache_key)
160
+ + if not (cache_img.exists() and cache_meta.exists()):
161
+ + return None
162
+ + if time.time() - cache_img.stat().st_mtime >= _IMAGE_CACHE_TTL_SECONDS:
163
+ + return None
164
+ + try:
165
+ + content_type = cache_meta.read_text(encoding="utf-8").strip() or "image/jpeg"
166
+ + return cache_img.read_bytes(), content_type
167
+ + except OSError as e:
168
+ + print(f"⚠️ 读取图片缓存失败: {e}")
169
+ + return None
170
+ +
171
+ +
172
+ +def _write_image_cache(cache_key: str, content: bytes, content_type: str) -> None:
173
+ + """原子写入磁盘缓存,失败不影响本次响应。"""
174
+ + cache_img, cache_meta = _image_cache_paths(cache_key)
175
+ + try:
176
+ + _IMAGE_CACHE_DIR.mkdir(parents=True, exist_ok=True)
177
+ + tmp_img = cache_img.with_suffix(".img.tmp")
178
+ + tmp_img.write_bytes(content)
179
+ + tmp_img.replace(cache_img)
180
+ + tmp_meta = cache_meta.with_suffix(".meta.tmp")
181
+ + tmp_meta.write_text(content_type, encoding="utf-8")
182
+ + tmp_meta.replace(cache_meta)
183
+ + except OSError as e:
184
+ + print(f"⚠️ 写入图片缓存失败: {e}")
185
+ +
186
+ +
187
+ +def _download_image(url: str) -> tuple:
188
+ + """服务端下载小红书图片,返回 (bytes, content_type)。"""
189
+ + try:
190
+ + resp = httpx.get(
191
+ + url,
192
+ + headers=_IMAGE_FETCH_HEADERS,
193
+ + timeout=15,
194
+ + follow_redirects=True,
195
+ + trust_env=False,
196
+ + )
197
+ + except httpx.TimeoutException as e:
198
+ + raise XHSImageProxyError(f"图片下载超时: {url}") from e
199
+ + except httpx.HTTPError as e:
200
+ + raise XHSImageProxyError(f"图片下载失败: {url}: {e}") from e
201
+ +
202
+ + if resp.status_code != 200:
203
+ + raise XHSImageProxyError(f"图片下载返回 HTTP {resp.status_code}: {url}")
204
+ +
205
+ + content = resp.content
206
+ + content_type = resp.headers.get("content-type", "image/jpeg").split(";")[0].strip()
207
+ + if not content:
208
+ + raise XHSImageProxyError(f"图片内容为空: {url}")
209
+ + if not content_type.startswith("image/"):
210
+ + raise XHSImageProxyError(f"响应不是图片 (content-type={content_type}): {url}")
211
+ + if len(content) > _IMAGE_MAX_SIZE_BYTES:
212
+ + raise XHSImageProxyError(f"图片超过大小限制 ({_IMAGE_MAX_SIZE_BYTES // 1024 // 1024}MB): {url}")
213
+ +
214
+ + return content, content_type
215
+ +
216
+ +
217
+ +def fetch_xhs_image_bytes(url: str) -> tuple:
218
+ + """按直链抓取小红书图片(URL 维度缓存),供 /api/poi/image?url= 使用。
219
+ +
220
+ + URL 非法抛 ValueError,抓取失败抛 XHSImageProxyError。
221
+ + 仅稳定格式直链可长期有效;时效签名直链过期后必然失败。
222
+ + """
223
+ + _validate_image_url(url)
224
+ +
225
+ + cached = _read_image_cache("url:" + url)
226
+ + if cached is not None:
227
+ + return cached
228
+ +
229
+ + content, content_type = _download_image(url)
230
+ + _write_image_cache("url:" + url, content, content_type)
231
+ + return content, content_type
232
+ +
233
+ +
234
+ +def get_xhs_photo_bytes_sync(keyword: str) -> Optional[tuple]:
235
+ + """获取关键词对应的图片字节;缓存 miss 时自动重搜新直链并立即下载。
236
+ +
237
+ + 返回 (bytes, content_type),无法获取时返回 None。
238
+ + """
239
+ + cached = _read_image_cache("kw:" + keyword)
240
+ + if cached is not None:
241
+ + return cached
242
+ +
243
+ + for attempt in range(2):
244
+ + url = _fetch_xhs_photo(keyword)
245
+ + if not url:
246
+ + return None
247
+ + try:
248
+ + _validate_image_url(url)
249
+ + content, content_type = _download_image(url)
250
+ + _write_image_cache("kw:" + keyword, content, content_type)
251
+ + return content, content_type
252
+ + except (XHSImageProxyError, ValueError) as e:
253
+ + # 直链多为限时签名,失败后重搜一条全新直链再试一次
254
+ + print(f"⚠️ 图片下载失败(第{attempt + 1}次,将重取新直链): {e}")
255
+ + return None
256
+ +
257
+ +
258
+ +async def get_photo_bytes_from_xhs(keyword: str) -> Optional[tuple]:
259
+ + """供异步环境调用的图片字节获取入口。"""
260
+ + import asyncio
261
+ + return await asyncio.to_thread(get_xhs_photo_bytes_sync, keyword)
262
+ diff --git a/frontend/src/views/Result.vue b/frontend/src/views/Result.vue
263
+ index 1d2ba82..2a88ed6 100644
264
+ --- a/frontend/src/views/Result.vue
265
+ +++ b/frontend/src/views/Result.vue
266
+ @@ -324,7 +324,7 @@
267
+ <!-- 景点图片 -->
268
+ <div class="attraction-image-wrapper">
269
+ <img
270
+ - :src="item.image_url || getAttractionImage(item.name, index)"
271
+ + :src="toProxiedPhotoUrl(item.image_url) || getAttractionImage(item.name, index)"
272
+ :alt="item.name"
273
+ class="attraction-image"
274
+ @error="handleImageError"
275
+ @@ -1797,6 +1797,12 @@ const restoreBudgetItem = (pendingItem: BudgetRestoreItem) => {
276
+ message.success(t('result.messages.budgetItemRestored'))
277
+ }
278
+
279
+ +// 将小红书图片直链包装为后端代理地址,规避图片 CDN 的 Referer 防盗链(issue #28)
280
+ +const toProxiedPhotoUrl = (url?: string | null): string => {
281
+ + if (!url) return ''
282
+ + return `${getRuntimeApiBaseUrl()}/api/poi/image?url=${encodeURIComponent(url)}`
283
+ +}
284
+ +
285
+ // 加载所有景点图片
286
+ const loadAttractionPhotos = async () => {
287
+ if (!tripPlan.value) return
288
+ @@ -1826,7 +1832,8 @@ const loadAttractionPhotos = async () => {
289
+ )
290
+ const data = await response.json()
291
+ if (data.success && data.data.photo_url) {
292
+ - attractionPhotos.value[name] = data.data.photo_url
293
+ + // 直链带时效签名会过期,统一改走后端 name 键代理(缓存 miss 时自动重搜重取)
294
+ + attractionPhotos.value[name] = `${apiBase}/api/poi/image?name=${encodeURIComponent(name)}`
295
+ }
296
+ } catch (err) {
297
+ console.error(`获取${name}图片失败:`, err)
298
+ @@ -1893,7 +1900,7 @@ const buildExportHTML = (mapDataUrl: string = ''): string => {
299
+ tp.days.forEach((day, index) => {
300
+ let attractionsHTML = ''
301
+ day.attractions.forEach((a, ai) => {
302
+ - const photoUrl = a.image_url || attractionPhotos.value[a.name] || ''
303
+ + const photoUrl = toProxiedPhotoUrl(a.image_url) || attractionPhotos.value[a.name] || ''
304
+ const durationText = t('result.export.durationLine', { duration: a.visit_duration || '—' })
305
+ // 图片自适应:不压缩不裁剪,保持原始比例
306
+ const imgTag = photoUrl
tasks/1sdv__TripStar-46/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/1sdv__TripStar-46/task.toml ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version = "1.0"
2
+
3
+ [task]
4
+ name = "trending/1sdv__TripStar-46"
5
+ description = "fix: 服务端代理小红书图片,修复非 localhost 部署图片 403 (issue #28)"
6
+
7
+ [metadata]
8
+ difficulty = "large"
9
+ category = "bugfix"
10
+ keywords = [
11
+ "TripStar",
12
+ "pr_diff",
13
+ ]
14
+
15
+ [metadata.repo2env]
16
+ pipeline = "pr_diff"
17
+ pipeline_version = "0.3.0"
18
+ repo = "1sdv/TripStar"
19
+ ref = "5a431e386612153bfdad19a9fcd35136a8f79d89"
20
+ reference = "https://github.com/1sdv/TripStar/pull/46"
21
+ source_access = "auto"
22
+ built_at = "2026-11-16T16:09:43.780466+00:00"
23
+ reward_kinds = [
24
+ "diff_similarity",
25
+ ]
26
+ spec_version = "0.2.0"
27
+ content_hash = "sha256:4a10056831e839dd6802f57cfc0a5b56daa5d03fc232742b23d5641db628eb55"
28
+
29
+ [metadata.repo2env.pr_diff]
30
+ pr_merged_at = "2026-09-16T12:18:03Z"
31
+ diff_format = "unified"
32
+ context_files = [
33
+ ".gitignore",
34
+ "backend/app/api/routes/poi.py",
35
+ "backend/app/services/xhs_service.py",
36
+ "frontend/src/views/Result.vue",
37
+ ]
38
+ bootstrap_image = "python:3.12-slim"
39
+
40
+ [metadata.repo2env.reward_calibration]
41
+ baseline_reward = 0.0
42
+ loc_changed = 229
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:19:57.789947+00:00"
62
+ pushed_by = "scalingX"
63
+ inline_recipe_sha256 = "sha256:6c7393bc537333d3fbf1216be4050e6fa77c6d6a4774c2e4936e98785c50a59c"
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/1sdv__TripStar-46/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/1sdv__TripStar-46/tests/instruction.md ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Issue
2
+
3
+ **Title:** fix: 服务端代理小红书图片,修复非 localhost 部署图片 403 (issue #28)
4
+
5
+ ## Description
6
+
7
+ ## What does this PR do?
8
+
9
+ 图片改为由后端在拿到直链的瞬间立即代取落盘,前端只引用以**景点名**为键的本地稳定地址(URL 会过期,景点名不会):
10
+
11
+ - `GET /api/poi/image` 新增 `name` 取图方式:优先读关键词磁盘缓存(24h TTL),miss 时自动重搜新直链并立即下载,过期/重启全程自愈;`url` 方式保留用于代理行程数据中内嵌的稳定直链(域名白名单 `*.xiaohongshu.com` / `*.xhscdn.com`,防 SSRF)
12
+ - `GET /api/poi/photo` 取到新直链后立即预取图片字节并按关键词落盘,契约不变,旧前端完全兼容
13
+ - 前端 `Result.vue` 图片统一走同源代理地址,同时修复导出长图时跨域图片导致的画布污染
14
+
15
+ ## Why is this change needed?
16
+
17
+ 小红书图片 CDN 存在两层限制(均实测确认):
18
+
19
+ 1. **防盗链**:稳定格式直链(`sns-img-*`)校验请求 Referer,前端 `<img>` 直接引用时,局域网 IP / 域名部署全部 403(仅 localhost 正常);
20
+ 2. **时效签名**:搜索/详情接口返回的部分直链(`sns-webpic-*`)路径内嵌时间戳,生成约 1 分钟后即失效——即使服务端带正确 Referer 再取也 403。因此任何"把 URL 交给前端加载"的方案都注定间歇性失败。
21
+
22
+ close #28
23
+
24
+ ## Related Issues
25
+
26
+
27
+
28
+ ## Type of Change
29
+
30
+ - [x] Bug fix
31
+ - [ ] Feature
32
+ - [ ] Documentation
33
+ - [ ] Refactor
34
+ - [ ] Other
35
+
36
+ ## Testing
37
+
38
+ 真实 Cookie 环境实测:
39
+
40
+ - 直连(带外部 Referer)403 → 走代理 200(756KB 图片)
41
+ - 无缓存冷启动自动重搜重取:200(约 5s)
42
+ - 缓存命中:200(磁盘直读)
43
+ - 非白名单域名 / 非法协议:400;过期签名直链:502(前端回落占位图);月龄稳定格式旧链:200
44
+ - `vue-tsc` 类型检查通过
45
+
46
+ ## Screenshots (if applicable)
47
+
48
+ (本地环境景点图片已正常加载,可补图)
49
+
50
+ ## Checklist
51
+
52
+ - [x] Code follows project style guidelines
53
+ - [x] Tests pass locally
54
+ - [ ] Documentation updated (if needed)
55
+ - [x] No breaking changes introduced
56
+
57
+ ## Task
58
+
59
+ Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `5a431e386612`. Edit files 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/1sdv__TripStar-46/tests/oracle.patch ADDED
@@ -0,0 +1,306 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/.gitignore b/.gitignore
2
+ index c774dde..9d18809 100644
3
+ --- a/.gitignore
4
+ +++ b/.gitignore
5
+ @@ -1,2 +1,3 @@
6
+ backend/runtime_settings.json
7
+ backend/data/trip_tasks
8
+ +backend/data/photo_cache
9
+ diff --git a/backend/app/api/routes/poi.py b/backend/app/api/routes/poi.py
10
+ index 84f1007..d076ef6 100644
11
+ --- a/backend/app/api/routes/poi.py
12
+ +++ b/backend/app/api/routes/poi.py
13
+ @@ -85,6 +85,58 @@ async def search_poi(keywords: str, city: str = "北京"):
14
+ )
15
+
16
+
17
+ +@router.get(
18
+ + "/image",
19
+ + summary="代理获取小红书图片",
20
+ + description="按景点名从缓存取图(miss 自动重搜新直链并立即下载),或代理白名单内的小红书稳定直链,规避 CDN 防盗链与时效签名(issue #28)"
21
+ +)
22
+ +async def proxy_attraction_image(name: Optional[str] = None, url: Optional[str] = None):
23
+ + """
24
+ + 代理小红书图片,二选一传参:
25
+ +
26
+ + - name: 景点名。优先读关键词磁盘缓存;miss 时自动重搜新直链并立即下载
27
+ + (搜索返回的直链约 1 分钟即失效,浏览器直接引用必然 403)。
28
+ + - url: 小红书稳定格式图片直链(仅限 *.xiaohongshu.com / *.xhscdn.com),
29
+ + 用于代理行程数据中内嵌的直链。
30
+ + """
31
+ + from fastapi.responses import Response
32
+ + from ...services.xhs_service import (
33
+ + XHSImageProxyError,
34
+ + fetch_xhs_image_bytes,
35
+ + get_photo_bytes_from_xhs,
36
+ + )
37
+ +
38
+ + if name:
39
+ + result = await get_photo_bytes_from_xhs(f"{name} 风景")
40
+ + if result is None:
41
+ + raise HTTPException(status_code=404, detail=f"未能获取 {name} 的景点图片")
42
+ + data, content_type = result
43
+ + return Response(
44
+ + content=data,
45
+ + media_type=content_type,
46
+ + headers={"Cache-Control": "public, max-age=86400"},
47
+ + )
48
+ +
49
+ + if url:
50
+ + try:
51
+ + data, content_type = fetch_xhs_image_bytes(url)
52
+ + except ValueError as e:
53
+ + raise HTTPException(status_code=400, detail=str(e))
54
+ + except XHSImageProxyError as e:
55
+ + print(f"❌ 图片代理失败: {e}")
56
+ + raise HTTPException(status_code=502, detail=str(e))
57
+ + except Exception as e:
58
+ + print(f"❌ 图片代理异常: {e}")
59
+ + raise HTTPException(status_code=502, detail=f"图片代理请求失败: {e}")
60
+ + return Response(
61
+ + content=data,
62
+ + media_type=content_type,
63
+ + headers={"Cache-Control": "public, max-age=86400"},
64
+ + )
65
+ +
66
+ + raise HTTPException(status_code=400, detail="必须提供 name 或 url 查询参数")
67
+ +
68
+ +
69
+ @router.get(
70
+ "/photo",
71
+ summary="获取景点图片",
72
+ diff --git a/backend/app/services/xhs_service.py b/backend/app/services/xhs_service.py
73
+ index f6d99ee..2d849da 100644
74
+ --- a/backend/app/services/xhs_service.py
75
+ +++ b/backend/app/services/xhs_service.py
76
+ @@ -13,6 +13,8 @@
77
+ import time
78
+ from collections import OrderedDict
79
+ from concurrent.futures import ThreadPoolExecutor
80
+ +from pathlib import Path
81
+ +from urllib.parse import urlparse
82
+ import requests
83
+ import httpx
84
+ from typing import List, Dict, Any, Optional
85
+ @@ -467,12 +469,23 @@ def _photo_cache_put(keyword: str, url: str) -> None:
86
+
87
+
88
+ def get_xhs_photo_sync(keyword: str) -> str:
89
+ - """带缓存的景点图片查询入口。"""
90
+ + """带缓存的景点图片直链查询入口(兼容旧调用方)。
91
+ +
92
+ + 搜索接口返回的直链带时效签名,必须拿到后立即预取字节落盘
93
+ + (按关键词缓存),否则前端稍后访问必然 403。
94
+ + """
95
+ cached = _photo_cache_get(keyword)
96
+ if cached is not None:
97
+ return cached
98
+
99
+ url = _fetch_xhs_photo(keyword)
100
+ + if url:
101
+ + try:
102
+ + _validate_image_url(url)
103
+ + content, content_type = _download_image(url)
104
+ + _write_image_cache("kw:" + keyword, content, content_type)
105
+ + except (XHSImageProxyError, ValueError) as e:
106
+ + print(f"⚠️ 预取图片字节失败(可稍后经 image 接口自动重试): {e}")
107
+ _photo_cache_put(keyword, url)
108
+ return url
109
+
110
+ @@ -563,3 +576,151 @@ async def get_photo_from_xhs(keyword: str) -> str:
111
+ """供异步环境调用的小红书图片搜索API"""
112
+ import asyncio
113
+ return await asyncio.to_thread(get_xhs_photo_sync, keyword)
114
+ +
115
+ +
116
+ +# ============ 图片代理(防盗链绕过 + 时效直链预取) ============
117
+ +# 小红书图片 CDN 有两层限制:
118
+ +# 1. 防盗链:稳定格式直链(sns-img-*.xhscdn.com)会校验请求 Referer,
119
+ +# 浏览器从非 localhost 站点直接引用会得到 403(issue #28);
120
+ +# 2. 时效签名:搜索/详情接口返回的部分直链(sns-webpic-*)路径内嵌时间戳,
121
+ +# 生成约 1 分钟后即失效,即使服务端带正确 Referer 再取也会 403。
122
+ +# 因此图片必须由后端在拿到直链的瞬间立即代取并落盘;磁盘缓存以搜索
123
+ +# 关键词为主键(而非 URL),缓存过期/丢失后可透明地重搜重取。
124
+ +
125
+ +_IMAGE_CACHE_DIR = Path(__file__).resolve().parents[2] / "data" / "photo_cache"
126
+ +_IMAGE_CACHE_TTL_SECONDS = 24 * 3600
127
+ +_IMAGE_MAX_SIZE_BYTES = 10 * 1024 * 1024
128
+ +_IMAGE_ALLOWED_HOST_SUFFIXES = (".xiaohongshu.com", ".xhscdn.com")
129
+ +_IMAGE_FETCH_HEADERS = {
130
+ + "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
131
+ + "Referer": "https://www.xiaohongshu.com/",
132
+ +}
133
+ +
134
+ +
135
+ +class XHSImageProxyError(Exception):
136
+ + """小红书图片代理抓取失败。"""
137
+ + pass
138
+ +
139
+ +
140
+ +def _validate_image_url(url: str) -> None:
141
+ + """校验图片 URL 必须指向小红书图片 CDN,防止代理被滥用于任意地址(SSRF)。"""
142
+ + parsed = urlparse(url)
143
+ + if parsed.scheme not in ("http", "https"):
144
+ + raise ValueError(f"不支持的图片 URL 协议: {parsed.scheme}")
145
+ + host = (parsed.hostname or "").lower()
146
+ + if not any(host == suffix.lstrip(".") or host.endswith(suffix) for suffix in _IMAGE_ALLOWED_HOST_SUFFIXES):
147
+ + raise ValueError(f"仅允许代理小红书图片域名,收到: {host}")
148
+ +
149
+ +
150
+ +def _image_cache_paths(cache_key: str) -> tuple:
151
+ + """磁盘缓存文件路径(.img 内容 + .meta Content-Type),键已含命名空间。"""
152
+ + import hashlib
153
+ + digest = hashlib.sha256(cache_key.encode("utf-8")).hexdigest()
154
+ + return _IMAGE_CACHE_DIR / f"{digest}.img", _IMAGE_CACHE_DIR / f"{digest}.meta"
155
+ +
156
+ +
157
+ +def _read_image_cache(cache_key: str) -> Optional[tuple]:
158
+ + """读取未过期的缓存图片,返回 (bytes, content_type) 或 None。"""
159
+ + cache_img, cache_meta = _image_cache_paths(cache_key)
160
+ + if not (cache_img.exists() and cache_meta.exists()):
161
+ + return None
162
+ + if time.time() - cache_img.stat().st_mtime >= _IMAGE_CACHE_TTL_SECONDS:
163
+ + return None
164
+ + try:
165
+ + content_type = cache_meta.read_text(encoding="utf-8").strip() or "image/jpeg"
166
+ + return cache_img.read_bytes(), content_type
167
+ + except OSError as e:
168
+ + print(f"⚠️ 读取图片缓存失败: {e}")
169
+ + return None
170
+ +
171
+ +
172
+ +def _write_image_cache(cache_key: str, content: bytes, content_type: str) -> None:
173
+ + """原子写入磁盘缓存,失败不影响本次响应。"""
174
+ + cache_img, cache_meta = _image_cache_paths(cache_key)
175
+ + try:
176
+ + _IMAGE_CACHE_DIR.mkdir(parents=True, exist_ok=True)
177
+ + tmp_img = cache_img.with_suffix(".img.tmp")
178
+ + tmp_img.write_bytes(content)
179
+ + tmp_img.replace(cache_img)
180
+ + tmp_meta = cache_meta.with_suffix(".meta.tmp")
181
+ + tmp_meta.write_text(content_type, encoding="utf-8")
182
+ + tmp_meta.replace(cache_meta)
183
+ + except OSError as e:
184
+ + print(f"⚠️ 写入图片缓存失败: {e}")
185
+ +
186
+ +
187
+ +def _download_image(url: str) -> tuple:
188
+ + """服务端下载小红书图片,返回 (bytes, content_type)。"""
189
+ + try:
190
+ + resp = httpx.get(
191
+ + url,
192
+ + headers=_IMAGE_FETCH_HEADERS,
193
+ + timeout=15,
194
+ + follow_redirects=True,
195
+ + trust_env=False,
196
+ + )
197
+ + except httpx.TimeoutException as e:
198
+ + raise XHSImageProxyError(f"图片下载超时: {url}") from e
199
+ + except httpx.HTTPError as e:
200
+ + raise XHSImageProxyError(f"图片下载失败: {url}: {e}") from e
201
+ +
202
+ + if resp.status_code != 200:
203
+ + raise XHSImageProxyError(f"图片下载返回 HTTP {resp.status_code}: {url}")
204
+ +
205
+ + content = resp.content
206
+ + content_type = resp.headers.get("content-type", "image/jpeg").split(";")[0].strip()
207
+ + if not content:
208
+ + raise XHSImageProxyError(f"图片内容为空: {url}")
209
+ + if not content_type.startswith("image/"):
210
+ + raise XHSImageProxyError(f"响应不是图片 (content-type={content_type}): {url}")
211
+ + if len(content) > _IMAGE_MAX_SIZE_BYTES:
212
+ + raise XHSImageProxyError(f"图片超过大小限制 ({_IMAGE_MAX_SIZE_BYTES // 1024 // 1024}MB): {url}")
213
+ +
214
+ + return content, content_type
215
+ +
216
+ +
217
+ +def fetch_xhs_image_bytes(url: str) -> tuple:
218
+ + """按直链抓取小红书图片(URL 维度缓存),供 /api/poi/image?url= 使用。
219
+ +
220
+ + URL 非法抛 ValueError,抓取失败抛 XHSImageProxyError。
221
+ + 仅稳定格式直链可长期有效;时效签名直链过期后必然失败。
222
+ + """
223
+ + _validate_image_url(url)
224
+ +
225
+ + cached = _read_image_cache("url:" + url)
226
+ + if cached is not None:
227
+ + return cached
228
+ +
229
+ + content, content_type = _download_image(url)
230
+ + _write_image_cache("url:" + url, content, content_type)
231
+ + return content, content_type
232
+ +
233
+ +
234
+ +def get_xhs_photo_bytes_sync(keyword: str) -> Optional[tuple]:
235
+ + """获取关键词对应的图片字节;缓存 miss 时自动重搜新直链并立即下载。
236
+ +
237
+ + 返回 (bytes, content_type),无法获取时返回 None。
238
+ + """
239
+ + cached = _read_image_cache("kw:" + keyword)
240
+ + if cached is not None:
241
+ + return cached
242
+ +
243
+ + for attempt in range(2):
244
+ + url = _fetch_xhs_photo(keyword)
245
+ + if not url:
246
+ + return None
247
+ + try:
248
+ + _validate_image_url(url)
249
+ + content, content_type = _download_image(url)
250
+ + _write_image_cache("kw:" + keyword, content, content_type)
251
+ + return content, content_type
252
+ + except (XHSImageProxyError, ValueError) as e:
253
+ + # 直链多为限时签名,失败后重搜一条全新直链再试一次
254
+ + print(f"⚠️ 图片下载失败(第{attempt + 1}次,将重取新直链): {e}")
255
+ + return None
256
+ +
257
+ +
258
+ +async def get_photo_bytes_from_xhs(keyword: str) -> Optional[tuple]:
259
+ + """供异步环境调用的图片字节获取入口。"""
260
+ + import asyncio
261
+ + return await asyncio.to_thread(get_xhs_photo_bytes_sync, keyword)
262
+ diff --git a/frontend/src/views/Result.vue b/frontend/src/views/Result.vue
263
+ index 1d2ba82..2a88ed6 100644
264
+ --- a/frontend/src/views/Result.vue
265
+ +++ b/frontend/src/views/Result.vue
266
+ @@ -324,7 +324,7 @@
267
+ <!-- 景点图片 -->
268
+ <div class="attraction-image-wrapper">
269
+ <img
270
+ - :src="item.image_url || getAttractionImage(item.name, index)"
271
+ + :src="toProxiedPhotoUrl(item.image_url) || getAttractionImage(item.name, index)"
272
+ :alt="item.name"
273
+ class="attraction-image"
274
+ @error="handleImageError"
275
+ @@ -1797,6 +1797,12 @@ const restoreBudgetItem = (pendingItem: BudgetRestoreItem) => {
276
+ message.success(t('result.messages.budgetItemRestored'))
277
+ }
278
+
279
+ +// 将小红书图片直链包装为后端代理地址,规避图片 CDN 的 Referer 防盗链(issue #28)
280
+ +const toProxiedPhotoUrl = (url?: string | null): string => {
281
+ + if (!url) return ''
282
+ + return `${getRuntimeApiBaseUrl()}/api/poi/image?url=${encodeURIComponent(url)}`
283
+ +}
284
+ +
285
+ // 加载所有景点图片
286
+ const loadAttractionPhotos = async () => {
287
+ if (!tripPlan.value) return
288
+ @@ -1826,7 +1832,8 @@ const loadAttractionPhotos = async () => {
289
+ )
290
+ const data = await response.json()
291
+ if (data.success && data.data.photo_url) {
292
+ - attractionPhotos.value[name] = data.data.photo_url
293
+ + // 直链带时效签名会过期,统一改走后端 name 键代理(缓存 miss 时自动重搜重取)
294
+ + attractionPhotos.value[name] = `${apiBase}/api/poi/image?name=${encodeURIComponent(name)}`
295
+ }
296
+ } catch (err) {
297
+ console.error(`获取${name}图片失败:`, err)
298
+ @@ -1893,7 +1900,7 @@ const buildExportHTML = (mapDataUrl: string = ''): string => {
299
+ tp.days.forEach((day, index) => {
300
+ let attractionsHTML = ''
301
+ day.attractions.forEach((a, ai) => {
302
+ - const photoUrl = a.image_url || attractionPhotos.value[a.name] || ''
303
+ + const photoUrl = toProxiedPhotoUrl(a.image_url) || attractionPhotos.value[a.name] || ''
304
+ const durationText = t('result.export.durationLine', { duration: a.visit_duration || '—' })
305
+ // 图片自适应:不压缩不裁剪,保持原始比例
306
+ const imgTag = photoUrl
tasks/1sdv__TripStar-46/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 5a431e386612153bfdad19a9fcd35136a8f79d89 > "$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/1sdv__TripStar-46/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/1sdv__TripStar-49/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/1sdv/TripStar.git /workspace; \
16
+ else \
17
+ git clone --filter=blob:none https://github.com/1sdv/TripStar.git /workspace; \
18
+ fi \
19
+ && git -C /workspace remote set-url origin https://github.com/1sdv/TripStar.git
20
+ WORKDIR /workspace
21
+ RUN git fetch --depth 1 origin 1dce6df8f358a8650693e201aa4cb1d974a688bd 2>/dev/null \
22
+ || git fetch --unshallow origin 2>/dev/null || true
23
+ RUN git reset --hard 1dce6df8f358a8650693e201aa4cb1d974a688bd \
24
+ && git clean -fdx -e .venv -e venv -e __pycache__
25
+ RUN git checkout -q -B base 1dce6df8f358a8650693e201aa4cb1d974a688bd \
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/1sdv__TripStar-49/instruction.md ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Issue
2
+
3
+ **Title:** Fix/offload blocking map calls
4
+
5
+ ## Description
6
+
7
+ ## What does this PR do?
8
+
9
+ <!-- Briefly describe what this PR accomplishes -->
10
+
11
+ ## Why is this change needed?
12
+
13
+ <!-- Explain the motivation and context -->
14
+
15
+ ## Related Issues
16
+
17
+ <!-- Link related issues: , -->
18
+
19
+ ## Type of Change
20
+
21
+ - [ ] Feature
22
+ - [ ] Bug fix
23
+ - [ ] Documentation
24
+ - [ ] Refactor
25
+ - [ ] Other
26
+
27
+ ## Testing
28
+
29
+ <!-- Describe how you tested this -->
30
+
31
+ ## Screenshots (if applicable)
32
+
33
+ <!-- Add before/after screenshots here -->
34
+
35
+ ## Checklist
36
+
37
+ - [ ] Code follows project style guidelines
38
+ - [ ] Tests pass locally
39
+ - [ ] Documentation updated (if needed)
40
+ - [ ] No breaking changes introduced
41
+
42
+ ## Task
43
+
44
+ Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `1dce6df8f358`. Edit files 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/1sdv__TripStar-49/solution/patch.diff ADDED
@@ -0,0 +1,495 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/backend/app/api/routes/map.py b/backend/app/api/routes/map.py
2
+ index 8719fde..d12a453 100644
3
+ --- a/backend/app/api/routes/map.py
4
+ +++ b/backend/app/api/routes/map.py
5
+ @@ -1,5 +1,7 @@
6
+ """地图服务API路由"""
7
+
8
+ +import asyncio
9
+ +
10
+ from fastapi import APIRouter, HTTPException, Query
11
+ from typing import Optional
12
+ from ...models.schemas import (
13
+ @@ -14,6 +16,12 @@
14
+
15
+ router = APIRouter(prefix="/map", tags=["地图服务"])
16
+
17
+ +# 本模块路由都是 async def,而 AmapService 连构造带调用都是同步阻塞的:
18
+ +# MCPTool 初始化会 spawn `uvx amap-mcp-server` 并做服务发现
19
+ +# (hello_agents/tools/builtin/protocol_tools.py:124 → :271),run() 也会
20
+ +# 另开线程后 future.result() 等待(同文件 :447-458)。因此统一用
21
+ +# asyncio.to_thread 派发,避免冻结事件循环导致进度推送与轮询一起失效。
22
+ +
23
+
24
+ @router.get(
25
+ "/poi",
26
+ @@ -39,10 +47,10 @@ async def search_poi(
27
+ """
28
+ try:
29
+ # 获取服务实例
30
+ - service = get_amap_service()
31
+ + service = await asyncio.to_thread(get_amap_service)
32
+
33
+ # 搜索POI
34
+ - pois = service.search_poi(keywords, city, citylimit)
35
+ + pois = await asyncio.to_thread(service.search_poi, keywords, city, citylimit)
36
+
37
+ return POISearchResponse(
38
+ success=bool(pois),
39
+ @@ -78,10 +86,10 @@ async def get_weather(
40
+ """
41
+ try:
42
+ # 获取服务实例
43
+ - service = get_amap_service()
44
+ + service = await asyncio.to_thread(get_amap_service)
45
+
46
+ # 查询天气
47
+ - weather_info = service.get_weather(city)
48
+ + weather_info = await asyncio.to_thread(service.get_weather, city)
49
+
50
+ return WeatherResponse(
51
+ success=bool(weather_info),
52
+ @@ -115,10 +123,11 @@ async def plan_route(request: RouteRequest):
53
+ """
54
+ try:
55
+ # 获取服务实例
56
+ - service = get_amap_service()
57
+ + service = await asyncio.to_thread(get_amap_service)
58
+
59
+ # 规划路线
60
+ - route_info = service.plan_route(
61
+ + route_info = await asyncio.to_thread(
62
+ + service.plan_route,
63
+ origin_address=request.origin_address,
64
+ destination_address=request.destination_address,
65
+ origin_city=request.origin_city,
66
+ @@ -161,7 +170,7 @@ async def health_check():
67
+ """健康检查"""
68
+ try:
69
+ # 检查服务是否可用
70
+ - service = get_amap_service()
71
+ + service = await asyncio.to_thread(get_amap_service)
72
+
73
+ return {
74
+ "status": "healthy",
75
+ diff --git a/backend/app/api/routes/poi.py b/backend/app/api/routes/poi.py
76
+ index d076ef6..eec9104 100644
77
+ --- a/backend/app/api/routes/poi.py
78
+ +++ b/backend/app/api/routes/poi.py
79
+ @@ -1,5 +1,7 @@
80
+ """POI相关API路由"""
81
+
82
+ +import asyncio
83
+ +
84
+ from fastapi import APIRouter, HTTPException
85
+ from pydantic import BaseModel, Field
86
+ from typing import List, Optional
87
+ @@ -7,6 +9,12 @@
88
+
89
+ router = APIRouter(prefix="/poi", tags=["POI"])
90
+
91
+ +# 本模块路由都是 async def,而 AmapService 连构造带调用都是同步阻塞的:
92
+ +# MCPTool 初始化会 spawn `uvx amap-mcp-server` 并做服务发现
93
+ +# (hello_agents/tools/builtin/protocol_tools.py:124 → :271),run() 也会
94
+ +# 另开线程后 future.result() 等待(同文件 :447-458)。因此统一用
95
+ +# asyncio.to_thread 派发,避免冻结事件循环导致进度推送与轮询一起失效。
96
+ +
97
+
98
+ class POIDetailResponse(BaseModel):
99
+ """POI详情响应"""
100
+ @@ -32,10 +40,10 @@ async def get_poi_detail(poi_id: str):
101
+ POI详情响应
102
+ """
103
+ try:
104
+ - amap_service = get_amap_service()
105
+ + amap_service = await asyncio.to_thread(get_amap_service)
106
+
107
+ # 调用高德地图POI详情API
108
+ - result = amap_service.get_poi_detail(poi_id)
109
+ + result = await asyncio.to_thread(amap_service.get_poi_detail, poi_id)
110
+
111
+ return POIDetailResponse(
112
+ success=True,
113
+ @@ -68,8 +76,8 @@ async def search_poi(keywords: str, city: str = "北京"):
114
+ 搜索结果
115
+ """
116
+ try:
117
+ - amap_service = get_amap_service()
118
+ - result = amap_service.search_poi(keywords, city)
119
+ + amap_service = await asyncio.to_thread(get_amap_service)
120
+ + result = await asyncio.to_thread(amap_service.search_poi, keywords, city)
121
+
122
+ return {
123
+ "success": True,
124
+ diff --git a/backend/app/services/amap_service.py b/backend/app/services/amap_service.py
125
+ index 78458b3..c62b0fa 100644
126
+ --- a/backend/app/services/amap_service.py
127
+ +++ b/backend/app/services/amap_service.py
128
+ @@ -1,5 +1,6 @@
129
+ """高德地图MCP服务封装"""
130
+
131
+ +import threading
132
+ from typing import List, Dict, Any, Optional
133
+ from hello_agents.tools import MCPTool
134
+ from ..config import get_settings
135
+ @@ -7,6 +8,9 @@
136
+
137
+ # 全局MCP工具实例
138
+ _amap_mcp_tool = None
139
+ +# 路由层现在会经 asyncio.to_thread 从多个工作线程调用本模块的取实例函数,
140
+ +# 因此「检查-构造-赋值」这段必须加锁(详见 get_amap_service 的注释)。
141
+ +_amap_mcp_tool_lock = threading.Lock()
142
+
143
+
144
+ def get_amap_mcp_tool() -> MCPTool:
145
+ @@ -19,31 +23,33 @@ def get_amap_mcp_tool() -> MCPTool:
146
+ global _amap_mcp_tool
147
+
148
+ if _amap_mcp_tool is None:
149
+ - settings = get_settings()
150
+ -
151
+ - if not settings.vite_amap_web_key:
152
+ - raise ValueError("高德地图 API Key 未配置,请先在前端设置页完成配置")
153
+ -
154
+ - # 创建MCP工具
155
+ - _amap_mcp_tool = MCPTool(
156
+ - name="amap",
157
+ - description="高德地图服务,支持POI搜索、路线规划、天气查询等功能",
158
+ - server_command=["uvx", "amap-mcp-server"],
159
+ - env={"AMAP_MAPS_API_KEY": settings.vite_amap_web_key},
160
+ - auto_expand=True # 自动展开为独立工具
161
+ - )
162
+ -
163
+ - print(f"✅ 高德地图MCP工具初始化成功")
164
+ - print(f" 工具数量: {len(_amap_mcp_tool._available_tools)}")
165
+ -
166
+ - # 打印可用工具列表
167
+ - if _amap_mcp_tool._available_tools:
168
+ - print(" 可用工具:")
169
+ - for tool in _amap_mcp_tool._available_tools[:5]: # 只打印前5个
170
+ - print(f" - {tool.get('name', 'unknown')}")
171
+ - if len(_amap_mcp_tool._available_tools) > 5:
172
+ - print(f" ... 还有 {len(_amap_mcp_tool._available_tools) - 5} 个工具")
173
+ -
174
+ + with _amap_mcp_tool_lock:
175
+ + if _amap_mcp_tool is None:
176
+ + settings = get_settings()
177
+ +
178
+ + if not settings.vite_amap_web_key:
179
+ + raise ValueError("高德地图 API Key 未配置,请先在前端设置页完成配置")
180
+ +
181
+ + # 创建MCP工具
182
+ + _amap_mcp_tool = MCPTool(
183
+ + name="amap",
184
+ + description="高德地图服务,支持POI搜索、路线规划、天气查询等功能",
185
+ + server_command=["uvx", "amap-mcp-server"],
186
+ + env={"AMAP_MAPS_API_KEY": settings.vite_amap_web_key},
187
+ + auto_expand=True # 自动展开为独立工具
188
+ + )
189
+ +
190
+ + print(f"✅ 高德地图MCP工具初始化成功")
191
+ + print(f" 工具数量: {len(_amap_mcp_tool._available_tools)}")
192
+ +
193
+ + # 打印可用工具列表
194
+ + if _amap_mcp_tool._available_tools:
195
+ + print(" 可用工具:")
196
+ + for tool in _amap_mcp_tool._available_tools[:5]: # 只打印前5个
197
+ + print(f" - {tool.get('name', 'unknown')}")
198
+ + if len(_amap_mcp_tool._available_tools) > 5:
199
+ + print(f" ... 还有 {len(_amap_mcp_tool._available_tools) - 5} 个工具")
200
+ +
201
+ return _amap_mcp_tool
202
+
203
+
204
+ @@ -256,20 +262,29 @@ def get_poi_detail(self, poi_id: str) -> Dict[str, Any]:
205
+
206
+ # 创建全局服务实例
207
+ _amap_service = None
208
+ +_amap_service_lock = threading.Lock()
209
+
210
+
211
+ def get_amap_service() -> AmapService:
212
+ """获取高德地图服务实例(单例模式)"""
213
+ global _amap_service
214
+ -
215
+ +
216
+ if _amap_service is None:
217
+ - _amap_service = AmapService()
218
+ -
219
+ + # 加锁的原因:路由层现在通过 asyncio.to_thread(get_amap_service) 调用本函数,
220
+ + # 并发首次请求会同时进入这里。若不加锁,「检查 - 构造 - 赋值」之间存在窗口,
221
+ + # 多个线程会各建一个 AmapService(每次构造都包含一次 MCP 服务发现往返),
222
+ + # 后写入的覆盖先写入的,多出来的实例被直接丢弃。
223
+ + with _amap_service_lock:
224
+ + if _amap_service is None:
225
+ + _amap_service = AmapService()
226
+ +
227
+ return _amap_service
228
+
229
+
230
+ def reset_amap_service() -> None:
231
+ """重置高德地图服务与 MCP 工具实例(用于运行时配置更新后热生效)。"""
232
+ global _amap_service, _amap_mcp_tool
233
+ - _amap_service = None
234
+ - _amap_mcp_tool = None
235
+ + with _amap_service_lock:
236
+ + _amap_service = None
237
+ + with _amap_mcp_tool_lock:
238
+ + _amap_mcp_tool = None
239
+ diff --git a/backend/tests/test_map_routes_do_not_block_loop.py b/backend/tests/test_map_routes_do_not_block_loop.py
240
+ new file mode 100644
241
+ index 0000000..81c42b3
242
+ --- /dev/null
243
+ +++ b/backend/tests/test_map_routes_do_not_block_loop.py
244
+ @@ -0,0 +1,251 @@
245
+ +"""回归测试:地图 / POI 路由不得阻塞事件循环。
246
+ +
247
+ +背景
248
+ +----
249
+ +``backend/app/api/routes/map.py`` 与 ``poi.py`` 中的路由都是 ``async def``,
250
+ +但它们直接调用了**同步**代码。阻塞来自两处:
251
+ +
252
+ +1. **服务方法调用**(每次请求):``AmapService`` 的方法最终走到 hello_agents
253
+ + 的 ``MCPTool.run()``:
254
+ +
255
+ + * ``hello_agents/tools/builtin/protocol_tools.py:447-458``:另开一个事件循环
256
+ + 放到**工作线程**里执行 MCP 操作,然后 ``return future.result()``——
257
+ + **阻塞当前调用线��**直到整个 MCP 往返结束;
258
+ + * 每次调用都会经 stdio 传输 spawn 一个 ``uvx amap-mcp-server`` 子进程
259
+ + (``hello_agents/protocols/mcp/client.py``),即进程启动 + 握手 + 调用。
260
+ +
261
+ +2. **服务实例构造**(每个进程一次):``get_amap_service()`` 是单例,首次调用会
262
+ + 构造 ``MCPTool``,而 ``MCPTool.__init__`` 在
263
+ + ``protocol_tools.py:124`` 调用 ``self._discover_tools()``,后者同样在
264
+ + ``:271`` 的 ``future.result()`` 上阻塞——即启动后的**第一个**地图 / POI
265
+ + 请求会额外承担一次 MCP 服务发现。
266
+ +
267
+ +两处都发生在事件循环线程上,因此任何一个地图 / POI 请求都会把整个 uvicorn
268
+ +worker 冻结数秒。冻结期间 ``/api/trip/status`` 轮询、``/api/trip/ws/{task_id}``
269
+ +的进度推送、以及其它用户的请求全部停摆。行程规划过程中前端会并发拉取 POI 与
270
+ +景点图片,所以这不是边缘场景。
271
+ +
272
+ +用例做法:用「同步 sleep」的假服务 / 假工厂模拟上述阻塞,同时在旁边跑一个每
273
+ +5ms 递增一次的 ticker。若阻塞留在事件循环线程上,ticker 会被饿死(约 0 次);
274
+ +反之会跑满约 50 次。
275
+ +
276
+ +完全离线:不访问网络、不需要 API Key,也不启动任何子进程。
277
+ +"""
278
+ +
279
+ +import asyncio
280
+ +import contextlib
281
+ +import sys
282
+ +import time
283
+ +import types
284
+ +import unittest
285
+ +from concurrent.futures import ThreadPoolExecutor
286
+ +from pathlib import Path
287
+ +from unittest import mock
288
+ +
289
+ +BACKEND_DIR = Path(__file__).resolve().parent.parent
290
+ +if str(BACKEND_DIR) not in sys.path:
291
+ + sys.path.insert(0, str(BACKEND_DIR))
292
+ +
293
+ +if hasattr(sys.stdout, "reconfigure"):
294
+ + sys.stdout.reconfigure(encoding="utf-8", errors="replace")
295
+ +if hasattr(sys.stderr, "reconfigure"):
296
+ + sys.stderr.reconfigure(encoding="utf-8", errors="replace")
297
+ +
298
+ +from app.api.routes import map as map_routes
299
+ +from app.api.routes import poi as poi_routes
300
+ +from app.models.schemas import RouteRequest
301
+ +from app.services import amap_service
302
+ +
303
+ +# 假阻塞的时长,以及 ticker 的间隔
304
+ +BLOCK_SECONDS = 0.25
305
+ +TICK_INTERVAL = 0.005
306
+ +EXPECTED_TICKS = int(BLOCK_SECONDS / TICK_INTERVAL)
307
+ +# 事件循环只要还能被调度,ticks 就应接近 EXPECTED_TICKS;这里取一个极宽松的
308
+ +# 下限,避免慢速 CI 上偶发失败。
309
+ +MIN_TICKS = 10
310
+ +
311
+ +
312
+ +class _BlockingAmapService:
313
+ + """同步 sleep 的假服务,模拟 MCP 往返对调用线程的阻塞。"""
314
+ +
315
+ + def __init__(self) -> None:
316
+ + self.mcp_tool = types.SimpleNamespace(
317
+ + _available_tools=[{"name": "maps_text_search"}]
318
+ + )
319
+ +
320
+ + def _block(self) -> None:
321
+ + time.sleep(BLOCK_SECONDS)
322
+ +
323
+ + def search_poi(self, *args, **kwargs):
324
+ + self._block()
325
+ + return []
326
+ +
327
+ + def get_weather(self, *args, **kwargs):
328
+ + self._block()
329
+ + return []
330
+ +
331
+ + def plan_route(self, *args, **kwargs):
332
+ + self._block()
333
+ + return None
334
+ +
335
+ + def get_poi_detail(self, *args, **kwargs):
336
+ + self._block()
337
+ + return None
338
+ +
339
+ +
340
+ +def _blocking_factory(service: _BlockingAmapService):
341
+ + """模拟 get_amap_service() 首次构造 MCPTool 时的阻塞。"""
342
+ +
343
+ + def factory():
344
+ + time.sleep(BLOCK_SECONDS)
345
+ + return service
346
+ +
347
+ + return factory
348
+ +
349
+ +
350
+ +async def _ticks_during(coro) -> int:
351
+ + """统计 coro 执行期间事件循环还能调度多少次 ticker。"""
352
+ + ticks = 0
353
+ +
354
+ + async def ticker() -> None:
355
+ + nonlocal ticks
356
+ + while True:
357
+ + ticks += 1
358
+ + await asyncio.sleep(TICK_INTERVAL)
359
+ +
360
+ + task = asyncio.create_task(ticker())
361
+ + try:
362
+ + await coro
363
+ + finally:
364
+ + task.cancel()
365
+ + with contextlib.suppress(asyncio.CancelledError):
366
+ + await task
367
+ + return ticks
368
+ +
369
+ +
370
+ +class _LoopStarvationAssertions(unittest.TestCase):
371
+ + def assert_loop_not_starved(self, coro, label: str) -> None:
372
+ + ticks = asyncio.run(_ticks_during(coro))
373
+ + self.assertGreaterEqual(
374
+ + ticks,
375
+ + MIN_TICKS,
376
+ + f"{label} 执行期间事件循环被阻塞:ticker 只运行了 {ticks} 次"
377
+ + f"(预期约 {EXPECTED_TICKS} 次)。该路由把同步的阻塞调用留在了"
378
+ + f"事件循环线程上,会冻结整个 worker。",
379
+ + )
380
+ +
381
+ +
382
+ +class ServiceMethodDoesNotBlockTheLoopTests(_LoopStarvationAssertions):
383
+ + """每次请求都会发生的阻塞:同步的 AmapService 方法调用。"""
384
+ +
385
+ + def setUp(self) -> None:
386
+ + service = _BlockingAmapService()
387
+ + for module in (map_routes, poi_routes):
388
+ + patcher = mock.patch.object(module, "get_amap_service", return_value=service)
389
+ + patcher.start()
390
+ + self.addCleanup(patcher.stop)
391
+ +
392
+ + def test_map_poi_route_does_not_block_the_loop(self) -> None:
393
+ + self.assert_loop_not_starved(
394
+ + map_routes.search_poi(keywords="故宫", city="北京"),
395
+ + "GET /api/map/poi",
396
+ + )
397
+ +
398
+ + def test_map_weather_route_does_not_block_the_loop(self) -> None:
399
+ + self.assert_loop_not_starved(
400
+ + map_routes.get_weather(city="北京"),
401
+ + "GET /api/map/weather",
402
+ + )
403
+ +
404
+ + def test_map_route_route_does_not_block_the_loop(self) -> None:
405
+ + request = RouteRequest(
406
+ + origin_address="北京市朝阳区阜通东大街6号",
407
+ + destination_address="北京市海淀区上地十街10号",
408
+ + )
409
+ + self.assert_loop_not_starved(
410
+ + map_routes.plan_route(request),
411
+ + "POST /api/map/route",
412
+ + )
413
+ +
414
+ + def test_poi_detail_route_does_not_block_the_loop(self) -> None:
415
+ + self.assert_loop_not_starved(
416
+ + poi_routes.get_poi_detail(poi_id="B000A8UIN8"),
417
+ + "GET /api/poi/detail/{poi_id}",
418
+ + )
419
+ +
420
+ + def test_poi_search_route_does_not_block_the_loop(self) -> None:
421
+ + self.assert_loop_not_starved(
422
+ + poi_routes.search_poi(keywords="故宫", city="北京"),
423
+ + "GET /api/poi/search",
424
+ + )
425
+ +
426
+ +
427
+ +class ServiceCreationDoesNotBlockTheLoopTests(_LoopStarvationAssertions):
428
+ + """每个进程一次的阻塞:get_amap_service() 首次构造 MCPTool 并做服务发现。"""
429
+ +
430
+ + def setUp(self) -> None:
431
+ + service = _BlockingAmapService()
432
+ + for module in (map_routes, poi_routes):
433
+ + patcher = mock.patch.object(
434
+ + module, "get_amap_service", new=_blocking_factory(service)
435
+ + )
436
+ + patcher.start()
437
+ + self.addCleanup(patcher.stop)
438
+ +
439
+ + def test_map_poi_route_does_not_block_on_service_creation(self) -> None:
440
+ + self.assert_loop_not_starved(
441
+ + map_routes.search_poi(keywords="故宫", city="北京"),
442
+ + "GET /api/map/poi 的服务实例构造",
443
+ + )
444
+ +
445
+ + def test_map_weather_route_does_not_block_on_service_creation(self) -> None:
446
+ + self.assert_loop_not_starved(
447
+ + map_routes.get_weather(city="北京"),
448
+ + "GET /api/map/weather 的服务实例构造",
449
+ + )
450
+ +
451
+ + def test_poi_search_route_does_not_block_on_service_creation(self) -> None:
452
+ + self.assert_loop_not_starved(
453
+ + poi_routes.search_poi(keywords="故宫", city="北京"),
454
+ + "GET /api/poi/search 的服务实例构造",
455
+ + )
456
+ +
457
+ +
458
+ +class ServiceSingletonIsThreadSafeTests(unittest.TestCase):
459
+ + """把取实例挪进线程后,单例本身必须线程安全。
460
+ +
461
+ + 改动前 get_amap_service() 在事件循环线程上被调用,事件循环天然把
462
+ + 「检查 - 构造 - 赋值」串行化了。改成 asyncio.to_thread 之后,并发首次请求
463
+ + 会同时进入该函数:若不加锁,多个线程都会看到 _amap_service is None 而各建
464
+ + 一个 AmapService——而每次构造都包含一次 MCP 服务发现往返,多出来的实例
465
+ + 随即被覆盖丢弃。
466
+ + """
467
+ +
468
+ + def test_concurrent_first_calls_create_exactly_one_instance(self) -> None:
469
+ + created = []
470
+ +
471
+ + class _SlowService:
472
+ + def __init__(self) -> None:
473
+ + # 放大构造窗口,使竞争在未加锁时能稳定复现
474
+ + time.sleep(0.05)
475
+ + created.append(self)
476
+ +
477
+ + workers = 8
478
+ + with mock.patch.object(amap_service, "AmapService", _SlowService), mock.patch.object(
479
+ + amap_service, "_amap_service", None
480
+ + ):
481
+ + with ThreadPoolExecutor(max_workers=workers) as pool:
482
+ + results = list(
483
+ + pool.map(lambda _: amap_service.get_amap_service(), range(workers))
484
+ + )
485
+ +
486
+ + self.assertEqual(
487
+ + len(created),
488
+ + 1,
489
+ + f"并发首次调用构造了 {len(created)} 个实例(应为 1)——单例存在竞态",
490
+ + )
491
+ + self.assertEqual(len({id(r) for r in results}), 1, "并发调用返回了不同实例")
492
+ +
493
+ +
494
+ +if __name__ == "__main__":
495
+ + unittest.main()
tasks/1sdv__TripStar-49/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/1sdv__TripStar-49/task.toml ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version = "1.0"
2
+
3
+ [task]
4
+ name = "trending/1sdv__TripStar-49"
5
+ description = "Fix/offload blocking map calls"
6
+
7
+ [metadata]
8
+ difficulty = "large"
9
+ category = "bugfix"
10
+ keywords = [
11
+ "TripStar",
12
+ "pr_diff",
13
+ ]
14
+
15
+ [metadata.repo2env]
16
+ pipeline = "pr_diff"
17
+ pipeline_version = "0.3.0"
18
+ repo = "1sdv/TripStar"
19
+ ref = "1dce6df8f358a8650693e201aa4cb1d974a688bd"
20
+ reference = "https://github.com/1sdv/TripStar/pull/49"
21
+ source_access = "auto"
22
+ built_at = "2026-11-16T16:09:43.778575+00:00"
23
+ reward_kinds = [
24
+ "diff_similarity",
25
+ ]
26
+ spec_version = "0.2.0"
27
+ content_hash = "sha256:5d0a3d6a0ae7daac7badef53a4319fb44144f03671a91a7bfeb9008453a3516f"
28
+
29
+ [metadata.repo2env.pr_diff]
30
+ pr_merged_at = "2026-10-07T02:44:30Z"
31
+ diff_format = "unified"
32
+ context_files = [
33
+ "backend/app/api/routes/map.py",
34
+ "backend/app/api/routes/poi.py",
35
+ "backend/app/services/amap_service.py",
36
+ "backend/tests/test_map_routes_do_not_block_loop.py",
37
+ ]
38
+ bootstrap_image = "python:3.12-slim"
39
+
40
+ [metadata.repo2env.reward_calibration]
41
+ baseline_reward = 0.0
42
+ loc_changed = 365
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:19:57.790472+00:00"
62
+ pushed_by = "scalingX"
63
+ inline_recipe_sha256 = "sha256:fd78f06b44f013d2f632e19b45c2d06fb91c7c2cc74e229086fa557091b3d864"
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/1sdv__TripStar-49/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/1sdv__TripStar-49/tests/instruction.md ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Issue
2
+
3
+ **Title:** Fix/offload blocking map calls
4
+
5
+ ## Description
6
+
7
+ ## What does this PR do?
8
+
9
+ <!-- Briefly describe what this PR accomplishes -->
10
+
11
+ ## Why is this change needed?
12
+
13
+ <!-- Explain the motivation and context -->
14
+
15
+ ## Related Issues
16
+
17
+ <!-- Link related issues: , -->
18
+
19
+ ## Type of Change
20
+
21
+ - [ ] Feature
22
+ - [ ] Bug fix
23
+ - [ ] Documentation
24
+ - [ ] Refactor
25
+ - [ ] Other
26
+
27
+ ## Testing
28
+
29
+ <!-- Describe how you tested this -->
30
+
31
+ ## Screenshots (if applicable)
32
+
33
+ <!-- Add before/after screenshots here -->
34
+
35
+ ## Checklist
36
+
37
+ - [ ] Code follows project style guidelines
38
+ - [ ] Tests pass locally
39
+ - [ ] Documentation updated (if needed)
40
+ - [ ] No breaking changes introduced
41
+
42
+ ## Task
43
+
44
+ Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `1dce6df8f358`. Edit files 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/1sdv__TripStar-49/tests/oracle.patch ADDED
@@ -0,0 +1,495 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/backend/app/api/routes/map.py b/backend/app/api/routes/map.py
2
+ index 8719fde..d12a453 100644
3
+ --- a/backend/app/api/routes/map.py
4
+ +++ b/backend/app/api/routes/map.py
5
+ @@ -1,5 +1,7 @@
6
+ """地图服务API路由"""
7
+
8
+ +import asyncio
9
+ +
10
+ from fastapi import APIRouter, HTTPException, Query
11
+ from typing import Optional
12
+ from ...models.schemas import (
13
+ @@ -14,6 +16,12 @@
14
+
15
+ router = APIRouter(prefix="/map", tags=["地图服务"])
16
+
17
+ +# 本模块路由都是 async def,而 AmapService 连构造带调用都是同步阻塞的:
18
+ +# MCPTool 初始化会 spawn `uvx amap-mcp-server` 并做服务发现
19
+ +# (hello_agents/tools/builtin/protocol_tools.py:124 → :271),run() 也会
20
+ +# 另开线程后 future.result() 等待(同文件 :447-458)。因此统一用
21
+ +# asyncio.to_thread 派发,避免冻结事件循环导致进度推送与轮询一起失效。
22
+ +
23
+
24
+ @router.get(
25
+ "/poi",
26
+ @@ -39,10 +47,10 @@ async def search_poi(
27
+ """
28
+ try:
29
+ # 获取服务实例
30
+ - service = get_amap_service()
31
+ + service = await asyncio.to_thread(get_amap_service)
32
+
33
+ # 搜索POI
34
+ - pois = service.search_poi(keywords, city, citylimit)
35
+ + pois = await asyncio.to_thread(service.search_poi, keywords, city, citylimit)
36
+
37
+ return POISearchResponse(
38
+ success=bool(pois),
39
+ @@ -78,10 +86,10 @@ async def get_weather(
40
+ """
41
+ try:
42
+ # 获取服务实例
43
+ - service = get_amap_service()
44
+ + service = await asyncio.to_thread(get_amap_service)
45
+
46
+ # 查询天气
47
+ - weather_info = service.get_weather(city)
48
+ + weather_info = await asyncio.to_thread(service.get_weather, city)
49
+
50
+ return WeatherResponse(
51
+ success=bool(weather_info),
52
+ @@ -115,10 +123,11 @@ async def plan_route(request: RouteRequest):
53
+ """
54
+ try:
55
+ # 获取服务实例
56
+ - service = get_amap_service()
57
+ + service = await asyncio.to_thread(get_amap_service)
58
+
59
+ # 规划路线
60
+ - route_info = service.plan_route(
61
+ + route_info = await asyncio.to_thread(
62
+ + service.plan_route,
63
+ origin_address=request.origin_address,
64
+ destination_address=request.destination_address,
65
+ origin_city=request.origin_city,
66
+ @@ -161,7 +170,7 @@ async def health_check():
67
+ """健康检查"""
68
+ try:
69
+ # 检查服务是否可用
70
+ - service = get_amap_service()
71
+ + service = await asyncio.to_thread(get_amap_service)
72
+
73
+ return {
74
+ "status": "healthy",
75
+ diff --git a/backend/app/api/routes/poi.py b/backend/app/api/routes/poi.py
76
+ index d076ef6..eec9104 100644
77
+ --- a/backend/app/api/routes/poi.py
78
+ +++ b/backend/app/api/routes/poi.py
79
+ @@ -1,5 +1,7 @@
80
+ """POI相关API路由"""
81
+
82
+ +import asyncio
83
+ +
84
+ from fastapi import APIRouter, HTTPException
85
+ from pydantic import BaseModel, Field
86
+ from typing import List, Optional
87
+ @@ -7,6 +9,12 @@
88
+
89
+ router = APIRouter(prefix="/poi", tags=["POI"])
90
+
91
+ +# 本模块路由都是 async def,而 AmapService 连构造带调用都是同步阻塞的:
92
+ +# MCPTool 初始化会 spawn `uvx amap-mcp-server` 并做服务发现
93
+ +# (hello_agents/tools/builtin/protocol_tools.py:124 → :271),run() 也会
94
+ +# 另开线程后 future.result() 等待(同文件 :447-458)。因此统一用
95
+ +# asyncio.to_thread 派发,避免冻结事件循环导致进度推送与轮询一起失效。
96
+ +
97
+
98
+ class POIDetailResponse(BaseModel):
99
+ """POI详情响应"""
100
+ @@ -32,10 +40,10 @@ async def get_poi_detail(poi_id: str):
101
+ POI详情响应
102
+ """
103
+ try:
104
+ - amap_service = get_amap_service()
105
+ + amap_service = await asyncio.to_thread(get_amap_service)
106
+
107
+ # 调用高德地图POI详情API
108
+ - result = amap_service.get_poi_detail(poi_id)
109
+ + result = await asyncio.to_thread(amap_service.get_poi_detail, poi_id)
110
+
111
+ return POIDetailResponse(
112
+ success=True,
113
+ @@ -68,8 +76,8 @@ async def search_poi(keywords: str, city: str = "北京"):
114
+ 搜索结果
115
+ """
116
+ try:
117
+ - amap_service = get_amap_service()
118
+ - result = amap_service.search_poi(keywords, city)
119
+ + amap_service = await asyncio.to_thread(get_amap_service)
120
+ + result = await asyncio.to_thread(amap_service.search_poi, keywords, city)
121
+
122
+ return {
123
+ "success": True,
124
+ diff --git a/backend/app/services/amap_service.py b/backend/app/services/amap_service.py
125
+ index 78458b3..c62b0fa 100644
126
+ --- a/backend/app/services/amap_service.py
127
+ +++ b/backend/app/services/amap_service.py
128
+ @@ -1,5 +1,6 @@
129
+ """高德地图MCP服务封装"""
130
+
131
+ +import threading
132
+ from typing import List, Dict, Any, Optional
133
+ from hello_agents.tools import MCPTool
134
+ from ..config import get_settings
135
+ @@ -7,6 +8,9 @@
136
+
137
+ # 全局MCP工具实例
138
+ _amap_mcp_tool = None
139
+ +# 路由层现在会经 asyncio.to_thread 从多个工作线程调用本模块的取实例函数,
140
+ +# 因此「检查-构造-赋值」这段必须加锁(详见 get_amap_service 的注释)。
141
+ +_amap_mcp_tool_lock = threading.Lock()
142
+
143
+
144
+ def get_amap_mcp_tool() -> MCPTool:
145
+ @@ -19,31 +23,33 @@ def get_amap_mcp_tool() -> MCPTool:
146
+ global _amap_mcp_tool
147
+
148
+ if _amap_mcp_tool is None:
149
+ - settings = get_settings()
150
+ -
151
+ - if not settings.vite_amap_web_key:
152
+ - raise ValueError("高德地图 API Key 未配置,请先在前端设置页完成配置")
153
+ -
154
+ - # 创建MCP工具
155
+ - _amap_mcp_tool = MCPTool(
156
+ - name="amap",
157
+ - description="高德地图服务,支持POI搜索、路线规划、天气查询等功能",
158
+ - server_command=["uvx", "amap-mcp-server"],
159
+ - env={"AMAP_MAPS_API_KEY": settings.vite_amap_web_key},
160
+ - auto_expand=True # 自动展开为独立工具
161
+ - )
162
+ -
163
+ - print(f"✅ 高德地图MCP工具初始化成功")
164
+ - print(f" 工具数量: {len(_amap_mcp_tool._available_tools)}")
165
+ -
166
+ - # 打印可用工具列表
167
+ - if _amap_mcp_tool._available_tools:
168
+ - print(" 可用工具:")
169
+ - for tool in _amap_mcp_tool._available_tools[:5]: # 只打印前5个
170
+ - print(f" - {tool.get('name', 'unknown')}")
171
+ - if len(_amap_mcp_tool._available_tools) > 5:
172
+ - print(f" ... 还有 {len(_amap_mcp_tool._available_tools) - 5} 个工具")
173
+ -
174
+ + with _amap_mcp_tool_lock:
175
+ + if _amap_mcp_tool is None:
176
+ + settings = get_settings()
177
+ +
178
+ + if not settings.vite_amap_web_key:
179
+ + raise ValueError("高德地图 API Key 未配置,请先在前端设置页完成配置")
180
+ +
181
+ + # 创建MCP工具
182
+ + _amap_mcp_tool = MCPTool(
183
+ + name="amap",
184
+ + description="高德地图服务,支持POI搜索、路线规划、天气查询等功能",
185
+ + server_command=["uvx", "amap-mcp-server"],
186
+ + env={"AMAP_MAPS_API_KEY": settings.vite_amap_web_key},
187
+ + auto_expand=True # 自动展开为独立工具
188
+ + )
189
+ +
190
+ + print(f"✅ 高德地图MCP工具初始化成功")
191
+ + print(f" 工具数量: {len(_amap_mcp_tool._available_tools)}")
192
+ +
193
+ + # 打印可用工具列表
194
+ + if _amap_mcp_tool._available_tools:
195
+ + print(" 可用工具:")
196
+ + for tool in _amap_mcp_tool._available_tools[:5]: # 只打印前5个
197
+ + print(f" - {tool.get('name', 'unknown')}")
198
+ + if len(_amap_mcp_tool._available_tools) > 5:
199
+ + print(f" ... 还有 {len(_amap_mcp_tool._available_tools) - 5} 个工具")
200
+ +
201
+ return _amap_mcp_tool
202
+
203
+
204
+ @@ -256,20 +262,29 @@ def get_poi_detail(self, poi_id: str) -> Dict[str, Any]:
205
+
206
+ # 创建全局服务实例
207
+ _amap_service = None
208
+ +_amap_service_lock = threading.Lock()
209
+
210
+
211
+ def get_amap_service() -> AmapService:
212
+ """获取高德地图服务实例(单例模式)"""
213
+ global _amap_service
214
+ -
215
+ +
216
+ if _amap_service is None:
217
+ - _amap_service = AmapService()
218
+ -
219
+ + # 加锁的原因:路由层现在通过 asyncio.to_thread(get_amap_service) 调用本函数,
220
+ + # 并发首次请求会同时进入这里。若不加锁,「检查 - 构造 - 赋值」之间存在窗口,
221
+ + # 多个线程会各建一个 AmapService(每次构造都包含一次 MCP 服务发现往返),
222
+ + # 后写入的覆盖先写入的,多出来的实例被直接丢弃。
223
+ + with _amap_service_lock:
224
+ + if _amap_service is None:
225
+ + _amap_service = AmapService()
226
+ +
227
+ return _amap_service
228
+
229
+
230
+ def reset_amap_service() -> None:
231
+ """重置高德地图服务与 MCP 工具实例(用于运行时配置更新后热生效)。"""
232
+ global _amap_service, _amap_mcp_tool
233
+ - _amap_service = None
234
+ - _amap_mcp_tool = None
235
+ + with _amap_service_lock:
236
+ + _amap_service = None
237
+ + with _amap_mcp_tool_lock:
238
+ + _amap_mcp_tool = None
239
+ diff --git a/backend/tests/test_map_routes_do_not_block_loop.py b/backend/tests/test_map_routes_do_not_block_loop.py
240
+ new file mode 100644
241
+ index 0000000..81c42b3
242
+ --- /dev/null
243
+ +++ b/backend/tests/test_map_routes_do_not_block_loop.py
244
+ @@ -0,0 +1,251 @@
245
+ +"""回归测试:地图 / POI 路由不得阻塞事件循环。
246
+ +
247
+ +背景
248
+ +----
249
+ +``backend/app/api/routes/map.py`` 与 ``poi.py`` 中的路由都是 ``async def``,
250
+ +但它们直接调用了**同步**代码。阻塞来自两处:
251
+ +
252
+ +1. **服务方法调用**(每次请求):``AmapService`` 的方法最终走到 hello_agents
253
+ + 的 ``MCPTool.run()``:
254
+ +
255
+ + * ``hello_agents/tools/builtin/protocol_tools.py:447-458``:另开一个事件循环
256
+ + 放到**工作线程**里执行 MCP 操作,然后 ``return future.result()``——
257
+ + **阻塞当前调用线��**直到整个 MCP 往返结束;
258
+ + * 每次调用都会经 stdio 传输 spawn 一个 ``uvx amap-mcp-server`` 子进程
259
+ + (``hello_agents/protocols/mcp/client.py``),即进程启动 + 握手 + 调用。
260
+ +
261
+ +2. **服务实例构造**(每个进程一次):``get_amap_service()`` 是单例,首次调用会
262
+ + 构造 ``MCPTool``,而 ``MCPTool.__init__`` 在
263
+ + ``protocol_tools.py:124`` 调用 ``self._discover_tools()``,后者同样在
264
+ + ``:271`` 的 ``future.result()`` 上阻塞——即启动后的**第一个**地图 / POI
265
+ + 请求会额外承担一次 MCP 服务发现。
266
+ +
267
+ +两处都发生在事件循环线程上,因此任何一个地图 / POI 请求都会把整个 uvicorn
268
+ +worker 冻结数秒。冻结期间 ``/api/trip/status`` 轮询、``/api/trip/ws/{task_id}``
269
+ +的进度推送、以及其它用户的请求全部停摆。行程规划过程中前端会并发拉取 POI 与
270
+ +景点图片,所以这不是边缘场景。
271
+ +
272
+ +用例做法:用「同步 sleep」的假服务 / 假工厂模拟上述阻塞,同时在旁边跑一个每
273
+ +5ms 递增一次的 ticker。若阻塞留在事件循环线程上,ticker 会被饿死(约 0 次);
274
+ +反之会跑满约 50 次。
275
+ +
276
+ +完全离线:不访问网络、不需要 API Key,也不启动任何子进程。
277
+ +"""
278
+ +
279
+ +import asyncio
280
+ +import contextlib
281
+ +import sys
282
+ +import time
283
+ +import types
284
+ +import unittest
285
+ +from concurrent.futures import ThreadPoolExecutor
286
+ +from pathlib import Path
287
+ +from unittest import mock
288
+ +
289
+ +BACKEND_DIR = Path(__file__).resolve().parent.parent
290
+ +if str(BACKEND_DIR) not in sys.path:
291
+ + sys.path.insert(0, str(BACKEND_DIR))
292
+ +
293
+ +if hasattr(sys.stdout, "reconfigure"):
294
+ + sys.stdout.reconfigure(encoding="utf-8", errors="replace")
295
+ +if hasattr(sys.stderr, "reconfigure"):
296
+ + sys.stderr.reconfigure(encoding="utf-8", errors="replace")
297
+ +
298
+ +from app.api.routes import map as map_routes
299
+ +from app.api.routes import poi as poi_routes
300
+ +from app.models.schemas import RouteRequest
301
+ +from app.services import amap_service
302
+ +
303
+ +# 假阻塞的时长,以及 ticker 的间隔
304
+ +BLOCK_SECONDS = 0.25
305
+ +TICK_INTERVAL = 0.005
306
+ +EXPECTED_TICKS = int(BLOCK_SECONDS / TICK_INTERVAL)
307
+ +# 事件循环只要还能被调度,ticks 就应接近 EXPECTED_TICKS;这里取一个极宽松的
308
+ +# 下限,避免慢速 CI 上偶发失败。
309
+ +MIN_TICKS = 10
310
+ +
311
+ +
312
+ +class _BlockingAmapService:
313
+ + """同步 sleep 的假服务,模拟 MCP 往返对调用线程的阻塞。"""
314
+ +
315
+ + def __init__(self) -> None:
316
+ + self.mcp_tool = types.SimpleNamespace(
317
+ + _available_tools=[{"name": "maps_text_search"}]
318
+ + )
319
+ +
320
+ + def _block(self) -> None:
321
+ + time.sleep(BLOCK_SECONDS)
322
+ +
323
+ + def search_poi(self, *args, **kwargs):
324
+ + self._block()
325
+ + return []
326
+ +
327
+ + def get_weather(self, *args, **kwargs):
328
+ + self._block()
329
+ + return []
330
+ +
331
+ + def plan_route(self, *args, **kwargs):
332
+ + self._block()
333
+ + return None
334
+ +
335
+ + def get_poi_detail(self, *args, **kwargs):
336
+ + self._block()
337
+ + return None
338
+ +
339
+ +
340
+ +def _blocking_factory(service: _BlockingAmapService):
341
+ + """模拟 get_amap_service() 首次构造 MCPTool 时的阻塞。"""
342
+ +
343
+ + def factory():
344
+ + time.sleep(BLOCK_SECONDS)
345
+ + return service
346
+ +
347
+ + return factory
348
+ +
349
+ +
350
+ +async def _ticks_during(coro) -> int:
351
+ + """统计 coro 执行期间事件循环还能调度多少次 ticker。"""
352
+ + ticks = 0
353
+ +
354
+ + async def ticker() -> None:
355
+ + nonlocal ticks
356
+ + while True:
357
+ + ticks += 1
358
+ + await asyncio.sleep(TICK_INTERVAL)
359
+ +
360
+ + task = asyncio.create_task(ticker())
361
+ + try:
362
+ + await coro
363
+ + finally:
364
+ + task.cancel()
365
+ + with contextlib.suppress(asyncio.CancelledError):
366
+ + await task
367
+ + return ticks
368
+ +
369
+ +
370
+ +class _LoopStarvationAssertions(unittest.TestCase):
371
+ + def assert_loop_not_starved(self, coro, label: str) -> None:
372
+ + ticks = asyncio.run(_ticks_during(coro))
373
+ + self.assertGreaterEqual(
374
+ + ticks,
375
+ + MIN_TICKS,
376
+ + f"{label} 执行期间事件循环被阻塞:ticker 只运行了 {ticks} 次"
377
+ + f"(预期约 {EXPECTED_TICKS} 次)。该路由把同步的阻塞调用留在了"
378
+ + f"事件循环线程上,会冻结整个 worker。",
379
+ + )
380
+ +
381
+ +
382
+ +class ServiceMethodDoesNotBlockTheLoopTests(_LoopStarvationAssertions):
383
+ + """每次请求都会发生的阻塞:同步的 AmapService 方法调用。"""
384
+ +
385
+ + def setUp(self) -> None:
386
+ + service = _BlockingAmapService()
387
+ + for module in (map_routes, poi_routes):
388
+ + patcher = mock.patch.object(module, "get_amap_service", return_value=service)
389
+ + patcher.start()
390
+ + self.addCleanup(patcher.stop)
391
+ +
392
+ + def test_map_poi_route_does_not_block_the_loop(self) -> None:
393
+ + self.assert_loop_not_starved(
394
+ + map_routes.search_poi(keywords="故宫", city="北京"),
395
+ + "GET /api/map/poi",
396
+ + )
397
+ +
398
+ + def test_map_weather_route_does_not_block_the_loop(self) -> None:
399
+ + self.assert_loop_not_starved(
400
+ + map_routes.get_weather(city="北京"),
401
+ + "GET /api/map/weather",
402
+ + )
403
+ +
404
+ + def test_map_route_route_does_not_block_the_loop(self) -> None:
405
+ + request = RouteRequest(
406
+ + origin_address="北京市朝阳区阜通东大街6号",
407
+ + destination_address="北京市海淀区上地十街10号",
408
+ + )
409
+ + self.assert_loop_not_starved(
410
+ + map_routes.plan_route(request),
411
+ + "POST /api/map/route",
412
+ + )
413
+ +
414
+ + def test_poi_detail_route_does_not_block_the_loop(self) -> None:
415
+ + self.assert_loop_not_starved(
416
+ + poi_routes.get_poi_detail(poi_id="B000A8UIN8"),
417
+ + "GET /api/poi/detail/{poi_id}",
418
+ + )
419
+ +
420
+ + def test_poi_search_route_does_not_block_the_loop(self) -> None:
421
+ + self.assert_loop_not_starved(
422
+ + poi_routes.search_poi(keywords="故宫", city="北京"),
423
+ + "GET /api/poi/search",
424
+ + )
425
+ +
426
+ +
427
+ +class ServiceCreationDoesNotBlockTheLoopTests(_LoopStarvationAssertions):
428
+ + """每个进程一次的阻塞:get_amap_service() 首次构造 MCPTool 并做服务发现。"""
429
+ +
430
+ + def setUp(self) -> None:
431
+ + service = _BlockingAmapService()
432
+ + for module in (map_routes, poi_routes):
433
+ + patcher = mock.patch.object(
434
+ + module, "get_amap_service", new=_blocking_factory(service)
435
+ + )
436
+ + patcher.start()
437
+ + self.addCleanup(patcher.stop)
438
+ +
439
+ + def test_map_poi_route_does_not_block_on_service_creation(self) -> None:
440
+ + self.assert_loop_not_starved(
441
+ + map_routes.search_poi(keywords="故宫", city="北京"),
442
+ + "GET /api/map/poi 的服务实例构造",
443
+ + )
444
+ +
445
+ + def test_map_weather_route_does_not_block_on_service_creation(self) -> None:
446
+ + self.assert_loop_not_starved(
447
+ + map_routes.get_weather(city="北京"),
448
+ + "GET /api/map/weather 的服务实例构造",
449
+ + )
450
+ +
451
+ + def test_poi_search_route_does_not_block_on_service_creation(self) -> None:
452
+ + self.assert_loop_not_starved(
453
+ + poi_routes.search_poi(keywords="故宫", city="北京"),
454
+ + "GET /api/poi/search 的服务实例构造",
455
+ + )
456
+ +
457
+ +
458
+ +class ServiceSingletonIsThreadSafeTests(unittest.TestCase):
459
+ + """把取实例挪进线程后,单例本身必须线程安全。
460
+ +
461
+ + 改动前 get_amap_service() 在事件循环线程上被调用,事件循环天然把
462
+ + 「检查 - 构造 - 赋值」串行化了。改成 asyncio.to_thread 之后,并发首次请求
463
+ + 会同时进入该函数:若不加锁,多个线程都会看到 _amap_service is None 而各建
464
+ + 一个 AmapService——而每次构造都包含一次 MCP 服务发现往返,多出来的实例
465
+ + 随即被覆盖丢弃。
466
+ + """
467
+ +
468
+ + def test_concurrent_first_calls_create_exactly_one_instance(self) -> None:
469
+ + created = []
470
+ +
471
+ + class _SlowService:
472
+ + def __init__(self) -> None:
473
+ + # 放大构造窗口,使竞争在未加锁时能稳定复现
474
+ + time.sleep(0.05)
475
+ + created.append(self)
476
+ +
477
+ + workers = 8
478
+ + with mock.patch.object(amap_service, "AmapService", _SlowService), mock.patch.object(
479
+ + amap_service, "_amap_service", None
480
+ + ):
481
+ + with ThreadPoolExecutor(max_workers=workers) as pool:
482
+ + results = list(
483
+ + pool.map(lambda _: amap_service.get_amap_service(), range(workers))
484
+ + )
485
+ +
486
+ + self.assertEqual(
487
+ + len(created),
488
+ + 1,
489
+ + f"并发首次调用构造了 {len(created)} 个实例(应为 1)——单例存在竞态",
490
+ + )
491
+ + self.assertEqual(len({id(r) for r in results}), 1, "并发调用返回了不同实例")
492
+ +
493
+ +
494
+ +if __name__ == "__main__":
495
+ + unittest.main()