Zanehpn commited on
Commit
11be211
·
verified ·
1 Parent(s): b31d575

Add Phoenix-bench code and evaluation artifacts

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +9 -0
  2. Repos/HWE/README.md +63 -0
  3. Repos/HWE/agents/Agentless/.gitignore +187 -0
  4. Repos/HWE/agents/Agentless/.pre-commit-config.yaml +21 -0
  5. Repos/HWE/agents/Agentless/LICENSE +21 -0
  6. Repos/HWE/agents/Agentless/README.md +102 -0
  7. Repos/HWE/agents/Agentless/README_swebench.md +374 -0
  8. Repos/HWE/agents/Agentless/agentless/fl/FL.py +775 -0
  9. Repos/HWE/agents/Agentless/agentless/fl/Index.py +333 -0
  10. Repos/HWE/agents/Agentless/agentless/fl/combine.py +82 -0
  11. Repos/HWE/agents/Agentless/agentless/fl/localize.py +680 -0
  12. Repos/HWE/agents/Agentless/agentless/fl/retrieve.py +204 -0
  13. Repos/HWE/agents/Agentless/agentless/repair/repair.py +855 -0
  14. Repos/HWE/agents/Agentless/agentless/repair/rerank.py +343 -0
  15. Repos/HWE/agents/Agentless/agentless/test/generate_reproduction_tests.py +554 -0
  16. Repos/HWE/agents/Agentless/agentless/test/run_regression_tests.py +254 -0
  17. Repos/HWE/agents/Agentless/agentless/test/run_reproduction_tests.py +170 -0
  18. Repos/HWE/agents/Agentless/agentless/test/run_tests.py +630 -0
  19. Repos/HWE/agents/Agentless/agentless/test/select_regression_tests.py +220 -0
  20. Repos/HWE/agents/Agentless/agentless/util/api_requests.py +192 -0
  21. Repos/HWE/agents/Agentless/agentless/util/compress_file.py +220 -0
  22. Repos/HWE/agents/Agentless/agentless/util/index_skeleton.py +73 -0
  23. Repos/HWE/agents/Agentless/agentless/util/model.py +421 -0
  24. Repos/HWE/agents/Agentless/agentless/util/parse_global_var.py +93 -0
  25. Repos/HWE/agents/Agentless/agentless/util/postprocess_data.py +1176 -0
  26. Repos/HWE/agents/Agentless/agentless/util/preprocess_data.py +868 -0
  27. Repos/HWE/agents/Agentless/agentless/util/utils.py +93 -0
  28. Repos/HWE/agents/Agentless/agentless_solutions.tar.gz +3 -0
  29. Repos/HWE/agents/Agentless/batch_run.sh +14 -0
  30. Repos/HWE/agents/Agentless/build_dataset.py +108 -0
  31. Repos/HWE/agents/Agentless/build_solutions.py +115 -0
  32. Repos/HWE/agents/Agentless/classification/README.md +40 -0
  33. Repos/HWE/agents/Agentless/classification/graph_classification.py +199 -0
  34. Repos/HWE/agents/Agentless/classification/load_filtered_benchmark.py +71 -0
  35. Repos/HWE/agents/Agentless/classification/requirements_graph.txt +2 -0
  36. Repos/HWE/agents/Agentless/classification/swebench_lite_classifications.csv +0 -0
  37. Repos/HWE/agents/Agentless/get_repo_structure/get_patch_info.py +72 -0
  38. Repos/HWE/agents/Agentless/get_repo_structure/get_repo_structure.py +376 -0
  39. Repos/HWE/agents/Agentless/requirements.txt +9 -0
  40. Repos/HWE/agents/Agentless/resources/comparison_graph.png +3 -0
  41. Repos/HWE/agents/Agentless/run_agentless.py +359 -0
  42. Repos/HWE/agents/Agentless/run_agentless.sh +112 -0
  43. Repos/HWE/agents/Agentless/tally_token_use.py +352 -0
  44. Repos/HWE/agents/Agentless/test_agentless/apfaudio_eurorack-pmod_pr36/.gitattributes +1 -0
  45. Repos/HWE/agents/Agentless/test_agentless/apfaudio_eurorack-pmod_pr36/.gitignore +28 -0
  46. Repos/HWE/agents/Agentless/test_agentless/apfaudio_eurorack-pmod_pr36/.gitmodules +6 -0
  47. Repos/HWE/agents/Agentless/test_agentless/apfaudio_eurorack-pmod_pr36/LICENSE +289 -0
  48. Repos/HWE/agents/Agentless/test_agentless/apfaudio_eurorack-pmod_pr36/README.md +135 -0
  49. Repos/HWE/agents/Agentless/test_agentless/apfaudio_eurorack-pmod_pr36/docs/img/labelled.jpg +3 -0
  50. Repos/HWE/agents/Agentless/test_agentless/apfaudio_eurorack-pmod_pr36/docs/img/leds_front.jpg +3 -0
.gitattributes CHANGED
@@ -796,3 +796,12 @@ snapshots/FPGA-MAFIA_fpga_mafia_pr479/FPGA/SDRAM_RTL_Test/DE10_LITE_SDRAM_RTL_Te
796
  snapshots/FPGA-MAFIA_fpga_mafia_pr479/FPGA/SDRAM_RTL_Test/DE10_LITE_SDRAM_RTL_Test.pof filter=lfs diff=lfs merge=lfs -text
797
  snapshots/FPGA-MAFIA_fpga_mafia_pr479/FPGA/SDRAM_RTL_Test/demo_batch/DE10_LITE_SDRAM_RTL_Test.sof filter=lfs diff=lfs merge=lfs -text
798
  snapshots/jotego_jtcores_pr960/cores/s16b/doc/315-5195_schematics.pdf filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
796
  snapshots/FPGA-MAFIA_fpga_mafia_pr479/FPGA/SDRAM_RTL_Test/DE10_LITE_SDRAM_RTL_Test.pof filter=lfs diff=lfs merge=lfs -text
797
  snapshots/FPGA-MAFIA_fpga_mafia_pr479/FPGA/SDRAM_RTL_Test/demo_batch/DE10_LITE_SDRAM_RTL_Test.sof filter=lfs diff=lfs merge=lfs -text
798
  snapshots/jotego_jtcores_pr960/cores/s16b/doc/315-5195_schematics.pdf filter=lfs diff=lfs merge=lfs -text
799
+ Repos/HWE/agents/Agentless/test_agentless/apfaudio_eurorack-pmod_pr36/hardware/datasheets/XZMDKVG55W-4.pdf filter=lfs diff=lfs merge=lfs -text
800
+ Repos/HWE/agents/Agentless/test_agentless/apfaudio_eurorack-pmod_pr36/hardware/datasheets/ak4619vn-en-datasheet.pdf filter=lfs diff=lfs merge=lfs -text
801
+ Repos/HWE/agents/Agentless/test_agentless/apfaudio_eurorack-pmod_pr36/hardware/datasheets/pj-301b.pdf filter=lfs diff=lfs merge=lfs -text
802
+ Repos/HWE/agents/Agentless/test_agentless/apfaudio_eurorack-pmod_pr36/hardware/datasheets/pj-324m0.pdf filter=lfs diff=lfs merge=lfs -text
803
+ Repos/HWE/agents/Agentless/test_agentless/apfaudio_eurorack-pmod_pr36/hardware/datasheets/pmod-interface-specification-1_2_0.pdf filter=lfs diff=lfs merge=lfs -text
804
+ Repos/HWE/agents/Lingxi/docs/Lingxi[[:space:]]Technical[[:space:]]Report[[:space:]]2505.pdf filter=lfs diff=lfs merge=lfs -text
805
+ Repos/HWE/agents/Lingxi/docs/Lingxi[[:space:]]v1.5[[:space:]]Technical[[:space:]]Report[[:space:]]200725.pdf filter=lfs diff=lfs merge=lfs -text
806
+ Repos/HWE/agents/Lingxi/docs/Lingxi[[:space:]]v2.0[[:space:]]Technical[[:space:]]Report[[:space:]]2026.pdf filter=lfs diff=lfs merge=lfs -text
807
+ Repos/HWE/agents/Lingxi/imgs/overview_fig.pdf filter=lfs diff=lfs merge=lfs -text
Repos/HWE/README.md ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # HWE — Phoenix-bench Code Release
2
+
3
+ Code that backs the paper *Phoenix-bench: A Hardware Engineering Benchmark for Agentic AI* (NeurIPS 2026). The companion data (per-instance snapshots, full Verilator testbenches, Docker images) lives at the project page; this tree holds source code, scripts, agent run artifacts, and lightweight metadata (~2.2 GB).
4
+
5
+ All paths and identifiers in this release have been anonymized; absolute paths in scripts and logs point at `/workspace/phoenix-bench/`, which the verifier maps to the snapshot/testbench layout described under "Data NOT included" below.
6
+
7
+ ## Layout
8
+
9
+ ```
10
+ HWE/
11
+ ├── agents/ # the 8 agentic frameworks evaluated in §4.2
12
+ │ ├── Agentless/ # workflow-based (Xia et al. 2024)
13
+ │ ├── Aider/ # interactive (paul-gauthier 2024)
14
+ │ ├── ExpeRepair/ # retrieval-aug. (Mu et al. 2025)
15
+ │ ├── KGCompass/ # knowledge-graph (2025)
16
+ │ ├── Lingxi/ # multi-agent (2025)
17
+ │ ├── mini-swe-agent/ # minimal SWE-agent variant (2025)
18
+ │ ├── OpenHands/ # interactive (Wang et al. 2024)
19
+ │ └── SWE-agent/ # interactive (Yang et al. 2024)
20
+ └── benchmark/
21
+ ├── construction/ # §3.1 funnel: GitHub crawl → issue/PR filtering
22
+ ├── verifier/ # §3 Phoenix-Ref harness + gold patches
23
+ └── eval_harness/ # §4 product+open-source agent evaluation scaffolds
24
+ ```
25
+
26
+ ## Mapping to the paper
27
+
28
+ | Paper element | Code path |
29
+ |---|---|
30
+ | §3.1 Data collection / 4-stage funnel | `benchmark/construction/` |
31
+ | §3 Phoenix-Ref harness (511 instances) | `benchmark/verifier/` |
32
+ | §3 Patch complexity / difficulty tiers (Tab 2, App C) | `benchmark/verifier/classify_patch_complexity.py`, `patch_complexity*` |
33
+ | §3 F2P / P2P verification | `benchmark/verifier/count_fail_to_pass.{py,sh}`, `f2p_sweep_one.sh` |
34
+ | §3 Coverage statistics (Tab 2) | `benchmark/verifier/collect_*coverage*.py` |
35
+ | §3 Issue classification (Fig 3) | `benchmark/verifier/classified_issues_full.json`, `classify_missing_issues.py` |
36
+ | §4.1 Four product agents | `benchmark/eval_harness/benchmark_{claude,codex,codex_new,copilot,gemini}/` |
37
+ | §4.2 Eight open-source agents | `agents/` |
38
+ | §4.2 mini-SWE-agent runs | `benchmark/eval_harness/benchmark_mini_agent/` |
39
+ | §4.3 File-level oracle localization | `benchmark/eval_harness/benchmark_localizations/` |
40
+ | §4.3 Testbench-feedback diagnostic | `benchmark/eval_harness/benchmark_eda/` |
41
+
42
+ ## Data NOT included (download separately)
43
+
44
+ These are required to actually re-run the benchmark; omitted here for size.
45
+
46
+ | Artifact | Original location | Size |
47
+ |---|---|---|
48
+ | Per-instance snapshots (511 × repo HEAD) | `HDL_verified_new/snapshots/` | 21 GB |
49
+ | Per-instance Verilator testbenches | `HDL_verified_new/testbench_verilator/` | 16 GB |
50
+ | OpenHands eval outputs (per-instance logs) | `openhands_eval/benchmarks/eval_outputs/` | 9.5 GB |
51
+
52
+ `benchmark/verifier/patches/` (122 MB, gold developer patches) IS included — needed for F2P verification once snapshots are restored.
53
+
54
+ ## Reproducing F2P verification
55
+
56
+ ```bash
57
+ # After downloading snapshots/ and testbench_verilator/ into benchmark/verifier/
58
+ cd benchmark/verifier
59
+ ls testbench_verilator/ > /tmp/instances.txt
60
+ SWEEP_CSV=/tmp/f2p.csv xargs -P 16 -I {} ./f2p_sweep_one.sh {} < /tmp/instances.txt
61
+ ```
62
+
63
+ The included `f2p_full_sweep_2026-05-27.csv` is a snapshot of the 511-instance sweep run on 2026-05-27 (475 PASS / 32 FAIL / 3 ERROR / 1 misclassified).
Repos/HWE/agents/Agentless/.gitignore ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py,cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # poetry
98
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102
+ #poetry.lock
103
+
104
+ # pdm
105
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
106
+ #pdm.lock
107
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
108
+ # in version control.
109
+ # https://pdm.fming.dev/#use-with-ide
110
+ .pdm.toml
111
+
112
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
113
+ __pypackages__/
114
+
115
+ # Celery stuff
116
+ celerybeat-schedule
117
+ celerybeat.pid
118
+
119
+ # SageMath parsed files
120
+ *.sage.py
121
+
122
+ # Environments
123
+ .env
124
+ .venv
125
+ env/
126
+ venv/
127
+ ENV/
128
+ env.bak/
129
+ venv.bak/
130
+
131
+ # Spyder project settings
132
+ .spyderproject
133
+ .spyproject
134
+
135
+ # Rope project settings
136
+ .ropeproject
137
+
138
+ # mkdocs documentation
139
+ /site
140
+
141
+ # mypy
142
+ .mypy_cache/
143
+ .dmypy.json
144
+ dmypy.json
145
+
146
+ # Pyre type checker
147
+ .pyre/
148
+
149
+ # pytype static type analyzer
150
+ .pytype/
151
+
152
+ # Cython debug symbols
153
+ cython_debug/
154
+
155
+ # PyCharm
156
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
157
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
158
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
159
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
160
+ # nuclear option because steven uses PyCharm.
161
+ .idea/
162
+
163
+ # some project specific stuff
164
+
165
+ /get_repo_structure/astropy
166
+ /get_repo_structure/django
167
+ /get_repo_structure/flask
168
+ /get_repo_structure/pylint
169
+ /get_repo_structure/pytest
170
+ /get_repo_structure/requests
171
+ /get_repo_structure/seaborn
172
+ /get_repo_structure/scikit-learn
173
+ /get_repo_structure/sphinx
174
+ /get_repo_structure/matplotlib
175
+ /get_repo_structure/sympy
176
+ /get_repo_structure/xarray
177
+ get_repo_structure/test_repo/
178
+ results/
179
+ logs/
180
+ dev/
181
+
182
+ # data files
183
+ *.jsonl
184
+ *.json
185
+
186
+ # Jupyter Notebooks
187
+ *.ipynb
Repos/HWE/agents/Agentless/.pre-commit-config.yaml ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ repos:
2
+ - repo: https://github.com/pycqa/isort
3
+ rev: 5.12.0
4
+ hooks:
5
+ - id: isort
6
+ name: isort (python)
7
+ args: ["--profile", "black"]
8
+ - repo: https://github.com/psf/black
9
+ rev: 22.6.0
10
+ hooks:
11
+ - id: black
12
+ - repo: https://github.com/pre-commit/pre-commit-hooks
13
+ rev: v4.3.0
14
+ hooks:
15
+ - id: check-yaml
16
+ - id: end-of-file-fixer
17
+ - id: trailing-whitespace
18
+ exclude: |
19
+ (?x)^(
20
+ README.*
21
+ )$
Repos/HWE/agents/Agentless/LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2024 OpenAutoCoder
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
Repos/HWE/agents/Agentless/README.md ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 😺 Agentless
2
+
3
+ <p align="center">
4
+ <a href="https://arxiv.org/abs/2407.01489"><img src="https://img.shields.io/badge/📃-Arxiv-b31b1b?style=for-the-badge"></a>
5
+ <a href="https://github.com/OpenAutoCoder/Agentless/blob/master/LICENSE"><img src="https://forthebadge.com/images/badges/license-mit.svg" style="height: 28px"></a>
6
+ </p>
7
+
8
+ <p align="center">
9
+ <big><a href="#-news">😽News</a></big> |
10
+ <big><a href="#-setup">🐈Setup</a></big> |
11
+ <big><a href="#-comparison">🧶Comparison</a></big> |
12
+ <big><a href="#-artifacts">🐈‍⬛Artifacts</a></big> |
13
+ <big><a href="#-citation">📝Citation</a></big> |
14
+ <big><a href="#-acknowledgement">😻Acknowledgement</a></big>
15
+ </p>
16
+
17
+ ## 😽 News
18
+
19
+ - *Dec 2nd, 2024*: We integrated Agentless with Claude 3.5 Sonnet to achieve 40.7% and 50.8% solve rate on SWE-bench lite and verified
20
+ - *Oct 28th, 2024*: We just released OpenAutoCoder-Agentless 1.5!
21
+ - *July 1st, 2024*: We just released OpenAutoCoder-Agentless 1.0! **Agentless** currently is the best open-source approach on SWE-bench lite with 82 fixes (27.3%) and costing on average $0.34 per issue.
22
+
23
+ ## 😺 About
24
+
25
+ **Agentless** is an *agentless* approach to automatically solve software development problems. To solve each issue, **Agentless** follows a simple three phase process: localization, repair, and patch validation.
26
+ - 🙀 **Localization**: Agentless employs a hierarchical process to first localize the fault to specific files, then to relevant classes or functions, and finally to fine-grained edit locations
27
+ - 😼 **Repair**: Agentless takes the edit locations and samples multiple candidate patches per bug in a simple diff format
28
+ - 😸 **Patch Validation**: Agentless selects the regression tests to run and generates additional reproduction test to reproduce the original error. Using the test results, Agentless re-ranks all remaining patches to selects one to submit
29
+
30
+ ## 🐈 Setup
31
+
32
+ First create the environment
33
+
34
+ ```shell
35
+ git clone https://github.com/OpenAutoCoder/Agentless.git
36
+ cd Agentless
37
+
38
+ conda create -n agentless python=3.11
39
+ conda activate agentless
40
+ pip install -r requirements.txt
41
+ export PYTHONPATH=$PYTHONPATH:$(pwd)
42
+ ```
43
+
44
+ <details><summary>⏬ Developer Setup</summary>
45
+ <div>
46
+
47
+ ```shell
48
+ # for contribution, please install the pre-commit hook.
49
+ pre-commit install # this allows a more standardized code style
50
+ ```
51
+
52
+ </div>
53
+ </details>
54
+
55
+ Then export your OpenAI API key
56
+ ```shell
57
+ export OPENAI_API_KEY={key_here}
58
+ ```
59
+
60
+ Now you are ready to run **Agentless** on the problems in SWE-bench!
61
+
62
+ > [!NOTE]
63
+ >
64
+ > To reproduce the full SWE-bench lite experiments and follow our exact setup as described in the paper. Please see this [README](https://github.com/OpenAutoCoder/Agentless/blob/main/README_swebench.md)
65
+
66
+ ## 🧶 Comparison
67
+
68
+ Below shows the comparison graph between **Agentless** and the best open-source agent-based approaches on SWE-bench lite
69
+
70
+ <p align="center">
71
+ <img src="./resources/comparison_graph.png" style="width:75%; margin-left: auto; margin-right: auto;">
72
+ </p>
73
+
74
+ ## 🐈‍⬛ Artifacts
75
+
76
+ You can download the complete artifacts of **Agentless** in our [v1.5.0 release](https://github.com/OpenAutoCoder/Agentless/releases/tag/v1.5.0):
77
+ - 🐈‍⬛ agentless_swebench_lite: complete Agentless run on SWE-bench Lite
78
+ - 🐈‍⬛ agentless_swebench_verified: complete Agentless run on SWE-bench Verified
79
+ - 🐈‍⬛ swebench_repo_structure: preprocessed structure information for each SWE-Bench problem
80
+
81
+ You can also checkout `classification/` folder to obtain our manual classifications of SWE-bench-lite as well as our filtered SWE-bench-lite-*S* problems.
82
+
83
+ ## 📝 Citation
84
+
85
+ ```bibtex
86
+ @article{agentless,
87
+ author = {Xia, Chunqiu Steven and Deng, Yinlin and Dunn, Soren and Zhang, Lingming},
88
+ title = {Agentless: Demystifying LLM-based Software Engineering Agents},
89
+ year = {2024},
90
+ journal = {arXiv preprint},
91
+ }
92
+ ```
93
+
94
+ > [!NOTE]
95
+ >
96
+ > The first two authors contributed equally to this work, with author order determined via [*Nigiri*](https://senseis.xmp.net/?Nigiri)
97
+
98
+ ## 😻 Acknowledgement
99
+
100
+ * [SWE-bench](https://www.swebench.com/)
101
+ * [Aider](https://github.com/paul-gauthier/aider)
102
+ * [SWE-bench-docker](https://github.com/aorwall/SWE-bench-docker)
Repos/HWE/agents/Agentless/README_swebench.md ADDED
@@ -0,0 +1,374 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Agentless experiments on SWE-Bench
2
+
3
+ <p align="center">
4
+ <big><a href="#-setup">🐈Setup</a></big> |
5
+ <big><a href="#-localization">🙀Localization</a></big> |
6
+ <big><a href="#-repair">😼Repair</a></big> |
7
+ <big><a href="#-patch-validation-and-selection">😸Patch Validation and Selection</a></big> |
8
+ <big><a href="#-cost">💰Cost</a></big>
9
+ </p>
10
+
11
+ In this document, we will go through the steps to generate the patches on SWE-bench.
12
+ Currently, we support both [SWE-Bench Lite](https://huggingface.co/datasets/princeton-nlp/SWE-bench_Lite) and [SWE-Bench Verified](https://huggingface.co/datasets/princeton-nlp/SWE-bench_Verified)
13
+
14
+ ## 🐈 Setup
15
+
16
+ First create the environment
17
+
18
+ ```shell
19
+ git clone https://github.com/OpenAutoCoder/Agentless.git
20
+ cd Agentless
21
+
22
+ conda create -n agentless python=3.11
23
+ conda activate agentless
24
+ pip install -r requirements.txt
25
+ export PYTHONPATH=$PYTHONPATH:$(pwd)
26
+ ```
27
+
28
+ Then export your OpenAI API key
29
+ ```shell
30
+ export OPENAI_API_KEY={key_here}
31
+ ```
32
+
33
+ Create the folder to save our results
34
+ ```shell
35
+ mkdir results # where we will save our results
36
+ ```
37
+
38
+ > [!TIP]
39
+ >
40
+ > We currently support SWE-Bench Lite and SWE-Bench Verified benchmarks, you can use `--dataset` to select the benchmark (by default it will be SWE-Bench Lite)
41
+ >
42
+ > For example `--dataset=princeton-nlp/SWE-bench_Verified`
43
+
44
+ > [!TIP]
45
+ >
46
+ > Since for each issue in the benchmark (both SWE-Bench Lite and SWE-Bench Verified) we need to checkout the repository and process the files, you might want to save some time by downloading the preprocessed data here: [swebench_lite_repo_structure.zip](https://github.com/OpenAutoCoder/Agentless/releases/tag/v1.5.0)
47
+ >
48
+ > After downloading, please unzip and export the location as such `export PROJECT_FILE_LOC={folder which you saved}`
49
+
50
+ > [!TIP]
51
+ >
52
+ > You can use `--target_id` to specific a particular bug you want to target.
53
+ >
54
+ > For example `--target_id=django__django-10914`
55
+
56
+ > [!TIP]
57
+ >
58
+ > We use multiple threads (controllable via `--num_threads`) to speed up the Agentless process
59
+
60
+ ## 🙀 Localization
61
+
62
+ In localization, the goal is to find the locations in source code where we need to edit to fix the issues.
63
+ At a high-level, **Agentless** uses a 3-stage localization step to first localize to specific files, then to relevant code elements, and finally to fine-grained edit locations.
64
+ We will now take you through the step-by-step procedure of Agentless in each of the localization steps.
65
+
66
+ #### 1. Localize to suspicious files
67
+
68
+ First, we localize to suspicious files. This is done in a multi-step process where we combine both LLM localized files with retrieval files.
69
+
70
+ Run the following command to generate the LLM-predicted suspicious files:
71
+
72
+ ```shell
73
+ python agentless/fl/localize.py --file_level \
74
+ --output_folder results/swe-bench-lite/file_level \
75
+ --num_threads 10 \
76
+ --skip_existing
77
+ ```
78
+
79
+ This will save all the LLM-predicted suspicious file locations in `results/swe-bench-lite/file_level/loc_outputs.jsonl` with the logs saved in `results/swe-bench-lite/file_level/localization_logs`
80
+
81
+ We then complement the previous suspicious files with a simple embedding-based retrieval method to identify additional suspicious files.
82
+
83
+ This is done by first filtering out irrelevant folders by using LLM to produce a list of irrelevant folders that do not need to be retrieved from with the following command:
84
+
85
+ ```shell
86
+ python agentless/fl/localize.py --file_level \
87
+ --irrelevant \
88
+ --output_folder results/swe-bench-lite/file_level_irrelevant \
89
+ --num_threads 10 \
90
+ --skip_existing
91
+ ```
92
+
93
+ This will save the identified irrelevant folders in `results/swe-bench-lite/file_level_irrelevant/loc_outputs.jsonl` with the logs saved in `results/swe-bench-lite/file_level_irrelevant/localization_logs`
94
+
95
+ We then perform the retrieval (note the embedding is done with OpenAI `text-embedding-3-small` model) by passing in the irrelevant folders and running the following command:
96
+
97
+ ```shell
98
+ python agentless/fl/retrieve.py --index_type simple \
99
+ --filter_type given_files \
100
+ --filter_file results/swe-bench-lite/file_level_irrelevant/loc_outputs.jsonl \
101
+ --output_folder results/swe-bench-lite/retrievel_embedding \
102
+ --persist_dir embedding/swe-bench_simple \
103
+ --num_threads 10
104
+ ```
105
+
106
+ This will save the retrieved files in `results/swe-bench-lite/retrievel_embedding/retrieve_locs.jsonl` with the logs saved in `results/swe-bench-lite/retrievel_embedding/retrieval_logs`
107
+
108
+ Finally we merge the LLM-predicted suspicious file locations with the embedding-based retrieved files to obtain a final list of relevant files:
109
+
110
+ ```shell
111
+ python agentless/fl/combine.py --retrieval_loc_file results/swe-bench-lite/retrievel_embedding/retrieve_locs.jsonl \
112
+ --model_loc_file results/swe-bench-lite/file_level/loc_outputs.jsonl \
113
+ --top_n 3 \
114
+ --output_folder results/swe-bench-lite/file_level_combined
115
+ ```
116
+
117
+ `results/swe-bench-lite/file_level_combined/combined_locs.jsonl` contains the final list of suspicious files identified by Agentless.
118
+
119
+ #### 2. localize to related elements
120
+
121
+ Next, we move on to localizing the related elements.
122
+
123
+ Run the following command to provide the suspicious files from the first stage as input:
124
+
125
+ ```shell
126
+ python agentless/fl/localize.py --related_level \
127
+ --output_folder results/swe-bench-lite/related_elements \
128
+ --top_n 3 \
129
+ --compress_assign \
130
+ --compress \
131
+ --start_file results/swe-bench-lite/file_level_combined/combined_locs.jsonl \
132
+ --num_threads 10 \
133
+ --skip_existing
134
+ ```
135
+
136
+ This will save the related elements in `results/swe-bench-lite/related_elements/loc_outputs.jsonl` with the logs saved in `results/swe-bench-lite/related_elements/localization_logs`
137
+
138
+ #### 3. localize to edit locations
139
+
140
+ Finally, using the related elements, we then localize to the edit locations. This is done via sampling to obtain multiple different sets of edit locations:
141
+
142
+
143
+ ```shell
144
+ python agentless/fl/localize.py --fine_grain_line_level \
145
+ --output_folder results/swe-bench-lite/edit_location_samples \
146
+ --top_n 3 \
147
+ --compress \
148
+ --temperature 0.8 \
149
+ --num_samples 4 \
150
+ --start_file results/swe-bench-lite/related_elements/loc_outputs.jsonl \
151
+ --num_threads 10 \
152
+ --skip_existing
153
+ ```
154
+
155
+ This will save the edit locations in `results/swe-bench-lite/edit_location_samples/loc_outputs.jsonl` with the logs saved in `results/swe-bench-lite/edit_location_samples/localization_logs`
156
+
157
+ <details><summary>⏬ Structure of `loc_outputs.jsonl` <i>:: click to expand ::</i> </summary>
158
+ <div>
159
+
160
+ - `instance_id`: task ID of the issue
161
+ - `found_files`: list of files localized by the model
162
+ - `additional_artifact_loc_file`: raw output of the model during file-level localization
163
+ - `file_traj`: trajectory of the model during file-level localization (e.g., \# of tokens)
164
+ - `found_related_locs`: dict of relevant code elements localized by the model
165
+ - `additional_artifact_loc_related`: raw output of the model during relevant-code-level localization
166
+ - `related_loc_traj`: trajectory of the model during relevant-code-level localization
167
+ - `found_edit_locs`: dict of edit locations localized by the model
168
+ - `additional_artifact_loc_edit_location`: raw output of the model during edit-location-level localization
169
+ - `edit_loc_traj`: trajectory of the model during edit-location-level localization
170
+
171
+ </div>
172
+ </details>
173
+
174
+ Run the following command to separate the individual sets of edit locations:
175
+
176
+ ```shell
177
+ python agentless/fl/localize.py --merge \
178
+ --output_folder results/swe-bench-lite/edit_location_individual \
179
+ --top_n 3 \
180
+ --num_samples 4 \
181
+ --start_file results/swe-bench-lite/edit_location_samples/loc_outputs.jsonl
182
+ ```
183
+
184
+ The separate sets of edit locations can be found in `results/swe-bench-lite/edit_location_individual`. The location files will be named `loc_merged_{x}-{x}_outputs.jsonl` where `x` indicates the individual samples. For our experiments on SWE-bench, we will use all 4 sets of edit locations and perform repairs on them individually to generate 4 different repair runs.
185
+
186
+ ## 😼 Repair
187
+
188
+ Using the 4 sets of edit locations from before, we now perform repair.
189
+
190
+ **Agentless** generates multiple patches per issue (controllable via parameters) and then perform majority voting with patch validation to select the final patch for submission
191
+
192
+ Run the following command to generate the patches:
193
+
194
+ ```shell
195
+ python agentless/repair/repair.py --loc_file results/swe-bench-lite/edit_location_individual/loc_merged_0-0_outputs.jsonl \
196
+ --output_folder results/swe-bench-lite/repair_sample_1 \
197
+ --loc_interval \
198
+ --top_n=3 \
199
+ --context_window=10 \
200
+ --max_samples 10 \
201
+ --cot \
202
+ --diff_format \
203
+ --gen_and_process \
204
+ --num_threads 2
205
+ ```
206
+
207
+ <details><summary>Additional Repair Commands</summary>
208
+ <div>
209
+
210
+ ```shell
211
+ for i in {1..3}; do
212
+ python agentless/repair/repair.py --loc_file results/swe-bench-lite/edit_location_individual/loc_merged_${i}-${i}_outputs.jsonl \
213
+ --output_folder results/swe-bench-lite/repair_sample_$((i+1)) \
214
+ --loc_interval \
215
+ --top_n=3 \
216
+ --context_window=10 \
217
+ --max_samples 10 \
218
+ --cot \
219
+ --diff_format \
220
+ --gen_and_process \
221
+ --num_threads 2
222
+ done
223
+
224
+ ```
225
+ </div>
226
+ </details>
227
+
228
+ These commands generate 10 samples each (1 greedy and 9 via temperature sampling) as defined `--max_samples 10`. The `--context_window` indicates the amount of code lines before and after each localized edit location we provide to the model for repair. The patches are saved in `results/swe-bench-lite/repair_sample_{i}/output.jsonl`, which contains the raw output of each sample as well as any trajectory information (e.g., number of tokens). The complete logs are also saved in `results/swe-bench-lite/repair_sample_{i}/repair_logs/`
229
+
230
+ The above commands will combine to generate 40 samples in total for each bug.
231
+
232
+ ## 😸 Patch Validation and Selection
233
+
234
+ Since Agentless generates multiple candidate patches per issue, we need a way to select a final patch for submission.
235
+
236
+ To do this, Agentless leverages both regression tests that exist in the codebase as well as generating new reproduction tests that can verify if the patch can solve the original issue.
237
+
238
+ #### Regression test selection
239
+
240
+ We first select a set of regression tests (tests that already exist in the repository and pass on the original codebase) to run.
241
+
242
+ Run the following command to get a list of passing tests in the original codebase:
243
+
244
+ ```shell
245
+ python agentless/test/run_regression_tests.py --run_id generate_regression_tests \
246
+ --output_file results/swe-bench-lite/passing_tests.jsonl
247
+ ```
248
+
249
+ This will generate a list of passing tests at `results/swe-bench-lite/passing_tests.jsonl`
250
+
251
+ > [!NOTE]
252
+ >
253
+ > We do not use any of provided PASS_TO_PASS field in the SWE-bench benchmark
254
+ >
255
+ > We select tests from the complete list of tests which can pass in the original repository
256
+
257
+ Next, we ask the LLM to remove any tests which should not be ran with the following command:
258
+
259
+ ```shell
260
+ python agentless/test/select_regression_tests.py --passing_tests results/swe-bench-lite/passing_tests.jsonl \
261
+ --output_folder results/swe-bench-lite/select_regression
262
+ ```
263
+
264
+ This will produce a list of final regression tests in `results/swe-bench-lite/select_regression/output.jsonl` with the logs at `results/swe-bench-lite/select_regression/select_test_logs`
265
+
266
+ We can run this on all the patches generate, repeated for each repair run (i.e., by changing `folder`):
267
+
268
+ ```shell
269
+ folder=results/swe-bench-lite/repair_sample_1
270
+ for num in {0..9..1}; do
271
+ run_id_prefix=$(basename $folder);
272
+ python agentless/test/run_regression_tests.py --regression_tests results/swe-bench-lite/select_regression/output.jsonl \
273
+ --predictions_path="${folder}/output_${num}_processed.jsonl" \
274
+ --run_id="${run_id_prefix}_regression_${num}" --num_workers 10;
275
+ done
276
+ ```
277
+
278
+ This will output the regression test results in the same folder as the repair results. `results/swe-bench-lite/repair_sample_1/output_{i}_regression_test_results.jsonl` contains the regression test results for each patch number (`i`).
279
+
280
+ > [!NOTE]
281
+ >
282
+ > We also perform post-processing to generate the complete git-diff patch for each repair sample.
283
+ >
284
+ > You can find the individual patch in `results/repair/output_{i}_processed.jsonl` where `i` is the sample number.
285
+
286
+ #### Reproduction test generation
287
+
288
+ In addition to the regression tests, Agentless also generates a reproduction test that attempt to check if the patch can solve the original issue.
289
+
290
+ Similar to patch generation, Agentless also generates multiple samples of reproduction tests, and then perform selection:
291
+ ```shell
292
+ python agentless/test/generate_reproduction_tests.py --max_samples 40 \
293
+ --output_folder results/swe-bench-lite/reproduction_test_samples \
294
+ --num_threads 10
295
+ ```
296
+
297
+ This will generate 40 samples (1 greedy + 39 temperature sampling) per issue. The generated reproduction tests can be found in `results/swe-bench-lite/reproduction_test_samples/output.jsonl`. The corresponding logs can be found in `results/swe-bench-lite/reproduction_test_samples/generating_test_logs/`.
298
+
299
+ Now we will execute each of these generated tests on the original repository to see if they can reproduce the original issue.
300
+
301
+ ```shell
302
+ for st in {0..36..4}; do en=$((st + 3));
303
+ echo "Processing ${st} to ${en}";
304
+ for num in $(seq $st $en); do
305
+ echo "Processing ${num}";
306
+ python agentless/test/run_reproduction_tests.py --run_id="reproduction_test_generation_filter_sample_${num}" \
307
+ --test_jsonl="results/swe-bench-lite/reproduction_test_samples/output_${num}_processed_reproduction_test.jsonl" \
308
+ --num_workers 6 \
309
+ --testing;
310
+ done & done
311
+ ```
312
+
313
+ > [!WARNING]
314
+ >
315
+ > In the above command we execute multiple SWE-bench evaluations in parallel, please ensure that your machine is able to handle that
316
+ >
317
+ > If not, you may want to reduce the amount of parallelization
318
+
319
+ This produces verification results for each tests in the same folder: `results/swe-bench-lite/reproduction_test_samples/`
320
+
321
+ We then perform majority voting to select one reproduction test per issue:
322
+
323
+ ```shell
324
+ python agentless/test/generate_reproduction_tests.py --max_samples 40 \
325
+ --output_folder results/swe-bench-lite/reproduction_test_samples \
326
+ --output_file reproduction_tests.jsonl \
327
+ --select
328
+ ```
329
+
330
+ This will generate the reproduction test file at: `results/swe-bench-lite/reproduction_test_samples/reproduction_tests.jsonl`
331
+
332
+ Finally, we evaluate the generated patches on the selected reproduction test. Similar to regression test execution, this is repeated for each repair run (i.e., by changing `folder`):
333
+
334
+ ```shell
335
+ folder=results/swe-bench-lite/repair_sample_1
336
+ for num in {0..9..1}; do
337
+ run_id_prefix=$(basename $folder);
338
+ python agentless/test/run_reproduction_tests.py --test_jsonl results/swe-bench-lite/reproduction_test_samples/reproduction_tests.jsonl \
339
+ --predictions_path="${folder}/output_${num}_processed.jsonl" \
340
+ --run_id="${run_id_prefix}_reproduction_${num}" --num_workers 10;
341
+ done
342
+ ```
343
+
344
+ This will output the reproduction test results in the same folder as the repair results. `results/swe-bench-lite/repair_sample_1/output_{i}_reproduction_test_results.jsonl` contains the reproduction test results for each patch number (`i`).
345
+
346
+
347
+ #### Reranking and patch selection
348
+
349
+ Finally, using the regression and reproduction test results, Agentless performs reranking to select the final patch for submission.
350
+
351
+ Run the following command (`--regression` indicates we are using regression tests for selection `--reproduction` indicates we are using the reproduction tests for selection)
352
+
353
+ ```shell
354
+ python agentless/repair/rerank.py --patch_folder results/swe-bench-lite/repair_sample_1/,results/swe-bench-lite/repair_sample_2/,results/swe-bench-lite/repair_sample_3/,results/swe-bench-lite/repair_sample_4/ \
355
+ --num_samples 40 \
356
+ --deduplicate \
357
+ --regression \
358
+ --reproduction
359
+ ```
360
+
361
+ This command will produced the `all_preds.jsonl` that contains the final selected patch for each instance_id which you can then directly use your favorite way of testing SWE-bench for evaluation!
362
+
363
+
364
+ ## 💰 Cost
365
+
366
+ To measure the cost of running Agentless, we have provided helpful utilities.
367
+
368
+ For each of the `output.jsonl` files produced for each of the steps (including substeps), run the following command:
369
+
370
+ ```shell
371
+ python dev/util/cost.py --output_file example_step/output.jsonl
372
+ ```
373
+
374
+ This will output the dollar cost as well as the number of tokens. `--embedding_cost` can be used to compute the cost of the embedding step.
Repos/HWE/agents/Agentless/agentless/fl/FL.py ADDED
@@ -0,0 +1,775 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from abc import ABC, abstractmethod
2
+
3
+ from agentless.repair.repair import construct_topn_file_context
4
+ from agentless.util.compress_file import get_skeleton
5
+ from agentless.util.postprocess_data import extract_code_blocks, extract_locs_for_files
6
+ from agentless.util.preprocess_data import (
7
+ correct_file_paths,
8
+ get_full_file_paths_and_classes_and_functions,
9
+ get_repo_files,
10
+ line_wrap_content,
11
+ show_project_structure,
12
+ )
13
+
14
+ MAX_CONTEXT_LENGTH = 128000
15
+
16
+
17
+ class FL(ABC):
18
+ def __init__(self, instance_id, structure, problem_statement, **kwargs):
19
+ self.structure = structure
20
+ self.instance_id = instance_id
21
+ self.problem_statement = problem_statement
22
+
23
+ @abstractmethod
24
+ def localize(self, top_n=1, mock=False) -> tuple[list, list, list, any]:
25
+ pass
26
+
27
+
28
+ class LLMFL(FL):
29
+ obtain_relevant_files_prompt = """
30
+ Please look through the following GitHub problem description and Repository structure and provide a list of files that one would need to edit to fix the problem in a Verilog/SystemVerilog hardware design repository.
31
+
32
+ ### GitHub Problem Description ###
33
+ {problem_statement}
34
+
35
+ ###
36
+
37
+ ### Repository Structure ###
38
+ {structure}
39
+
40
+ ###
41
+
42
+ Please only provide the full path and return at most 5 files.
43
+ The returned files should be separated by new lines ordered by most to least important and wrapped with ```
44
+ For example:
45
+ rtl/top.sv
46
+ rtl/core/alu.sv
47
+ tb/top_tb.sv
48
+
49
+ """
50
+
51
+ obtain_irrelevant_files_prompt = """
52
+ Please look through the following GitHub problem description and Repository structure and provide a list of folders that are irrelevant to fixing the problem.
53
+ Note that irrelevant folders are those that do not need to be modified and are safe to ignore when trying to solve this problem.
54
+
55
+ ### GitHub Problem Description ###
56
+ {problem_statement}
57
+
58
+ ###
59
+
60
+ ### Repository Structure ###
61
+ {structure}
62
+
63
+ ###
64
+
65
+ Please only provide the full path.
66
+ Remember that any subfolders will be considered as irrelevant if you provide the parent folder.
67
+ Please ensure that the provided irrelevant folders do not include any important files needed to fix the problem (e.g., RTL, testbenches, constraints, build scripts, or verification collateral).
68
+ The returned folders should be separated by new lines and wrapped with ```
69
+ For example:
70
+ docs/
71
+ scripts/legacy/
72
+ third_party/
73
+
74
+ """
75
+
76
+ file_content_template = """
77
+ ### File: {file_name} ###
78
+ {file_content}
79
+ """
80
+
81
+ file_content_in_block_template = """
82
+ ### File: {file_name} ###
83
+ ```systemverilog
84
+ {file_content}
85
+ """
86
+
87
+ obtain_relevant_code_combine_top_n_prompt = """
88
+ Please review the following GitHub problem description and relevant files, and provide a set of locations that need to be edited to fix the issue in a Verilog/SystemVerilog codebase.
89
+ Locations may be specified as module names, interface names, package names, task/function names, parameter/localparam names, signal names, or exact line numbers requiring modification.
90
+
91
+ GitHub Problem Description
92
+ {problem_statement}
93
+
94
+ {file_contents}
95
+
96
+ Please provide the module/interface/package name, task/function name, parameter name, or the exact line numbers that need to be edited.
97
+ The possible location outputs should be either "module", "interface", "package", "function", "task", "parameter", "signal", or "line".
98
+
99
+ Examples:
100
+ rtl/top.sv
101
+ line: 42
102
+ module: top
103
+ line: 120
104
+
105
+ rtl/core/alu.sv
106
+ module: alu
107
+ function: compute_flags
108
+ line: 88
109
+
110
+ rtl/common/types_pkg.sv
111
+ package: types_pkg
112
+ parameter: XLEN
113
+ Return just the location(s) wrapped with ```.
114
+ """
115
+
116
+ obtain_relevant_code_combine_top_n_no_line_number_prompt = """
117
+ Please review the following GitHub problem description and relevant files, and provide a set of locations that need to be edited to fix the issue in a Verilog/SystemVerilog codebase.
118
+ Locations may be specified as module/interface/package names, task names, function names, parameters, or signals that require modification.
119
+
120
+ GitHub Problem Description
121
+ {problem_statement}
122
+
123
+ {file_contents}
124
+
125
+ Please provide the module/interface/package, task, function, parameter, or signal names that need to be edited.
126
+
127
+ Examples:
128
+ rtl/top.sv
129
+ module: top
130
+ signal: reset_n
131
+
132
+ rtl/core/alu.sv
133
+ module: alu
134
+ function: compute_flags
135
+ task: do_execute
136
+
137
+ rtl/common/types_pkg.sv
138
+ package: types_pkg
139
+ parameter: XLEN
140
+ Return just the location(s) wrapped with ```.
141
+ """
142
+
143
+ obtain_relevant_functions_and_vars_from_compressed_files_prompt_more = """
144
+ Please look through the following GitHub Problem Description and the Skeleton of Relevant Files.
145
+ Identify all locations that need inspection or editing to fix the problem in a Verilog/SystemVerilog repository, including directly related areas as well as any potentially related parameters, signals, modules, interfaces, packages, tasks, functions, and assertions.
146
+ For each location you provide, give the name of a module, interface, package, task, function, parameter/localparam, signal, or a named assertion/property/sequence.
147
+
148
+ GitHub Problem Description
149
+ {problem_statement}
150
+
151
+ Skeleton of Relevant Files
152
+ {file_contents}
153
+
154
+ Please provide the complete set of locations as either a module name, interface name, package name, task name, function name, parameter name, signal name, or assertion/property name.
155
+ Note that if you include a module/interface/package, you do not need to list its internal blocks unless you want to point to a specific task/function or named generate block.
156
+
157
+ Examples:
158
+ rtl/top.sv
159
+ module: top
160
+ signal: reset_n
161
+ parameter: BOOT_ADDR
162
+
163
+ rtl/core/pipe.sv
164
+ module: pipeline
165
+ function: compute_next_pc
166
+ task: flush_pipe
167
+ signal: stall
168
+
169
+ rtl/common/types_pkg.sv
170
+ package: types_pkg
171
+ parameter: XLEN
172
+ Return just the locations wrapped with ```.
173
+ """
174
+
175
+ obtain_relevant_functions_and_vars_from_raw_files_prompt = """
176
+ Please look through the following GitHub Problem Description and Relevant Files.
177
+ Identify all locations that need inspection or editing to fix the problem in a Verilog/SystemVerilog repository, including directly related areas as well as any potentially related parameters, signals, modules, interfaces, packages, tasks, functions, and assertions.
178
+ For each location you provide, give the name of a module, interface, package, task, function, parameter/localparam, signal, or a named assertion/property/sequence.
179
+
180
+ GitHub Problem Description
181
+ {problem_statement}
182
+
183
+ Relevant Files
184
+ {file_contents}
185
+
186
+ Please provide the complete set of locations as either a module name, interface name, package name, task name, function name, parameter name, signal name, or assertion/property name.
187
+ Note that if you include a module/interface/package, you do not need to list its internal blocks unless you want to point to a specific task/function or named generate block.
188
+
189
+ Examples:
190
+ rtl/top.sv
191
+ module: top
192
+ signal: reset_n
193
+ parameter: BOOT_ADDR
194
+
195
+ rtl/core/pipe.sv
196
+ module: pipeline
197
+ function: compute_next_pc
198
+ task: flush_pipe
199
+ signal: stall
200
+
201
+ rtl/common/types_pkg.sv
202
+ package: types_pkg
203
+ parameter: XLEN
204
+ Return just the locations wrapped with ```.
205
+ """
206
+
207
+ def __init__(
208
+ self,
209
+ instance_id,
210
+ structure,
211
+ problem_statement,
212
+ model_name,
213
+ backend,
214
+ logger,
215
+ **kwargs,
216
+ ):
217
+ super().__init__(instance_id, structure, problem_statement)
218
+ self.max_tokens = 300
219
+ self.model_name = model_name
220
+ self.backend = backend
221
+ self.logger = logger
222
+
223
+ def _parse_model_return_lines(self, content: str) -> list[str]:
224
+ if not content:
225
+ self.logger.error("Model returned empty response; cannot parse paths.")
226
+ return []
227
+ return content.strip().split("\n")
228
+
229
+ def localize_irrelevant(self, top_n=1, mock=False):
230
+ from agentless.util.api_requests import num_tokens_from_messages
231
+ from agentless.util.model import make_model
232
+
233
+ message = self.obtain_irrelevant_files_prompt.format(
234
+ problem_statement=self.problem_statement,
235
+ structure=show_project_structure(self.structure).strip(),
236
+ ).strip()
237
+ self.logger.info(f"prompting with message:\n{message}")
238
+ self.logger.info("=" * 80)
239
+
240
+ if mock:
241
+ self.logger.info("Skipping querying model since mock=True")
242
+ traj = {
243
+ "prompt": message,
244
+ "usage": {
245
+ "prompt_tokens": num_tokens_from_messages(message, self.model),
246
+ },
247
+ }
248
+ return [], {"raw_output_loc": ""}, traj
249
+
250
+ model = make_model(
251
+ model=self.model_name,
252
+ backend=self.backend,
253
+ logger=self.logger,
254
+ max_tokens=2048, # self.max_tokens,
255
+ temperature=0,
256
+ batch_size=1,
257
+ )
258
+ traj = model.codegen(message, num_samples=1)[0]
259
+ traj["prompt"] = message
260
+ raw_output = traj["response"]
261
+
262
+ files, classes, functions = get_full_file_paths_and_classes_and_functions(
263
+ self.structure
264
+ )
265
+
266
+ f_files = []
267
+ filtered_files = []
268
+
269
+ model_identified_files_folder = self._parse_model_return_lines(raw_output)
270
+ # remove any none folder none files
271
+ model_identified_files_folder = [
272
+ x
273
+ for x in model_identified_files_folder
274
+ if x.endswith("/") or x.endswith(".py")
275
+ ]
276
+
277
+ for file_content in files:
278
+ file_name = file_content[0]
279
+ if any([file_name.startswith(x) for x in model_identified_files_folder]):
280
+ filtered_files.append(file_name)
281
+ else:
282
+ f_files.append(file_name)
283
+
284
+ self.logger.info(raw_output)
285
+
286
+ return (
287
+ f_files,
288
+ {
289
+ "raw_output_files": raw_output,
290
+ "found_files": f_files,
291
+ "filtered_files": filtered_files,
292
+ },
293
+ traj,
294
+ )
295
+
296
+ def localize(self, top_n=1, mock=False) -> tuple[list, list, list, any]:
297
+ from agentless.util.api_requests import num_tokens_from_messages
298
+ from agentless.util.model import make_model
299
+
300
+ found_files = []
301
+
302
+ message = self.obtain_relevant_files_prompt.format(
303
+ problem_statement=self.problem_statement,
304
+ structure=show_project_structure(self.structure).strip(),
305
+ ).strip()
306
+ self.logger.info(f"prompting with message:\n{message}")
307
+ self.logger.info("=" * 80)
308
+ if mock:
309
+ self.logger.info("Skipping querying model since mock=True")
310
+ traj = {
311
+ "prompt": message,
312
+ "usage": {
313
+ "prompt_tokens": num_tokens_from_messages(message, self.model_name),
314
+ },
315
+ }
316
+ return [], {"raw_output_loc": ""}, traj
317
+
318
+ model = make_model(
319
+ model=self.model_name,
320
+ backend=self.backend,
321
+ logger=self.logger,
322
+ max_tokens=self.max_tokens,
323
+ temperature=0,
324
+ batch_size=1,
325
+ )
326
+ traj = model.codegen(message, num_samples=1)[0]
327
+ traj["prompt"] = message
328
+ raw_output = traj["response"]
329
+ model_found_files = self._parse_model_return_lines(raw_output)
330
+
331
+ files, classes, functions = get_full_file_paths_and_classes_and_functions(
332
+ self.structure
333
+ )
334
+
335
+ # sort based on order of appearance in model_found_files
336
+ found_files = correct_file_paths(model_found_files, files)
337
+
338
+ self.logger.info(raw_output)
339
+
340
+ return (
341
+ found_files,
342
+ {"raw_output_files": raw_output},
343
+ traj,
344
+ )
345
+
346
+ def localize_function_from_compressed_files(
347
+ self,
348
+ file_names,
349
+ mock=False,
350
+ temperature=0.0,
351
+ keep_old_order=False,
352
+ compress_assign: bool = False,
353
+ total_lines=30,
354
+ prefix_lines=10,
355
+ suffix_lines=10,
356
+ ):
357
+ from agentless.util.api_requests import num_tokens_from_messages
358
+ from agentless.util.model import make_model
359
+
360
+ file_contents = get_repo_files(self.structure, file_names)
361
+ compressed_file_contents = {
362
+ fn: get_skeleton(
363
+ code,
364
+ compress_assign=compress_assign,
365
+ total_lines=total_lines,
366
+ prefix_lines=prefix_lines,
367
+ suffix_lines=suffix_lines,
368
+ )
369
+ for fn, code in file_contents.items()
370
+ }
371
+ contents = [
372
+ self.file_content_in_block_template.format(file_name=fn, file_content=code)
373
+ for fn, code in compressed_file_contents.items()
374
+ ]
375
+ file_contents = "".join(contents)
376
+ template = (
377
+ self.obtain_relevant_functions_and_vars_from_compressed_files_prompt_more
378
+ )
379
+ message = template.format(
380
+ problem_statement=self.problem_statement, file_contents=file_contents
381
+ )
382
+ self.logger.info(f"prompting with message:")
383
+ self.logger.info("\n" + message)
384
+
385
+ def message_too_long(message):
386
+ return (
387
+ num_tokens_from_messages(message, self.model_name) >= MAX_CONTEXT_LENGTH
388
+ )
389
+
390
+ while message_too_long(message) and len(contents) > 1:
391
+ self.logger.info(f"reducing to \n{len(contents)} files")
392
+ contents = contents[:-1]
393
+ file_contents = "".join(contents)
394
+ message = template.format(
395
+ problem_statement=self.problem_statement, file_contents=file_contents
396
+ ) # Recreate message
397
+
398
+ if message_too_long(message):
399
+ raise ValueError(
400
+ "The remaining file content is too long to fit within the context length"
401
+ )
402
+ self.logger.info(f"prompting with message:\n{message}")
403
+ self.logger.info("=" * 80)
404
+
405
+ if mock:
406
+ self.logger.info("Skipping querying model since mock=True")
407
+ traj = {
408
+ "prompt": message,
409
+ "usage": {
410
+ "prompt_tokens": num_tokens_from_messages(
411
+ message,
412
+ self.model_name,
413
+ ),
414
+ },
415
+ }
416
+ return {}, {"raw_output_loc": ""}, traj
417
+
418
+ model = make_model(
419
+ model=self.model_name,
420
+ backend=self.backend,
421
+ logger=self.logger,
422
+ max_tokens=self.max_tokens,
423
+ temperature=temperature,
424
+ batch_size=1,
425
+ )
426
+ traj = model.codegen(message, num_samples=1)[0]
427
+ traj["prompt"] = message
428
+ raw_output = traj["response"]
429
+
430
+ model_found_locs = extract_code_blocks(raw_output)
431
+ model_found_locs_separated = extract_locs_for_files(
432
+ model_found_locs, file_names, keep_old_order
433
+ )
434
+
435
+ self.logger.info(f"==== raw output ====")
436
+ self.logger.info(raw_output)
437
+ self.logger.info("=" * 80)
438
+ self.logger.info(f"==== extracted locs ====")
439
+ for loc in model_found_locs_separated:
440
+ self.logger.info(loc)
441
+ self.logger.info("=" * 80)
442
+
443
+ return model_found_locs_separated, {"raw_output_loc": raw_output}, traj
444
+
445
+ def localize_function_from_raw_text(
446
+ self,
447
+ file_names,
448
+ mock=False,
449
+ temperature=0.0,
450
+ keep_old_order=False,
451
+ ):
452
+ from agentless.util.api_requests import num_tokens_from_messages
453
+ from agentless.util.model import make_model
454
+
455
+ file_contents = get_repo_files(self.structure, file_names)
456
+ raw_file_contents = {fn: code for fn, code in file_contents.items()}
457
+ contents = [
458
+ self.file_content_template.format(file_name=fn, file_content=code)
459
+ for fn, code in raw_file_contents.items()
460
+ ]
461
+ file_contents = "".join(contents)
462
+ template = self.obtain_relevant_functions_and_vars_from_raw_files_prompt
463
+ message = template.format(
464
+ problem_statement=self.problem_statement, file_contents=file_contents
465
+ )
466
+ self.logger.info(f"prompting with message:")
467
+ self.logger.info("\n" + message)
468
+
469
+ def message_too_long(message):
470
+ return (
471
+ num_tokens_from_messages(message, self.model_name) >= MAX_CONTEXT_LENGTH
472
+ )
473
+
474
+ while message_too_long(message) and len(contents) > 1:
475
+ self.logger.info(f"reducing to \n{len(contents)} files")
476
+ contents = contents[:-1]
477
+ file_contents = "".join(contents)
478
+ message = template.format(
479
+ problem_statement=self.problem_statement, file_contents=file_contents
480
+ ) # Recreate message
481
+
482
+ if message_too_long(message):
483
+ raise ValueError(
484
+ "The remaining file content is too long to fit within the context length"
485
+ )
486
+ self.logger.info(f"prompting with message:\n{message}")
487
+ self.logger.info("=" * 80)
488
+
489
+ if mock:
490
+ self.logger.info("Skipping querying model since mock=True")
491
+ traj = {
492
+ "prompt": message,
493
+ "usage": {
494
+ "prompt_tokens": num_tokens_from_messages(
495
+ message,
496
+ self.model_name,
497
+ ),
498
+ },
499
+ }
500
+ return {}, {"raw_output_loc": ""}, traj
501
+
502
+ model = make_model(
503
+ model=self.model_name,
504
+ backend=self.backend,
505
+ logger=self.logger,
506
+ max_tokens=self.max_tokens,
507
+ temperature=temperature,
508
+ batch_size=1,
509
+ )
510
+ traj = model.codegen(message, num_samples=1)[0]
511
+ traj["prompt"] = message
512
+ raw_output = traj["response"]
513
+
514
+ model_found_locs = extract_code_blocks(raw_output)
515
+ model_found_locs_separated = extract_locs_for_files(
516
+ model_found_locs, file_names, keep_old_order
517
+ )
518
+
519
+ self.logger.info(f"==== raw output ====")
520
+ self.logger.info(raw_output)
521
+ self.logger.info("=" * 80)
522
+ self.logger.info(f"==== extracted locs ====")
523
+ for loc in model_found_locs_separated:
524
+ self.logger.info(loc)
525
+ self.logger.info("=" * 80)
526
+
527
+ return model_found_locs_separated, {"raw_output_loc": raw_output}, traj
528
+
529
+ def localize_line_from_coarse_function_locs(
530
+ self,
531
+ file_names,
532
+ coarse_locs,
533
+ context_window: int,
534
+ add_space: bool,
535
+ sticky_scroll: bool,
536
+ no_line_number: bool,
537
+ temperature: float = 0.0,
538
+ num_samples: int = 1,
539
+ mock=False,
540
+ keep_old_order=False,
541
+ ):
542
+ from agentless.util.api_requests import num_tokens_from_messages
543
+ from agentless.util.model import make_model
544
+
545
+ file_contents = get_repo_files(self.structure, file_names)
546
+ topn_content, file_loc_intervals = construct_topn_file_context(
547
+ coarse_locs,
548
+ file_names,
549
+ file_contents,
550
+ self.structure,
551
+ context_window=context_window,
552
+ loc_interval=True,
553
+ add_space=add_space,
554
+ sticky_scroll=sticky_scroll,
555
+ no_line_number=no_line_number,
556
+ )
557
+ if no_line_number:
558
+ template = self.obtain_relevant_code_combine_top_n_no_line_number_prompt
559
+ else:
560
+ template = self.obtain_relevant_code_combine_top_n_prompt
561
+ message = template.format(
562
+ problem_statement=self.problem_statement, file_contents=topn_content
563
+ )
564
+ self.logger.info(f"prompting with message:\n{message}")
565
+ self.logger.info("=" * 80)
566
+
567
+ def message_too_long(message):
568
+ return (
569
+ num_tokens_from_messages(message, self.model_name) >= MAX_CONTEXT_LENGTH
570
+ )
571
+
572
+ while message_too_long(message) and len(coarse_locs) > 1:
573
+ self.logger.info(f"reducing to \n{len(coarse_locs)} files")
574
+ coarse_locs.popitem()
575
+ topn_content, file_loc_intervals = construct_topn_file_context(
576
+ coarse_locs,
577
+ file_names,
578
+ file_contents,
579
+ self.structure,
580
+ context_window=context_window,
581
+ loc_interval=True,
582
+ add_space=add_space,
583
+ sticky_scroll=sticky_scroll,
584
+ no_line_number=no_line_number,
585
+ )
586
+ message = template.format(
587
+ problem_statement=self.problem_statement, file_contents=topn_content
588
+ )
589
+
590
+ if message_too_long(message):
591
+ raise ValueError(
592
+ "The remaining file content is too long to fit within the context length"
593
+ )
594
+
595
+ if mock:
596
+ self.logger.info("Skipping querying model since mock=True")
597
+ traj = {
598
+ "prompt": message,
599
+ "usage": {
600
+ "prompt_tokens": num_tokens_from_messages(message, self.model_name),
601
+ },
602
+ }
603
+ return [], {"raw_output_loc": ""}, traj
604
+
605
+ model = make_model(
606
+ model=self.model_name,
607
+ backend=self.backend,
608
+ logger=self.logger,
609
+ max_tokens=self.max_tokens,
610
+ temperature=temperature,
611
+ batch_size=num_samples,
612
+ )
613
+ raw_trajs = model.codegen(
614
+ message, num_samples=num_samples, prompt_cache=num_samples > 1
615
+ )
616
+
617
+ # Merge trajectories
618
+ raw_outputs = [raw_traj["response"] for raw_traj in raw_trajs]
619
+ traj = {
620
+ "prompt": message,
621
+ "response": raw_outputs,
622
+ "usage": { # merge token usage
623
+ "completion_tokens": sum(
624
+ raw_traj["usage"]["completion_tokens"] for raw_traj in raw_trajs
625
+ ),
626
+ "prompt_tokens": sum(
627
+ raw_traj["usage"]["prompt_tokens"] for raw_traj in raw_trajs
628
+ ),
629
+ },
630
+ }
631
+ model_found_locs_separated_in_samples = []
632
+ for raw_output in raw_outputs:
633
+ model_found_locs = extract_code_blocks(raw_output)
634
+ model_found_locs_separated = extract_locs_for_files(
635
+ model_found_locs, file_names, keep_old_order
636
+ )
637
+ model_found_locs_separated_in_samples.append(model_found_locs_separated)
638
+
639
+ self.logger.info(f"==== raw output ====")
640
+ self.logger.info(raw_output)
641
+ self.logger.info("=" * 80)
642
+ self.logger.info(f"==== extracted locs ====")
643
+ for loc in model_found_locs_separated:
644
+ self.logger.info(loc)
645
+ self.logger.info("=" * 80)
646
+ self.logger.info("==== Input coarse_locs")
647
+ coarse_info = ""
648
+ for fn, found_locs in coarse_locs.items():
649
+ coarse_info += f"### {fn}\n"
650
+ if isinstance(found_locs, str):
651
+ coarse_info += found_locs + "\n"
652
+ else:
653
+ coarse_info += "\n".join(found_locs) + "\n"
654
+ self.logger.info("\n" + coarse_info)
655
+ if len(model_found_locs_separated_in_samples) == 1:
656
+ model_found_locs_separated_in_samples = (
657
+ model_found_locs_separated_in_samples[0]
658
+ )
659
+
660
+ return (
661
+ model_found_locs_separated_in_samples,
662
+ {"raw_output_loc": raw_outputs},
663
+ traj,
664
+ )
665
+
666
+ def localize_line_from_raw_text(
667
+ self,
668
+ file_names,
669
+ mock=False,
670
+ temperature=0.0,
671
+ num_samples=1,
672
+ keep_old_order=False,
673
+ ):
674
+ from agentless.util.api_requests import num_tokens_from_messages
675
+ from agentless.util.model import make_model
676
+
677
+ file_contents = get_repo_files(self.structure, file_names)
678
+ raw_file_contents = {
679
+ fn: line_wrap_content(code) for fn, code in file_contents.items()
680
+ }
681
+ contents = [
682
+ self.file_content_template.format(file_name=fn, file_content=code)
683
+ for fn, code in raw_file_contents.items()
684
+ ]
685
+ file_contents = "".join(contents)
686
+ template = self.obtain_relevant_code_combine_top_n_prompt
687
+ message = template.format(
688
+ problem_statement=self.problem_statement, file_contents=file_contents
689
+ )
690
+ self.logger.info(f"prompting with message:")
691
+ self.logger.info("\n" + message)
692
+
693
+ def message_too_long(message):
694
+ return (
695
+ num_tokens_from_messages(message, self.model_name) >= MAX_CONTEXT_LENGTH
696
+ )
697
+
698
+ while message_too_long(message) and len(contents) > 1:
699
+ self.logger.info(f"reducing to \n{len(contents)} files")
700
+ contents = contents[:-1]
701
+ file_contents = "".join(contents)
702
+ message = template.format(
703
+ problem_statement=self.problem_statement, file_contents=file_contents
704
+ ) # Recreate message
705
+
706
+ if message_too_long(message):
707
+ raise ValueError(
708
+ "The remaining file content is too long to fit within the context length"
709
+ )
710
+ self.logger.info(f"prompting with message:\n{message}")
711
+ self.logger.info("=" * 80)
712
+
713
+ if mock:
714
+ self.logger.info("Skipping querying model since mock=True")
715
+ traj = {
716
+ "prompt": message,
717
+ "usage": {
718
+ "prompt_tokens": num_tokens_from_messages(
719
+ message,
720
+ self.model_name,
721
+ ),
722
+ },
723
+ }
724
+ return {}, {"raw_output_loc": ""}, traj
725
+
726
+ model = make_model(
727
+ model=self.model_name,
728
+ backend=self.backend,
729
+ logger=self.logger,
730
+ max_tokens=self.max_tokens,
731
+ temperature=temperature,
732
+ batch_size=num_samples,
733
+ )
734
+ raw_trajs = model.codegen(message, num_samples=num_samples)
735
+
736
+ # Merge trajectories
737
+ raw_outputs = [raw_traj["response"] for raw_traj in raw_trajs]
738
+ traj = {
739
+ "prompt": message,
740
+ "response": raw_outputs,
741
+ "usage": { # merge token usage
742
+ "completion_tokens": sum(
743
+ raw_traj["usage"]["completion_tokens"] for raw_traj in raw_trajs
744
+ ),
745
+ "prompt_tokens": sum(
746
+ raw_traj["usage"]["prompt_tokens"] for raw_traj in raw_trajs
747
+ ),
748
+ },
749
+ }
750
+ model_found_locs_separated_in_samples = []
751
+ for raw_output in raw_outputs:
752
+ model_found_locs = extract_code_blocks(raw_output)
753
+ model_found_locs_separated = extract_locs_for_files(
754
+ model_found_locs, file_names, keep_old_order
755
+ )
756
+ model_found_locs_separated_in_samples.append(model_found_locs_separated)
757
+
758
+ self.logger.info(f"==== raw output ====")
759
+ self.logger.info(raw_output)
760
+ self.logger.info("=" * 80)
761
+ self.logger.info(f"==== extracted locs ====")
762
+ for loc in model_found_locs_separated:
763
+ self.logger.info(loc)
764
+ self.logger.info("=" * 80)
765
+
766
+ if len(model_found_locs_separated_in_samples) == 1:
767
+ model_found_locs_separated_in_samples = (
768
+ model_found_locs_separated_in_samples[0]
769
+ )
770
+
771
+ return (
772
+ model_found_locs_separated_in_samples,
773
+ {"raw_output_loc": raw_outputs},
774
+ traj,
775
+ )
Repos/HWE/agents/Agentless/agentless/fl/Index.py ADDED
@@ -0,0 +1,333 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ import os
3
+ from abc import ABC
4
+
5
+ import tiktoken
6
+ from llama_index.core import (
7
+ Document,
8
+ MockEmbedding,
9
+ Settings,
10
+ StorageContext,
11
+ VectorStoreIndex,
12
+ load_index_from_storage,
13
+ )
14
+ from llama_index.core.callbacks import CallbackManager, TokenCountingHandler
15
+ from llama_index.core.retrievers import VectorIndexRetriever
16
+ from llama_index.core.schema import MetadataMode
17
+ from llama_index.embeddings.openai import OpenAIEmbedding
18
+
19
+ from agentless.util.api_requests import num_tokens_from_messages
20
+ from agentless.util.preprocess_data import (
21
+ clean_method_left_space,
22
+ get_full_file_paths_and_classes_and_functions,
23
+ )
24
+ try:
25
+ from get_repo_structure.get_repo_structure import parse_verilog_file as parse_source_file
26
+ except ImportError:
27
+ from get_repo_structure.get_repo_structure import parse_python_file as parse_source_file
28
+
29
+ VERILOG_EXTENSIONS = {".v", ".sv", ".vh", ".svh"}
30
+
31
+
32
+ def _is_verilog_path(file_name: str) -> bool:
33
+ _, ext = os.path.splitext(file_name)
34
+ return ext.lower() in VERILOG_EXTENSIONS
35
+
36
+
37
+ def _parse_global_stmt(file_content: str, file_name: str) -> tuple[str, str]:
38
+ if _is_verilog_path(file_name):
39
+ return "", ""
40
+ try:
41
+ from agentless.util.index_skeleton import parse_global_stmt_from_code
42
+ except Exception:
43
+ return "", ""
44
+ return parse_global_stmt_from_code(file_content)
45
+
46
+
47
+ def construct_file_meta_data(file_name: str, clazzes: list, functions: list) -> dict:
48
+ meta_data = {
49
+ "file_name": file_name,
50
+ }
51
+ meta_data["File Name"] = file_name
52
+
53
+ if clazzes:
54
+ class_names = ", ".join([c["name"] for c in clazzes])
55
+ meta_data["Classes"] = class_names
56
+ if _is_verilog_path(file_name):
57
+ meta_data["Modules"] = class_names
58
+ if functions:
59
+ function_names = ", ".join([f["name"] for f in functions])
60
+ meta_data["Functions"] = function_names
61
+ if _is_verilog_path(file_name):
62
+ meta_data["Tasks/Functions"] = function_names
63
+
64
+ return meta_data
65
+
66
+
67
+ def check_meta_data(meta_data: dict) -> bool:
68
+
69
+ doc = Document(
70
+ text="",
71
+ metadata=meta_data,
72
+ metadata_template="### {key}: {value}",
73
+ text_template="Metadata:\n{metadata_str}\n-----\nCode:\n{content}",
74
+ )
75
+
76
+ if (
77
+ num_tokens_from_messages(
78
+ doc.get_content(metadata_mode=MetadataMode.EMBED),
79
+ model="text-embedding-3-small",
80
+ )
81
+ > Settings.chunk_size // 2
82
+ ):
83
+ # half of the chunk size should not be metadata
84
+ return False
85
+
86
+ return True
87
+
88
+
89
+ def build_file_documents_simple(
90
+ clazzes: list, functions: list, file_name: str, file_content: str
91
+ ) -> list[Document]:
92
+ """
93
+ Really simple file document format, where we put all content of a single file into a single document
94
+ """
95
+ documents = []
96
+
97
+ meta_data = construct_file_meta_data(file_name, clazzes, functions)
98
+
99
+ doc = Document(
100
+ text=file_content,
101
+ metadata=meta_data,
102
+ metadata_template="### {key}: {value}",
103
+ text_template="Metadata:\n{metadata_str}\n-----\nCode:\n{content}",
104
+ )
105
+ doc.excluded_embed_metadata_keys = ["file_name"] # used for searching only.
106
+ doc.excluded_llm_metadata_keys = ["file_name"] # used for searching only.
107
+ if not check_meta_data(meta_data):
108
+ # meta_data a bit too long, instead we just exclude meta data
109
+ doc.excluded_embed_metadata_keys = list(meta_data.keys())
110
+ doc.excluded_llm_metadata_keys = list(meta_data.keys())
111
+ documents.append(doc)
112
+ else:
113
+ documents.append(doc)
114
+
115
+ return documents
116
+
117
+
118
+ def build_file_documents_complex(
119
+ clazzes: list, functions: list, file_name: str, file_content: str
120
+ ) -> list[Document]:
121
+
122
+ documents = []
123
+
124
+ global_stmt, _ = _parse_global_stmt(file_content, file_name)
125
+ base_meta_data = construct_file_meta_data(file_name, clazzes, functions)
126
+ is_verilog = _is_verilog_path(file_name)
127
+
128
+ for clazz in clazzes:
129
+ content = "\n".join(clazz["text"])
130
+ meta_data = copy.deepcopy(base_meta_data)
131
+ meta_data["Class Name"] = clazz["name"]
132
+ if is_verilog:
133
+ meta_data["Module Name"] = clazz["name"]
134
+ doc = Document(
135
+ text=content,
136
+ metadata=meta_data,
137
+ metadata_template="### {key}: {value}",
138
+ text_template="Metadata:\n{metadata_str}\n-----\nCode:\n{content}",
139
+ )
140
+
141
+ doc.excluded_embed_metadata_keys = ["file_name"] # used for searching only.
142
+ doc.excluded_llm_metadata_keys = ["file_name"] # used for searching only.
143
+ if not check_meta_data(meta_data):
144
+ doc.excluded_embed_metadata_keys = list(meta_data.keys())
145
+ doc.excluded_llm_metadata_keys = list(meta_data.keys())
146
+ documents.append(doc)
147
+
148
+ for class_method in clazz["methods"]:
149
+ method_meta_data = copy.deepcopy(base_meta_data)
150
+ method_meta_data["Class Name"] = clazz["name"]
151
+ method_meta_data["Method Name"] = class_method["name"]
152
+ if is_verilog:
153
+ method_meta_data["Task/Function Name"] = class_method["name"]
154
+ content = clean_method_left_space("\n".join(class_method["text"]))
155
+
156
+ doc = Document(
157
+ text=content,
158
+ metadata=method_meta_data,
159
+ metadata_template="### {key}: {value}",
160
+ text_template="Metadata:\n{metadata_str}\n-----\nCode:\n{content}",
161
+ )
162
+ doc.excluded_embed_metadata_keys = ["file_name"] # used for searching only.
163
+ doc.excluded_llm_metadata_keys = ["file_name"] # used for searching only.
164
+ if not check_meta_data(method_meta_data):
165
+ doc.excluded_embed_metadata_keys = list(method_meta_data.keys())
166
+ doc.excluded_llm_metadata_keys = list(method_meta_data.keys())
167
+ documents.append(doc)
168
+
169
+ for function in functions:
170
+ content = "\n".join(function["text"])
171
+ function_meta_data = copy.deepcopy(base_meta_data)
172
+ function_meta_data["Function Name"] = function["name"]
173
+ if is_verilog:
174
+ function_meta_data["Task/Function Name"] = function["name"]
175
+ doc = Document(
176
+ text=content,
177
+ metadata=function_meta_data,
178
+ metadata_template="### {key}: {value}",
179
+ text_template="Metadata:\n{metadata_str}\n-----\nCode:\n{content}",
180
+ )
181
+
182
+ doc.excluded_embed_metadata_keys = ["file_name"] # used for searching only.
183
+ doc.excluded_llm_metadata_keys = ["file_name"] # used for searching only.
184
+ if not check_meta_data(function_meta_data):
185
+ doc.excluded_embed_metadata_keys = list(function_meta_data.keys())
186
+ doc.excluded_llm_metadata_keys = list(function_meta_data.keys())
187
+ documents.append(doc)
188
+
189
+ if global_stmt != "":
190
+ content = global_stmt
191
+ global_meta_data = copy.deepcopy(base_meta_data)
192
+
193
+ doc = Document(
194
+ text=content,
195
+ metadata=global_meta_data,
196
+ metadata_template="### {key}: {value}",
197
+ text_template="Metadata:\n{metadata_str}\n-----\nCode:\n{content}",
198
+ )
199
+ doc.excluded_embed_metadata_keys = ["file_name"] # used for searching only.
200
+ doc.excluded_llm_metadata_keys = ["file_name"] # used for searching only.
201
+ if not check_meta_data(global_meta_data):
202
+ doc.excluded_embed_metadata_keys = list(global_meta_data.keys())
203
+ doc.excluded_llm_metadata_keys = list(global_meta_data.keys())
204
+ documents.append(doc)
205
+
206
+ return documents
207
+
208
+
209
+ class EmbeddingIndex(ABC):
210
+ def __init__(
211
+ self,
212
+ instance_id,
213
+ structure,
214
+ problem_statement,
215
+ persist_dir,
216
+ filter_type,
217
+ index_type,
218
+ chunk_size,
219
+ chunk_overlap,
220
+ logger,
221
+ **kwargs,
222
+ ):
223
+ self.instance_id = instance_id
224
+ self.structure = structure
225
+ self.problem_statement = problem_statement
226
+ self.persist_dir = persist_dir + "/{instance_id}"
227
+ self.filter_type = filter_type
228
+ self.index_type = index_type
229
+ self.chunk_size = chunk_size
230
+ self.chunk_overlap = chunk_overlap
231
+ self.logger = logger
232
+ self.kwargs = kwargs
233
+ # set some embedding global settings.
234
+
235
+ Settings.chunk_size = chunk_size
236
+ Settings.chunk_overlap = chunk_overlap
237
+
238
+ def filter_files(self, files):
239
+ if self.filter_type == "given_files":
240
+ given_files = self.kwargs["given_files"][: self.kwargs["filter_top_n"]]
241
+ return given_files
242
+ elif self.filter_type == "none":
243
+ # all files are included
244
+ return [file_content[0] for file_content in files]
245
+ else:
246
+ raise NotImplementedError
247
+
248
+ def retrieve(self, mock=False):
249
+
250
+ persist_dir = self.persist_dir.format(instance_id=self.instance_id)
251
+ token_counter = TokenCountingHandler(
252
+ tokenizer=tiktoken.encoding_for_model("text-embedding-3-small").encode
253
+ )
254
+ if not os.path.exists(persist_dir) or mock:
255
+ files, _, _ = get_full_file_paths_and_classes_and_functions(self.structure)
256
+ filtered_files = self.filter_files(files)
257
+ self.logger.info(f"Total number of considered files: {len(filtered_files)}")
258
+ print(f"Total number of considered files: {len(filtered_files)}")
259
+ documents = []
260
+
261
+ for file_content in files:
262
+ content = "\n".join(file_content[1])
263
+ file_name = file_content[0]
264
+
265
+ if file_name not in filtered_files:
266
+ continue
267
+
268
+ # create documents
269
+ class_info, function_names, _ = parse_source_file(None, content)
270
+ if self.index_type == "simple":
271
+ docs = build_file_documents_simple(
272
+ class_info, function_names, file_name, content
273
+ )
274
+ elif self.index_type == "complex":
275
+ docs = build_file_documents_complex(
276
+ class_info, function_names, file_name, content
277
+ )
278
+ else:
279
+ raise NotImplementedError
280
+
281
+ documents.extend(docs)
282
+
283
+ self.logger.info(f"Total number of documents: {len(documents)}")
284
+ print(f"Total number of documents: {len(documents)}")
285
+
286
+ if mock:
287
+ embed_model = MockEmbedding(
288
+ embed_dim=1024
289
+ ) # embedding dimension does not matter for mocking.
290
+ Settings.callback_manager = CallbackManager([token_counter])
291
+ else:
292
+ embed_model = OpenAIEmbedding(model_name="text-embedding-3-small")
293
+ index = VectorStoreIndex.from_documents(documents, embed_model=embed_model)
294
+ index.storage_context.persist(persist_dir=persist_dir)
295
+ else:
296
+ storage_context = StorageContext.from_defaults(persist_dir=persist_dir)
297
+ index = load_index_from_storage(storage_context)
298
+
299
+ self.logger.info(f"Retrieving with query:\n{self.problem_statement}")
300
+
301
+ retriever = VectorIndexRetriever(index=index, similarity_top_k=100)
302
+ documents = retriever.retrieve(self.problem_statement)
303
+
304
+ self.logger.info(
305
+ f"Embedding Tokens: {token_counter.total_embedding_token_count}"
306
+ )
307
+ print(f"Embedding Tokens: {token_counter.total_embedding_token_count}")
308
+
309
+ traj = {
310
+ "usage": {"embedding_tokens": token_counter.total_embedding_token_count}
311
+ }
312
+
313
+ token_counter.reset_counts()
314
+
315
+ if mock:
316
+ self.logger.info("Skipping since mock=True")
317
+ return [], None, traj
318
+
319
+ file_names = []
320
+ meta_infos = []
321
+
322
+ for node in documents:
323
+ file_name = node.node.metadata["File Name"]
324
+ if file_name not in file_names:
325
+ file_names.append(file_name)
326
+ self.logger.info("================")
327
+ self.logger.info(file_name)
328
+
329
+ self.logger.info(node.node.text)
330
+
331
+ meta_infos.append({"code": node.node.text, "metadata": node.node.metadata})
332
+
333
+ return file_names, meta_infos, traj
Repos/HWE/agents/Agentless/agentless/fl/combine.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import json
3
+ import os
4
+ from collections import Counter
5
+
6
+ from tqdm import tqdm
7
+
8
+ from agentless.util.utils import load_jsonl
9
+
10
+
11
+ def combine_file_level(args):
12
+
13
+ embed_used_locs = load_jsonl(args.retrieval_loc_file)
14
+ model_used_locs = load_jsonl(args.model_loc_file)
15
+
16
+ with open(f"{args.output_folder}/embed_used_locs.jsonl", "w") as f:
17
+ for loc in embed_used_locs:
18
+ f.write(json.dumps(loc) + "\n")
19
+
20
+ with open(f"{args.output_folder}/model_used_locs.jsonl", "w") as f:
21
+ for loc in model_used_locs:
22
+ f.write(json.dumps(loc) + "\n")
23
+
24
+ for pred in tqdm(model_used_locs, colour="MAGENTA"):
25
+ instance_id = pred["instance_id"]
26
+
27
+ model_loc = pred["found_files"]
28
+ retrieve_loc = [x for x in embed_used_locs if x["instance_id"] == instance_id][
29
+ 0
30
+ ]["found_files"]
31
+
32
+ combined_loc_counter = Counter()
33
+ combined_locs = []
34
+
35
+ for loc in model_loc[: args.top_n]:
36
+ combined_loc_counter[loc] += 1
37
+
38
+ for loc in retrieve_loc[: args.top_n]:
39
+ combined_loc_counter[loc] += 1
40
+
41
+ combined_locs = [loc for loc, _ in combined_loc_counter.most_common()]
42
+
43
+ with open(args.output_file, "a") as f:
44
+ f.write(
45
+ json.dumps(
46
+ {
47
+ "instance_id": instance_id,
48
+ "found_files": combined_locs,
49
+ "additional_artifact_loc_file": {},
50
+ "file_traj": {},
51
+ }
52
+ )
53
+ + "\n"
54
+ )
55
+
56
+
57
+ def main():
58
+ parser = argparse.ArgumentParser()
59
+
60
+ parser.add_argument("--output_folder", type=str, required=True)
61
+ parser.add_argument("--output_file", type=str, default="combined_locs.jsonl")
62
+ parser.add_argument("--retrieval_loc_file", type=str, required=True)
63
+ parser.add_argument("--model_loc_file", type=str, required=True)
64
+ # supports file level (step-1) combination
65
+ parser.add_argument("--top_n", type=int, required=True)
66
+
67
+ args = parser.parse_args()
68
+
69
+ args.output_file = os.path.join(args.output_folder, args.output_file)
70
+ assert not os.path.exists(args.output_file), "Output file already exists"
71
+
72
+ os.makedirs(args.output_folder, exist_ok=True)
73
+
74
+ # dump argument
75
+ with open(os.path.join(args.output_folder, "args.json"), "w") as f:
76
+ json.dump(vars(args), f, indent=4)
77
+
78
+ combine_file_level(args)
79
+
80
+
81
+ if __name__ == "__main__":
82
+ main()
Repos/HWE/agents/Agentless/agentless/fl/localize.py ADDED
@@ -0,0 +1,680 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import concurrent.futures
3
+ import json
4
+ import os
5
+ from threading import Lock
6
+
7
+ from datasets import load_dataset
8
+ from tqdm import tqdm
9
+
10
+ from agentless.fl.FL import LLMFL
11
+ from agentless.util.preprocess_data import (
12
+ check_contains_valid_loc,
13
+ filter_non_source,
14
+ filter_out_test_files,
15
+ get_repo_structure,
16
+ )
17
+ from agentless.util.utils import load_existing_instance_ids, load_jsonl, setup_logger
18
+
19
+ MAX_RETRIES = 5
20
+ HDL_EXTENSIONS = {".v", ".sv", ".vh", ".svh"}
21
+
22
+
23
+ def _filter_hdl_files(files):
24
+ return [
25
+ file
26
+ for file in files
27
+ if os.path.splitext(file)[1].lower() in HDL_EXTENSIONS
28
+ ]
29
+
30
+
31
+ def _filter_loc_dict(locs, allowed_files):
32
+ if not isinstance(locs, dict):
33
+ return locs
34
+ return {file: loc for file, loc in locs.items() if file in allowed_files}
35
+
36
+
37
+ def _filter_edit_locs(edit_locs, allowed_files):
38
+ if isinstance(edit_locs, list):
39
+ return [
40
+ _filter_loc_dict(loc, allowed_files) if isinstance(loc, dict) else loc
41
+ for loc in edit_locs
42
+ ]
43
+ if isinstance(edit_locs, dict):
44
+ return _filter_loc_dict(edit_locs, allowed_files)
45
+ return edit_locs
46
+
47
+
48
+ def load_bench_data(args):
49
+ if args.dataset_path:
50
+ if args.dataset_path.endswith(".jsonl"):
51
+ return load_jsonl(args.dataset_path)
52
+ if args.dataset_path.endswith(".json"):
53
+ with open(args.dataset_path, "r") as f:
54
+ return json.load(f)
55
+ raise ValueError("Unsupported dataset_path; use .json or .jsonl")
56
+ return load_dataset(args.dataset, split=args.dataset_split)
57
+
58
+
59
+ def localize_irrelevant_instance(
60
+ bug, args, swe_bench_data, existing_instance_ids, write_lock=None
61
+ ):
62
+ instance_id = bug["instance_id"]
63
+ log_file = os.path.join(
64
+ args.output_folder, "localization_logs", f"{instance_id}.log"
65
+ )
66
+ if args.target_id is not None:
67
+ if args.target_id != bug["instance_id"]:
68
+ return
69
+
70
+ logger = setup_logger(log_file)
71
+ logger.info(f"Processing bug {instance_id}")
72
+
73
+ if bug["instance_id"] in existing_instance_ids:
74
+ logger.info(f"Skipping existing instance_id: {bug['instance_id']}")
75
+ return
76
+
77
+ logger.info(f"================ localize {instance_id} ================")
78
+
79
+ bench_data = [x for x in swe_bench_data if x["instance_id"] == instance_id][0]
80
+ problem_statement = bench_data["problem_statement"]
81
+ structure = get_repo_structure(
82
+ instance_id, bug["repo"], bug["base_commit"], "playground"
83
+ )
84
+
85
+ filter_non_source(structure) # some basic filtering steps
86
+ filter_out_test_files(structure)
87
+
88
+ found_files = []
89
+ found_related_locs = {}
90
+ found_edit_locs = {}
91
+
92
+ additional_artifact_loc_file = None
93
+ additional_artifact_loc_related = None
94
+ additional_artifact_loc_edit_location = None
95
+ file_traj, related_loc_traj, edit_loc_traj = {}, {}, {}
96
+
97
+ # file level localization
98
+ if args.file_level:
99
+ fl = LLMFL(
100
+ instance_id,
101
+ structure,
102
+ problem_statement,
103
+ args.model,
104
+ args.backend,
105
+ logger,
106
+ )
107
+ found_files, additional_artifact_loc_file, file_traj = fl.localize_irrelevant(
108
+ mock=args.mock
109
+ )
110
+ found_files = _filter_hdl_files(found_files)
111
+ else:
112
+ raise NotImplementedError
113
+
114
+ if write_lock is not None:
115
+ write_lock.acquire()
116
+ allowed_files = set(found_files)
117
+ found_related_locs = _filter_loc_dict(found_related_locs, allowed_files)
118
+ found_edit_locs = _filter_edit_locs(found_edit_locs, allowed_files)
119
+ with open(args.output_file, "a") as f:
120
+ f.write(
121
+ json.dumps(
122
+ {
123
+ "instance_id": instance_id,
124
+ "found_files": found_files,
125
+ "additional_artifact_loc_file": additional_artifact_loc_file,
126
+ "file_traj": file_traj,
127
+ "found_related_locs": found_related_locs,
128
+ "additional_artifact_loc_related": additional_artifact_loc_related,
129
+ "related_loc_traj": related_loc_traj,
130
+ "found_edit_locs": found_edit_locs,
131
+ "additional_artifact_loc_edit_location": additional_artifact_loc_edit_location,
132
+ "edit_loc_traj": edit_loc_traj,
133
+ }
134
+ )
135
+ + "\n"
136
+ )
137
+ if write_lock is not None:
138
+ write_lock.release()
139
+
140
+
141
+ def localize_instance(
142
+ bug, args, swe_bench_data, start_file_locs, existing_instance_ids, write_lock=None
143
+ ):
144
+ instance_id = bug["instance_id"]
145
+ log_file = os.path.join(
146
+ args.output_folder, "localization_logs", f"{instance_id}.log"
147
+ )
148
+ if args.target_id is not None:
149
+ if args.target_id != bug["instance_id"]:
150
+ return
151
+
152
+ logger = setup_logger(log_file)
153
+ logger.info(f"Processing bug {instance_id}")
154
+
155
+ if instance_id in existing_instance_ids:
156
+ logger.info(f"Skipping existing instance_id: {bug['instance_id']}")
157
+ return
158
+
159
+ structure = get_repo_structure(
160
+ instance_id, bug["repo"], bug["base_commit"], "playground"
161
+ )
162
+
163
+ logger.info(f"================ localize {instance_id} ================")
164
+
165
+ bench_data = [x for x in swe_bench_data if x["instance_id"] == instance_id][0]
166
+ problem_statement = bench_data["problem_statement"]
167
+
168
+ filter_non_source(structure) # some basic filtering steps
169
+ filter_out_test_files(structure)
170
+
171
+ found_files = []
172
+ found_related_locs = {}
173
+ found_edit_locs = {}
174
+ additional_artifact_loc_file = None
175
+ additional_artifact_loc_related = None
176
+ additional_artifact_loc_edit_location = None
177
+ file_traj, related_loc_trajs, edit_loc_traj = {}, [], {}
178
+
179
+ # file level localization
180
+ if args.file_level:
181
+ fl = LLMFL(
182
+ instance_id,
183
+ structure,
184
+ problem_statement,
185
+ args.model,
186
+ args.backend,
187
+ logger,
188
+ )
189
+ found_files, additional_artifact_loc_file, file_traj = fl.localize(
190
+ mock=args.mock
191
+ )
192
+ found_files = _filter_hdl_files(found_files)
193
+ else:
194
+ # assume start_file is provided
195
+ for locs in start_file_locs:
196
+ if locs["instance_id"] == instance_id:
197
+ found_files = locs["found_files"]
198
+ if "additional_artifact_loc_file" in locs:
199
+ additional_artifact_loc_file = locs["additional_artifact_loc_file"]
200
+ file_traj = locs["file_traj"]
201
+ if "found_related_locs" in locs:
202
+ found_related_locs = locs["found_related_locs"]
203
+ additional_artifact_loc_related = locs[
204
+ "additional_artifact_loc_related"
205
+ ]
206
+ related_loc_trajs = locs["related_loc_traj"]
207
+ break
208
+
209
+ found_files = _filter_hdl_files(found_files)
210
+ allowed_files = set(found_files)
211
+ found_related_locs = _filter_loc_dict(found_related_locs, allowed_files)
212
+
213
+ if len(found_files) == 0:
214
+ return
215
+
216
+ # related class, functions, global var localization
217
+ if args.related_level:
218
+ if len(found_files) != 0:
219
+ trying_temp = 0 # related always try with temp 0
220
+ related_loc_trajs = []
221
+ for _ in range(MAX_RETRIES):
222
+ pred_files = found_files[: args.top_n]
223
+ fl = LLMFL(
224
+ instance_id,
225
+ structure,
226
+ problem_statement,
227
+ args.model,
228
+ args.backend,
229
+ logger,
230
+ )
231
+ additional_artifact_loc_related = []
232
+ found_related_locs = {}
233
+ related_loc_traj = {}
234
+ if args.compress and not args.related_level_separate_file:
235
+ (
236
+ found_related_locs,
237
+ additional_artifact_loc_related,
238
+ related_loc_traj,
239
+ ) = fl.localize_function_from_compressed_files(
240
+ pred_files,
241
+ mock=args.mock,
242
+ temperature=trying_temp,
243
+ keep_old_order=args.keep_old_order,
244
+ compress_assign=args.compress_assign,
245
+ total_lines=args.compress_assign_total_lines,
246
+ prefix_lines=args.compress_assign_prefix_lines,
247
+ suffix_lines=args.compress_assign_suffix_lines,
248
+ )
249
+ additional_artifact_loc_related = [additional_artifact_loc_related]
250
+ related_loc_trajs.append(related_loc_traj)
251
+
252
+ if check_contains_valid_loc(
253
+ found_related_locs, structure=structure
254
+ ):
255
+ break
256
+
257
+ logger.info(
258
+ f"No valid related locations found ... retrying with higher temperature ..."
259
+ )
260
+ trying_temp = 1.0 # set trying temp to 1 to get valid locs
261
+
262
+ elif args.compress and args.related_level_separate_file:
263
+ additional_artifact_loc_related = []
264
+ found_related_locs = {fn: [] for fn in pred_files}
265
+ related_loc_traj = []
266
+ for i, pred_file in enumerate(pred_files):
267
+ (
268
+ found_related_locs_i,
269
+ additional_artifact_loc_related_i,
270
+ related_loc_traj_i,
271
+ ) = fl.localize_function_from_compressed_files(
272
+ [pred_file],
273
+ mock=args.mock,
274
+ temperature=trying_temp,
275
+ compress_assign=args.compress_assign,
276
+ total_lines=args.compress_assign_total_lines,
277
+ prefix_lines=args.compress_assign_prefix_lines,
278
+ suffix_lines=args.compress_assign_suffix_lines,
279
+ )
280
+ found_related_locs[pred_file] = found_related_locs_i[pred_file]
281
+ additional_artifact_loc_related.append(
282
+ additional_artifact_loc_related_i
283
+ )
284
+ related_loc_traj.append(related_loc_traj_i)
285
+ related_loc_trajs.append(related_loc_traj)
286
+
287
+ if check_contains_valid_loc(
288
+ found_related_locs, structure=structure
289
+ ):
290
+ break
291
+ trying_temp = 1.0 # set trying temp to 1 to get valid locs
292
+ else:
293
+ # directly use raw code file instead of skeleton format as ablation
294
+ (
295
+ found_related_locs,
296
+ additional_artifact_loc_related,
297
+ related_loc_traj,
298
+ ) = fl.localize_function_from_raw_text(
299
+ pred_files,
300
+ mock=args.mock,
301
+ temperature=trying_temp,
302
+ keep_old_order=args.keep_old_order,
303
+ )
304
+ additional_artifact_loc_related = [additional_artifact_loc_related]
305
+ related_loc_trajs.append(related_loc_traj)
306
+
307
+ if check_contains_valid_loc(
308
+ found_related_locs, structure=structure
309
+ ):
310
+ break
311
+
312
+ logger.info(
313
+ f"No valid related locations found ... retrying with higher temperature ..."
314
+ )
315
+ trying_temp = 1.0 # set trying temp to 1 to get valid locs
316
+
317
+ if args.fine_grain_line_level:
318
+ if len(found_files) != 0:
319
+ # Only supports the following args for now
320
+ trying_temp = args.temperature
321
+ for _ in range(MAX_RETRIES):
322
+ pred_files = found_files[: args.top_n]
323
+ fl = LLMFL(
324
+ instance_id,
325
+ structure,
326
+ problem_statement,
327
+ args.model,
328
+ args.backend,
329
+ logger,
330
+ )
331
+ if not args.direct_edit_loc:
332
+ coarse_found_locs = found_related_locs
333
+ (
334
+ found_edit_locs,
335
+ additional_artifact_loc_edit_location,
336
+ edit_loc_traj,
337
+ ) = fl.localize_line_from_coarse_function_locs(
338
+ pred_files,
339
+ coarse_found_locs,
340
+ context_window=args.context_window,
341
+ add_space=args.add_space,
342
+ no_line_number=args.no_line_number,
343
+ sticky_scroll=args.sticky_scroll,
344
+ mock=args.mock,
345
+ temperature=trying_temp,
346
+ num_samples=args.num_samples,
347
+ keep_old_order=args.keep_old_order,
348
+ )
349
+ additional_artifact_loc_edit_location = [
350
+ additional_artifact_loc_edit_location
351
+ ]
352
+ if args.num_samples > 1 and isinstance(found_edit_locs, dict):
353
+ logger.info(
354
+ "Requested multiple samples but got a single response from "
355
+ f"{args.backend}:{args.model}; wrapping for validation."
356
+ )
357
+ found_edit_locs = [found_edit_locs]
358
+
359
+ sample_valid = False
360
+ if args.num_samples > 1:
361
+ for found_edit_loc in found_edit_locs:
362
+ if check_contains_valid_loc(
363
+ found_edit_loc, structure=structure
364
+ ):
365
+ # at least one set of location contains valid edit locs is okay
366
+ sample_valid = True
367
+ break
368
+ else:
369
+ if check_contains_valid_loc(
370
+ found_edit_locs, structure=structure
371
+ ):
372
+ break
373
+
374
+ if sample_valid:
375
+ break
376
+
377
+ logger.info(
378
+ f"No valid edit locations found ... retrying with higher temperature ..."
379
+ )
380
+ trying_temp = 1.0 # set trying temp to 1 to get valid locs
381
+ else:
382
+ # directly use the raw source code to get to edit location, used as ablation setting
383
+ (
384
+ found_edit_locs,
385
+ additional_artifact_loc_edit_location,
386
+ edit_loc_traj,
387
+ ) = fl.localize_line_from_raw_text(
388
+ pred_files,
389
+ mock=args.mock,
390
+ temperature=trying_temp,
391
+ num_samples=args.num_samples,
392
+ keep_old_order=args.keep_old_order,
393
+ )
394
+ additional_artifact_loc_edit_location = [
395
+ additional_artifact_loc_edit_location
396
+ ]
397
+ if args.num_samples > 1 and isinstance(found_edit_locs, dict):
398
+ logger.info(
399
+ "Requested multiple samples but got a single response from "
400
+ f"{args.backend}:{args.model}; wrapping for validation."
401
+ )
402
+ found_edit_locs = [found_edit_locs]
403
+
404
+ if check_contains_valid_loc(
405
+ found_related_locs, structure=structure
406
+ ):
407
+ break
408
+
409
+ sample_valid = False
410
+ if args.num_samples > 1:
411
+ for found_edit_loc in found_edit_locs:
412
+ if check_contains_valid_loc(
413
+ found_edit_loc, structure=structure
414
+ ):
415
+ # at least one set of location contains valid edit locs is okay
416
+ sample_valid = True
417
+ break
418
+ else:
419
+ if check_contains_valid_loc(
420
+ found_edit_locs, structure=structure
421
+ ):
422
+ break
423
+
424
+ if sample_valid:
425
+ break
426
+
427
+ logger.info(
428
+ f"No valid edit locations found ... retrying with higher temperature ..."
429
+ )
430
+ trying_temp = 1.0 # set trying temp to 1 to get valid locs
431
+
432
+ if write_lock is not None:
433
+ write_lock.acquire()
434
+ with open(args.output_file, "a") as f:
435
+ f.write(
436
+ json.dumps(
437
+ {
438
+ "instance_id": instance_id,
439
+ "found_files": found_files,
440
+ "additional_artifact_loc_file": additional_artifact_loc_file,
441
+ "file_traj": file_traj,
442
+ "found_related_locs": found_related_locs,
443
+ "additional_artifact_loc_related": additional_artifact_loc_related,
444
+ "related_loc_traj": related_loc_trajs,
445
+ "found_edit_locs": found_edit_locs,
446
+ "additional_artifact_loc_edit_location": additional_artifact_loc_edit_location,
447
+ "edit_loc_traj": edit_loc_traj,
448
+ }
449
+ )
450
+ + "\n"
451
+ )
452
+ if write_lock is not None:
453
+ write_lock.release()
454
+
455
+
456
+ def localize_irrelevant(args):
457
+ swe_bench_data = load_bench_data(args)
458
+ existing_instance_ids = (
459
+ load_existing_instance_ids(args.output_file) if args.skip_existing else set()
460
+ )
461
+ if args.num_threads == 1:
462
+ for bug in tqdm(swe_bench_data, colour="MAGENTA"):
463
+ localize_irrelevant_instance(
464
+ bug, args, swe_bench_data, existing_instance_ids
465
+ )
466
+ else:
467
+ write_lock = Lock()
468
+ with concurrent.futures.ThreadPoolExecutor(
469
+ max_workers=args.num_threads
470
+ ) as executor:
471
+ futures = [
472
+ executor.submit(
473
+ localize_irrelevant_instance,
474
+ bug,
475
+ args,
476
+ swe_bench_data,
477
+ existing_instance_ids,
478
+ write_lock,
479
+ )
480
+ for bug in swe_bench_data
481
+ ]
482
+ for future in tqdm(
483
+ concurrent.futures.as_completed(futures),
484
+ total=len(swe_bench_data),
485
+ colour="MAGENTA",
486
+ ):
487
+ future.result()
488
+
489
+
490
+ def localize(args):
491
+ swe_bench_data = load_bench_data(args)
492
+ start_file_locs = load_jsonl(args.start_file) if args.start_file else None
493
+ existing_instance_ids = (
494
+ load_existing_instance_ids(args.output_file) if args.skip_existing else set()
495
+ )
496
+
497
+ if args.num_threads == 1:
498
+ for bug in tqdm(swe_bench_data, colour="MAGENTA"):
499
+ localize_instance(
500
+ bug, args, swe_bench_data, start_file_locs, existing_instance_ids
501
+ )
502
+ else:
503
+ write_lock = Lock()
504
+ with concurrent.futures.ThreadPoolExecutor(
505
+ max_workers=args.num_threads
506
+ ) as executor:
507
+ futures = [
508
+ executor.submit(
509
+ localize_instance,
510
+ bug,
511
+ args,
512
+ swe_bench_data,
513
+ start_file_locs,
514
+ existing_instance_ids,
515
+ write_lock,
516
+ )
517
+ for bug in swe_bench_data
518
+ ]
519
+ for future in tqdm(
520
+ concurrent.futures.as_completed(futures),
521
+ total=len(swe_bench_data),
522
+ colour="MAGENTA",
523
+ ):
524
+ future.result()
525
+
526
+
527
+ def merge(args):
528
+ """Merge predicted locations."""
529
+ start_file_locs = load_jsonl(args.start_file)
530
+
531
+ def merge_locs(sample_found_locs: list[dict]):
532
+ merged_found_locs = {}
533
+ for locs in sample_found_locs:
534
+ for fn, file_found_locs in locs.items():
535
+ if isinstance(file_found_locs, str) and file_found_locs.strip():
536
+ merged_found_locs.setdefault(fn, [""])[0] += "\n" + file_found_locs
537
+ elif "\n".join(file_found_locs).strip():
538
+ merged_found_locs.setdefault(fn, [""])[0] += "\n" + "\n".join(
539
+ file_found_locs
540
+ )
541
+ return merged_found_locs
542
+
543
+ # Dump each location sample.
544
+ for st_id in range(args.num_samples):
545
+ en_id = st_id
546
+ merged_locs = []
547
+ for locs in start_file_locs:
548
+ merged_found_locs = []
549
+ if "found_edit_locs" in locs and len(locs["found_edit_locs"]):
550
+ merged_found_locs = merge_locs(
551
+ locs["found_edit_locs"][st_id : st_id + 1]
552
+ )
553
+ merged_locs.append({**locs, "found_edit_locs": merged_found_locs})
554
+ with open(
555
+ f"{args.output_folder}/loc_merged_{st_id}-{en_id}_outputs.jsonl", "w"
556
+ ) as f:
557
+ for data in merged_locs:
558
+ f.write(json.dumps(data) + "\n")
559
+
560
+
561
+ def check_valid_args(args):
562
+ assert (
563
+ not os.path.exists(args.output_file) or args.skip_existing
564
+ ), "Output file already exists and not set to skip existing localizations"
565
+
566
+ assert not (
567
+ args.file_level and args.start_file
568
+ ), "Cannot use both file_level and start_file"
569
+
570
+ assert not (
571
+ args.file_level and args.fine_grain_line_level and not args.related_level
572
+ ), "Cannot use both file_level and fine_grain_line_level without related_level"
573
+
574
+ assert not (
575
+ (not args.file_level) and (not args.start_file)
576
+ ), "Must use either file_level or start_file"
577
+
578
+ assert (not "deepseek" in args.model) or (
579
+ args.backend == "deepseek"
580
+ ), "Must specify `--backend deepseek` if using a DeepSeek model"
581
+
582
+
583
+ def main():
584
+ parser = argparse.ArgumentParser()
585
+
586
+ parser.add_argument("--output_folder", type=str, required=True)
587
+ parser.add_argument("--output_file", type=str, default="loc_outputs.jsonl")
588
+ parser.add_argument(
589
+ "--start_file",
590
+ type=str,
591
+ help="""previous output file to start with to reduce
592
+ the work, should use in combination without --file_level""",
593
+ )
594
+ parser.add_argument("--file_level", action="store_true")
595
+ parser.add_argument("--related_level", action="store_true")
596
+ parser.add_argument("--fine_grain_line_level", action="store_true")
597
+ parser.add_argument("--top_n", type=int, default=3)
598
+ parser.add_argument("--temperature", type=float, default=0.0)
599
+ parser.add_argument("--num_samples", type=int, default=1)
600
+ parser.add_argument("--compress", action="store_true")
601
+ parser.add_argument("--compress_assign", action="store_true")
602
+ parser.add_argument("--compress_assign_total_lines", type=int, default=30)
603
+ parser.add_argument("--compress_assign_prefix_lines", type=int, default=10)
604
+ parser.add_argument("--compress_assign_suffix_lines", type=int, default=10)
605
+ parser.add_argument("--merge", action="store_true")
606
+ parser.add_argument("--add_space", action="store_true")
607
+ parser.add_argument("--no_line_number", action="store_true")
608
+ parser.add_argument("--sticky_scroll", action="store_true")
609
+ parser.add_argument("--related_level_separate_file", action="store_true")
610
+ parser.add_argument("--context_window", type=int, default=10)
611
+ parser.add_argument("--keep_old_order", action="store_true")
612
+ parser.add_argument("--irrelevant", action="store_true")
613
+ parser.add_argument("--direct_edit_loc", action="store_true")
614
+ parser.add_argument(
615
+ "--num_threads",
616
+ type=int,
617
+ default=1,
618
+ help="Number of threads to use for creating API requests",
619
+ )
620
+ parser.add_argument("--target_id", type=str)
621
+ parser.add_argument(
622
+ "--skip_existing",
623
+ action="store_true",
624
+ help="Skip localization of instance id's which already contain a localization in the output file.",
625
+ )
626
+ parser.add_argument(
627
+ "--mock", action="store_true", help="Mock run to compute prompt tokens."
628
+ )
629
+ parser.add_argument(
630
+ "--model",
631
+ type=str,
632
+ default=os.getenv("AGENTLESS_MODEL", "gpt-5.2"),
633
+ help="Model name (defaults to $AGENTLESS_MODEL).",
634
+ )
635
+ parser.add_argument(
636
+ "--backend",
637
+ type=str,
638
+ default="openai",
639
+ choices=["openai", "deepseek", "anthropic"],
640
+ )
641
+ parser.add_argument(
642
+ "--dataset",
643
+ type=str,
644
+ default="princeton-nlp/SWE-bench_Lite",
645
+ choices=["princeton-nlp/SWE-bench_Lite", "princeton-nlp/SWE-bench_Verified"],
646
+ help="Current supported dataset for evaluation",
647
+ )
648
+ parser.add_argument(
649
+ "--dataset_path",
650
+ type=str,
651
+ help="Local dataset file (JSON or JSONL) built by build_dataset.py.",
652
+ )
653
+ parser.add_argument(
654
+ "--dataset_split",
655
+ type=str,
656
+ default="test",
657
+ help="Split name when loading an HF dataset.",
658
+ )
659
+
660
+ args = parser.parse_args()
661
+ args.output_file = os.path.join(args.output_folder, args.output_file)
662
+ check_valid_args(args)
663
+
664
+ os.makedirs(os.path.join(args.output_folder, "localization_logs"), exist_ok=True)
665
+ os.makedirs(args.output_folder, exist_ok=True)
666
+
667
+ # write the arguments
668
+ with open(f"{args.output_folder}/args.json", "w") as f:
669
+ json.dump(vars(args), f, indent=4)
670
+
671
+ if args.merge:
672
+ merge(args)
673
+ elif args.irrelevant:
674
+ localize_irrelevant(args)
675
+ else:
676
+ localize(args)
677
+
678
+
679
+ if __name__ == "__main__":
680
+ main()
Repos/HWE/agents/Agentless/agentless/fl/retrieve.py ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import concurrent.futures
3
+ import json
4
+ import os
5
+ from threading import Lock
6
+
7
+ from datasets import load_dataset
8
+ from tqdm import tqdm
9
+
10
+ from agentless.fl.Index import EmbeddingIndex
11
+ from agentless.util.preprocess_data import (
12
+ filter_non_source,
13
+ filter_out_test_files,
14
+ get_repo_structure,
15
+ )
16
+ from agentless.util.utils import load_json, load_jsonl, setup_logger
17
+
18
+
19
+ def load_bench_data(args):
20
+ if args.dataset_path:
21
+ if args.dataset_path.endswith(".jsonl"):
22
+ return load_jsonl(args.dataset_path)
23
+ if args.dataset_path.endswith(".json"):
24
+ with open(args.dataset_path, "r") as f:
25
+ return json.load(f)
26
+ raise ValueError("Unsupported dataset_path; use .json or .jsonl")
27
+ return load_dataset(args.dataset, split=args.dataset_split)
28
+
29
+
30
+ def retrieve_locs(bug, args, swe_bench_data, found_files, prev_o, write_lock=None):
31
+
32
+ found = False
33
+ for o in prev_o:
34
+ if o["instance_id"] == bug["instance_id"]:
35
+ found = True
36
+ break
37
+
38
+ if found:
39
+ logger.info(f"skipping {bug['instance_id']} since patch already generated")
40
+ return None
41
+
42
+ instance_id = bug["instance_id"]
43
+
44
+ if args.target_id is not None:
45
+ if args.target_id != instance_id:
46
+ return None
47
+
48
+ log_file = os.path.join(args.output_folder, "retrieval_logs", f"{instance_id}.log")
49
+ logger = setup_logger(log_file)
50
+ logger.info(f"Processing bug {instance_id}")
51
+
52
+ bench_data = [x for x in swe_bench_data if x["instance_id"] == instance_id][0]
53
+ problem_statement = bench_data["problem_statement"]
54
+ structure = get_repo_structure(
55
+ instance_id, bug["repo"], bug["base_commit"], "playground"
56
+ )
57
+
58
+ filter_non_source(structure)
59
+ filter_out_test_files(structure)
60
+
61
+ if args.filter_file:
62
+ kwargs = { # build retrieval kwargs
63
+ "given_files": [x for x in found_files if x["instance_id"] == instance_id][
64
+ 0
65
+ ]["found_files"],
66
+ "filter_top_n": args.filter_top_n,
67
+ }
68
+ else:
69
+ kwargs = {}
70
+
71
+ # main retrieval
72
+ retriever = EmbeddingIndex(
73
+ instance_id,
74
+ structure,
75
+ problem_statement,
76
+ persist_dir=args.persist_dir,
77
+ filter_type=args.filter_type,
78
+ index_type=args.index_type,
79
+ chunk_size=args.chunk_size,
80
+ chunk_overlap=args.chunk_overlap,
81
+ logger=logger,
82
+ **kwargs,
83
+ )
84
+
85
+ file_names, meta_infos, traj = retriever.retrieve(mock=args.mock)
86
+
87
+ if write_lock is not None:
88
+ write_lock.acquire()
89
+ with open(args.output_file, "a") as f:
90
+ f.write(
91
+ json.dumps(
92
+ {
93
+ "instance_id": instance_id,
94
+ "found_files": file_names,
95
+ "node_info": meta_infos,
96
+ "traj": traj,
97
+ }
98
+ )
99
+ + "\n"
100
+ )
101
+ if write_lock is not None:
102
+ write_lock.release()
103
+
104
+
105
+ def retrieve(args):
106
+ if args.filter_file:
107
+ found_files = load_jsonl(args.filter_file)
108
+ else:
109
+ found_files = []
110
+
111
+ swe_bench_data = load_bench_data(args)
112
+ prev_o = load_jsonl(args.output_file) if os.path.exists(args.output_file) else []
113
+
114
+ if args.num_threads == 1:
115
+ for bug in tqdm(swe_bench_data, colour="MAGENTA"):
116
+ retrieve_locs(
117
+ bug, args, swe_bench_data, found_files, prev_o, write_lock=None
118
+ )
119
+ else:
120
+ write_lock = Lock()
121
+ with concurrent.futures.ThreadPoolExecutor(
122
+ max_workers=args.num_threads
123
+ ) as executor:
124
+ futures = [
125
+ executor.submit(
126
+ retrieve_locs,
127
+ bug,
128
+ args,
129
+ swe_bench_data,
130
+ found_files,
131
+ prev_o,
132
+ write_lock,
133
+ )
134
+ for bug in swe_bench_data
135
+ ]
136
+ for _ in tqdm(
137
+ concurrent.futures.as_completed(futures),
138
+ total=len(swe_bench_data),
139
+ colour="MAGENTA",
140
+ ):
141
+ pass
142
+
143
+
144
+ def main():
145
+ parser = argparse.ArgumentParser()
146
+
147
+ parser.add_argument("--output_folder", type=str, required=True)
148
+ parser.add_argument("--output_file", type=str, default="retrieve_locs.jsonl")
149
+ parser.add_argument(
150
+ "--index_type", type=str, default="simple", choices=["simple", "complex"]
151
+ )
152
+ parser.add_argument(
153
+ "--filter_type", type=str, default="none", choices=["none", "given_files"]
154
+ )
155
+ parser.add_argument("--filter_top_n", type=int, default=None)
156
+ parser.add_argument("--filter_file", type=str, default="")
157
+ parser.add_argument("--chunk_size", type=int, default=1024)
158
+ parser.add_argument("--chunk_overlap", type=int, default=0)
159
+ parser.add_argument("--persist_dir", type=str)
160
+ parser.add_argument("--target_id", type=str)
161
+ parser.add_argument("--mock", action="store_true")
162
+ parser.add_argument(
163
+ "--num_threads",
164
+ type=int,
165
+ default=1,
166
+ help="Number of threads to use for creating API requests (WARNING, embedding token counts are only accurate when thread=1)",
167
+ )
168
+ parser.add_argument(
169
+ "--dataset",
170
+ type=str,
171
+ default="princeton-nlp/SWE-bench_Lite",
172
+ choices=["princeton-nlp/SWE-bench_Lite", "princeton-nlp/SWE-bench_Verified"],
173
+ )
174
+ parser.add_argument(
175
+ "--dataset_path",
176
+ type=str,
177
+ help="Local dataset file (JSON or JSONL) built by build_dataset.py.",
178
+ )
179
+ parser.add_argument(
180
+ "--dataset_split",
181
+ type=str,
182
+ default="test",
183
+ help="Split name when loading an HF dataset.",
184
+ )
185
+
186
+ args = parser.parse_args()
187
+
188
+ args.output_file = os.path.join(args.output_folder, args.output_file)
189
+ assert (
190
+ not args.filter_type == "given_files" or args.filter_file != ""
191
+ ), "Need to provide a filtering file"
192
+
193
+ os.makedirs(args.output_folder, exist_ok=True)
194
+ os.makedirs(os.path.join(args.output_folder, "retrieval_logs"), exist_ok=True)
195
+
196
+ # dump argument
197
+ with open(os.path.join(args.output_folder, "args.json"), "w") as f:
198
+ json.dump(vars(args), f, indent=4)
199
+
200
+ retrieve(args)
201
+
202
+
203
+ if __name__ == "__main__":
204
+ main()
Repos/HWE/agents/Agentless/agentless/repair/repair.py ADDED
@@ -0,0 +1,855 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import concurrent.futures
3
+ import json
4
+ import os
5
+ from difflib import unified_diff
6
+ from threading import Lock
7
+
8
+ from datasets import load_dataset
9
+ from tqdm import tqdm
10
+
11
+ from agentless.util.api_requests import num_tokens_from_messages
12
+ from agentless.util.model import make_model
13
+ from agentless.util.postprocess_data import (
14
+ check_code_differ_by_just_empty_lines,
15
+ check_syntax,
16
+ extract_python_blocks,
17
+ fake_git_repo,
18
+ lint_code,
19
+ parse_diff_edit_commands,
20
+ parse_edit_commands,
21
+ parse_str_replace_edit_commands,
22
+ split_edit_multifile_commands,
23
+ )
24
+ from agentless.util.preprocess_data import (
25
+ get_full_file_paths_and_classes_and_functions,
26
+ get_repo_structure,
27
+ line_wrap_content,
28
+ transfer_arb_locs_to_locs,
29
+ )
30
+ from agentless.util.utils import cleanup_logger, load_jsonl, setup_logger
31
+
32
+
33
+ def load_bench_data(args):
34
+ if args.dataset_path:
35
+ if args.dataset_path.endswith(".jsonl"):
36
+ return load_jsonl(args.dataset_path)
37
+ if args.dataset_path.endswith(".json"):
38
+ with open(args.dataset_path, "r") as f:
39
+ return json.load(f)
40
+ raise ValueError("Unsupported dataset_path; use .json or .jsonl")
41
+ return load_dataset(args.dataset, split=args.dataset_split)
42
+
43
+
44
+ repair_relevant_file_instruction = """
45
+ Below are some code segments, each from a relevant file in a Verilog/SystemVerilog hardware design/verification repository. One or more of these files may contain bugs (e.g., RTL logic issues, reset/clocking problems, parameterization mistakes, width mismatches, or testbench/constraint errors).
46
+ """
47
+
48
+ repair_prompt_combine_topn = """
49
+ We are currently solving the following issue within our Verilog/SystemVerilog repository. Here is the issue text:
50
+ --- BEGIN ISSUE ---
51
+ {problem_statement}
52
+ --- END ISSUE ---
53
+
54
+ {repair_relevant_file_instruction}
55
+ --- BEGIN FILE ---
56
+ ```systemverilog
57
+ {content}
58
+ --- END FILE ---
59
+
60
+ Please generate edit_file commands to fix the issue (e.g., adjust RTL modules/interfaces/packages, fix always_comb/always_ff logic, correct signal widths/types, parameters/localparams, assigns, generate blocks, or testbench assertions).
61
+
62
+ The edit_file command takes four arguments:
63
+
64
+ edit_file(filename: str, start: int, end: int, content: str) -> None:
65
+ Edit a file. It replaces lines start through end (inclusive) with the given text content in the open file.
66
+ Args:
67
+ filename: str: The full file name to edit.
68
+ start: int: The start line number. Must satisfy start >= 1.
69
+ end: int: The end line number. Must satisfy start <= end <= number of lines in the file.
70
+ content: str: The content to replace the lines with.
71
+
72
+ Please note that THE edit_file FUNCTION REQUIRES PROPER INDENTATION. If you would like to add the line ' $display(x);', you must fully write that out, with all those spaces before the code!
73
+ Wrap the edit_file command in ```python``` blocks, and include the full file path inside the block as the edit_file filename argument (do not put file paths outside the block).
74
+ """
75
+
76
+ repair_prompt_combine_topn_cot = """
77
+ We are currently solving the following issue within our Verilog/SystemVerilog repository. Here is the issue text:
78
+ --- BEGIN ISSUE ---
79
+ {problem_statement}
80
+ --- END ISSUE ---
81
+
82
+ {repair_relevant_file_instruction}
83
+ --- BEGIN FILE ---
84
+
85
+ {content}
86
+ --- END FILE ---
87
+
88
+ Please first localize the bug based on the issue statement (e.g., identify the faulty module/interface/package, signal, parameter, always block, assignment, or assertion), and then generate edit_file commands to fix the issue.
89
+
90
+ The edit_file command takes four arguments:
91
+
92
+ edit_file(filename: str, start: int, end: int, content: str) -> None:
93
+ Edit a file. It replaces lines start through end (inclusive) with the given text content in the open file.
94
+ Args:
95
+ filename: str: The full file name to edit.
96
+ start: int: The start line number. Must satisfy start >= 1.
97
+ end: int: The end line number. Must satisfy start <= end <= number of lines in the file.
98
+ content: str: The content to replace the lines with.
99
+
100
+ Please note that THE edit_file FUNCTION REQUIRES PROPER INDENTATION. If you would like to add the line ' $display(x);', you must fully write that out, with all those spaces before the code!
101
+ Wrap the edit_file command in ```python``` blocks, and include the full file path inside the block as the edit_file filename argument (do not put file paths outside the block).
102
+ """
103
+
104
+ repair_prompt_combine_topn_cot_diff = """
105
+ We are currently solving the following issue within our Verilog/SystemVerilog repository. Here is the issue text:
106
+ --- BEGIN ISSUE ---
107
+ {problem_statement}
108
+ --- END ISSUE ---
109
+
110
+ {repair_relevant_file_instruction}
111
+ --- BEGIN FILE ---
112
+
113
+ {content}
114
+ --- END FILE ---
115
+
116
+ Please first localize the bug based on the issue statement (e.g., identify the faulty module/interface/package, signal, parameter, always block, assignment, generate block, or assertion), and then generate SEARCH/REPLACE edits to fix the issue.
117
+
118
+ Every SEARCH/REPLACE edit must use this format:
119
+
120
+ The file path
121
+
122
+ The start of search block: <<<<<<< SEARCH
123
+
124
+ A contiguous chunk of lines to search for in the existing source code
125
+
126
+ The dividing line: =======
127
+
128
+ The lines to replace into the source code
129
+
130
+ The end of the replace block: >>>>>>> REPLACE
131
+
132
+ Here is an example:
133
+
134
+ ```python
135
+ ### rtl/top.sv
136
+ <<<<<<< SEARCH
137
+ module top(input logic clk, input logic rst_n);
138
+ =======
139
+ module top(input logic clk, input logic rst_n);
140
+ // Added reset synchronizer
141
+ >>>>>>> REPLACE
142
+ ```
143
+ Please note that the SEARCH/REPLACE edit REQUIRES PROPER INDENTATION. If you would like to add the line ' $display(x);', you must fully write that out, with all those spaces before the code!
144
+ Wrap EACH SEARCH/REPLACE edit in a ```python block, and include the file path as the first line INSIDE that block.
145
+ """
146
+
147
+ repair_prompt_combine_topn_cot_str_replace = """
148
+ We are currently solving the following issue within our Verilog/SystemVerilog repository. Here is the issue text:
149
+ --- BEGIN ISSUE ---
150
+ {problem_statement}
151
+ --- END ISSUE ---
152
+
153
+ {repair_relevant_file_instruction}
154
+ --- BEGIN FILE ---
155
+
156
+ {content}
157
+ --- END FILE ---
158
+
159
+ Please first localize the bug based on the issue statement, and then generate editing commands to fix the issue (e.g., update RTL modules/interfaces/packages, fix signal widths/types, reset/clock logic, parameters/localparams, combinational/sequential logic, assertions, or testbench drivers).
160
+ Each edit command must include the full file path in its `path` field, and do not put file paths outside the command.
161
+ """
162
+
163
+ def _post_process_multifile_repair(
164
+ raw_output: str,
165
+ file_contents: dict[str, str],
166
+ logger,
167
+ file_loc_intervals: dict[str, list],
168
+ diff_format=False,
169
+ str_replace_format=False,
170
+ ) -> tuple[list[str], list[str]]:
171
+ if not str_replace_format:
172
+ edit_multifile_commands = extract_python_blocks(raw_output)
173
+ else:
174
+ edit_multifile_commands = raw_output
175
+ edited_files = []
176
+ new_contents = []
177
+ try:
178
+ file_to_commands = split_edit_multifile_commands(
179
+ edit_multifile_commands,
180
+ diff_format=diff_format,
181
+ str_replace_format=str_replace_format,
182
+ )
183
+ except Exception as e:
184
+ logger.error(e)
185
+ return edited_files, new_contents
186
+
187
+ logger.info("=== file_to_commands: ===")
188
+ logger.info(json.dumps(file_to_commands, indent=2))
189
+
190
+ for edited_file_key in file_to_commands:
191
+ edited_file = ""
192
+ new_content = ""
193
+ try:
194
+ logger.info(f"=== edited_file: {edited_file_key} ===")
195
+ edit_commands = file_to_commands[edited_file_key]
196
+ logger.info("=== edit_commands: ===")
197
+ for c in edit_commands:
198
+ logger.info(c)
199
+ logger.info("\n" + "-" * 40)
200
+ edited_file = eval(edited_file_key) # convert '"file.py"' to 'file.py'
201
+ content = file_contents[edited_file]
202
+ if diff_format:
203
+ new_content = parse_diff_edit_commands(
204
+ edit_commands, content, file_loc_intervals[edited_file]
205
+ )
206
+ elif str_replace_format:
207
+ new_content = parse_str_replace_edit_commands(
208
+ edit_commands, content, file_loc_intervals[edited_file]
209
+ )
210
+ else:
211
+ new_content = parse_edit_commands(edit_commands, content)
212
+ except Exception as e:
213
+ logger.error(e)
214
+ edited_file = ""
215
+ new_content = ""
216
+
217
+ if edited_file == "" or new_content == "":
218
+ continue
219
+ edited_files.append(edited_file)
220
+ new_contents.append(new_content)
221
+ diff = list(
222
+ unified_diff(
223
+ content.split("\n"),
224
+ new_content.split("\n"),
225
+ fromfile=edited_file,
226
+ tofile=edited_file,
227
+ lineterm="",
228
+ )
229
+ )
230
+
231
+ logger.info(f"extracted patch:")
232
+ logger.info("\n".join(diff))
233
+ print("\n".join(diff))
234
+
235
+ return edited_files, new_contents
236
+
237
+
238
+ def construct_topn_file_context(
239
+ file_to_locs,
240
+ pred_files,
241
+ file_contents,
242
+ structure,
243
+ context_window: int,
244
+ loc_interval: bool = True,
245
+ fine_grain_loc_only: bool = False,
246
+ add_space: bool = False,
247
+ sticky_scroll: bool = False,
248
+ no_line_number: bool = True,
249
+ ):
250
+ """Concatenate provided locations to form a context.
251
+
252
+ loc: {"file_name_1": ["loc_str_1"], ...}
253
+ """
254
+ file_loc_intervals = dict()
255
+ topn_content = ""
256
+
257
+ for pred_file, locs in file_to_locs.items():
258
+ content = file_contents[pred_file]
259
+ line_locs, context_intervals = transfer_arb_locs_to_locs(
260
+ locs,
261
+ structure,
262
+ pred_file,
263
+ context_window,
264
+ loc_interval,
265
+ fine_grain_loc_only,
266
+ file_content=file_contents[pred_file] if pred_file in file_contents else "",
267
+ )
268
+
269
+ if len(line_locs) > 0:
270
+ # Note that if no location is predicted, we exclude this file.
271
+ file_loc_content = line_wrap_content(
272
+ content,
273
+ context_intervals,
274
+ add_space=add_space,
275
+ no_line_number=no_line_number,
276
+ sticky_scroll=sticky_scroll,
277
+ )
278
+ topn_content += f"### {pred_file}\n{file_loc_content}\n\n\n"
279
+ file_loc_intervals[pred_file] = context_intervals
280
+
281
+ return topn_content, file_loc_intervals
282
+
283
+
284
+ def process_loc(loc, args, swe_bench_data, prev_o, write_lock=None):
285
+ instance_id = loc["instance_id"]
286
+
287
+ if args.target_id is not None:
288
+ if args.target_id != instance_id:
289
+ return
290
+
291
+ log_file = os.path.join(args.output_folder, "repair_logs", f"{instance_id}.log")
292
+ logger = setup_logger(log_file)
293
+ found = False
294
+ for o in prev_o:
295
+ if o["instance_id"] == instance_id:
296
+ found = True
297
+ break
298
+
299
+ if found:
300
+ logger.info(f"skipping {instance_id} since patch already generated")
301
+ return None
302
+
303
+ logger.info(f"================ repairing {instance_id} ================")
304
+ if len(loc["found_files"]) == 0:
305
+ if write_lock is not None:
306
+ write_lock.acquire()
307
+ with open(args.output_file, "a") as f:
308
+ f.write(
309
+ json.dumps(
310
+ {
311
+ "instance_id": instance_id,
312
+ "raw_output": [""],
313
+ "try_count": [0],
314
+ "all_generations": [[]],
315
+ "traj": [],
316
+ "prev_content": [[]],
317
+ "file_names": [[]],
318
+ }
319
+ )
320
+ + "\n"
321
+ )
322
+ if write_lock is not None:
323
+ write_lock.release()
324
+ return
325
+
326
+ pred_files = loc["found_files"][: args.top_n]
327
+ bench_data = [x for x in swe_bench_data if x["instance_id"] == instance_id][0]
328
+ problem_statement = bench_data["problem_statement"]
329
+ structure = get_repo_structure(
330
+ instance_id, bench_data["repo"], bench_data["base_commit"], "playground"
331
+ )
332
+ files, _, _ = get_full_file_paths_and_classes_and_functions(structure)
333
+ raw_outputs, counts, all_generations, traj, prev_contents, file_names = (
334
+ [],
335
+ [],
336
+ [],
337
+ [],
338
+ [],
339
+ [],
340
+ )
341
+
342
+ raw_output = ""
343
+ topn_content = ""
344
+ # Construct file contents
345
+ file_contents = dict()
346
+ for i, pred_file in enumerate(pred_files):
347
+ content = None
348
+ for file_content in files:
349
+ if file_content[0] == pred_file:
350
+ content = "\n".join(file_content[1])
351
+ file_contents[pred_file] = content
352
+ break
353
+
354
+ assert content is not None, f"{pred_file} file not found"
355
+ # Construct top-n file context
356
+ file_to_edit_locs = dict()
357
+
358
+ if "found_edit_locs" in loc:
359
+ file_to_edit_locs = loc["found_edit_locs"]
360
+
361
+ topn_content, file_loc_intervals = construct_topn_file_context(
362
+ file_to_edit_locs,
363
+ pred_files,
364
+ file_contents,
365
+ structure,
366
+ context_window=args.context_window,
367
+ loc_interval=args.loc_interval,
368
+ fine_grain_loc_only=args.fine_grain_loc_only,
369
+ add_space=args.add_space,
370
+ no_line_number=args.diff_format or args.str_replace_format,
371
+ sticky_scroll=args.sticky_scroll,
372
+ )
373
+
374
+ if topn_content.strip() == "":
375
+ if write_lock is not None:
376
+ write_lock.acquire()
377
+ with open(args.output_file, "a") as f:
378
+ f.write(
379
+ json.dumps(
380
+ {
381
+ "instance_id": instance_id,
382
+ "raw_output": [""],
383
+ "try_count": [0],
384
+ "all_generations": [[]],
385
+ "traj": [],
386
+ "prev_content": [[]],
387
+ "file_names": [[]],
388
+ }
389
+ )
390
+ + "\n"
391
+ )
392
+ if write_lock is not None:
393
+ write_lock.release()
394
+ return
395
+
396
+ prompt_template = (
397
+ repair_prompt_combine_topn_cot_str_replace
398
+ if args.cot and args.str_replace_format
399
+ else repair_prompt_combine_topn_cot_diff
400
+ if args.cot and args.diff_format
401
+ else repair_prompt_combine_topn_cot
402
+ if args.cot
403
+ else repair_prompt_combine_topn
404
+ )
405
+ file_instruction = repair_relevant_file_instruction
406
+ message = prompt_template.format(
407
+ repair_relevant_file_instruction=file_instruction,
408
+ problem_statement=problem_statement,
409
+ content=topn_content.rstrip(),
410
+ ).strip()
411
+ logger.info(f"prompting with message:\n{message}")
412
+
413
+ all_generations, counts, traj, prev_contents, file_names = [], [], [], [], []
414
+ sample_responses = []
415
+ # get greedy sample
416
+ model = make_model(
417
+ model=args.model,
418
+ logger=logger,
419
+ backend=args.backend,
420
+ max_tokens=1024,
421
+ temperature=0,
422
+ batch_size=1,
423
+ )
424
+ if args.skip_greedy:
425
+ greedy_traj = {
426
+ "response": "",
427
+ "usage": {
428
+ "completion_tokens": 0,
429
+ "prompt_tokens": 0,
430
+ },
431
+ }
432
+ else:
433
+ if args.mock:
434
+ greedy_traj = {
435
+ "response": "",
436
+ "usage": {
437
+ "prompt_tokens": num_tokens_from_messages(message, args.model),
438
+ },
439
+ }
440
+ else:
441
+ if args.str_replace_format:
442
+ greedy_traj = model.codegen_w_tool(
443
+ message, num_samples=1, prompt_cache=args.max_samples > 1
444
+ )[0]
445
+ else:
446
+ greedy_traj = model.codegen(
447
+ message, num_samples=1, prompt_cache=args.max_samples > 1
448
+ )[0]
449
+
450
+ sample_responses.append(greedy_traj)
451
+ # get temperature samples
452
+ model = make_model(
453
+ model=args.model,
454
+ logger=logger,
455
+ backend=args.backend,
456
+ max_tokens=1024,
457
+ temperature=0.8,
458
+ batch_size=args.max_samples - 1, # minus the 1 greedy sample
459
+ )
460
+
461
+ if args.mock:
462
+ first_traj = {
463
+ "response": "",
464
+ "usage": {
465
+ "prompt_tokens": num_tokens_from_messages(message, args.model),
466
+ },
467
+ }
468
+ later_traj = {
469
+ "response": "",
470
+ "usage": {"prompt_tokens": 0},
471
+ }
472
+ if args.max_samples - 1:
473
+ sample_trajs = [first_traj] + [later_traj] * (args.max_samples - 2)
474
+ else:
475
+ sample_trajs = []
476
+ else:
477
+ if args.max_samples - 1:
478
+ # always use cached prompt if possible for later samples
479
+ if args.str_replace_format:
480
+ sample_trajs = model.codegen_w_tool(
481
+ message, num_samples=args.max_samples - 1, prompt_cache=True
482
+ )
483
+ else:
484
+ sample_trajs = model.codegen(
485
+ message, num_samples=args.max_samples - 1, prompt_cache=True
486
+ )
487
+ else:
488
+ sample_trajs = []
489
+
490
+ sample_responses.extend(sample_trajs)
491
+
492
+ count = 0
493
+ while count < args.max_samples:
494
+ print(f"trying the {count + 1}-th sample ...")
495
+ ret = sample_responses[count]
496
+ count += 1
497
+ traj.append({**ret, "prompt": message})
498
+
499
+ if args.mock:
500
+ continue
501
+
502
+ raw_output = ret["response"]
503
+ logger.info(f"raw output:\n{raw_output}")
504
+ all_generations.append(raw_output)
505
+ edited_files, new_contents = _post_process_multifile_repair(
506
+ raw_output,
507
+ file_contents,
508
+ logger,
509
+ file_loc_intervals,
510
+ diff_format=args.diff_format,
511
+ str_replace_format=args.str_replace_format,
512
+ )
513
+
514
+ if len(new_contents) == 0:
515
+ prev_contents.append("")
516
+ file_names.append("")
517
+ else:
518
+ prev_content = [file_contents[edited_file] for edited_file in edited_files]
519
+ prev_contents.append(prev_content)
520
+ file_names.append(edited_files)
521
+
522
+ counts.append(count)
523
+ raw_outputs.append(raw_output)
524
+
525
+ if write_lock is not None:
526
+ write_lock.acquire()
527
+ with open(args.output_file, "a") as f:
528
+ f.write(
529
+ json.dumps(
530
+ {
531
+ "instance_id": instance_id,
532
+ "raw_output": raw_outputs,
533
+ "all_generations": [all_generations],
534
+ "try_count": counts,
535
+ "traj": traj,
536
+ "prev_content": [prev_contents],
537
+ "file_names": [file_names],
538
+ }
539
+ )
540
+ + "\n"
541
+ )
542
+ if write_lock is not None:
543
+ write_lock.release()
544
+
545
+
546
+ def repair(args):
547
+ with open(f"{args.output_folder}/args.json", "w") as f:
548
+ json.dump(vars(args), f, indent=4)
549
+
550
+ swe_bench_data = load_bench_data(args)
551
+ locs = load_jsonl(args.loc_file)
552
+ prev_o = load_jsonl(args.output_file) if os.path.exists(args.output_file) else []
553
+
554
+ with open(f"{args.output_folder}/used_locs.jsonl", "w") as f:
555
+ for loc in locs:
556
+ f.write(json.dumps(loc) + "\n")
557
+
558
+ if args.num_threads == 1:
559
+ for loc in tqdm(locs, total=len(locs), colour="MAGENTA"):
560
+ process_loc(loc, args, swe_bench_data, prev_o)
561
+ else:
562
+ write_lock = Lock()
563
+ with concurrent.futures.ThreadPoolExecutor(
564
+ max_workers=args.num_threads
565
+ ) as executor:
566
+ futures = {
567
+ executor.submit(
568
+ process_loc, loc, args, swe_bench_data, prev_o, write_lock
569
+ ): loc
570
+ for loc in locs
571
+ }
572
+ for future in tqdm(
573
+ concurrent.futures.as_completed(futures),
574
+ total=len(locs),
575
+ colour="MAGENTA",
576
+ ):
577
+ future.result()
578
+
579
+
580
+ def post_process_raw_output(
581
+ raw_output_text, file_contents, logger, file_loc_intervals, args
582
+ ):
583
+ git_diffs = ""
584
+ raw_git_diffs = ""
585
+ edited_files, new_contents, contents = [], [], []
586
+ try:
587
+ edited_files, new_contents = _post_process_multifile_repair(
588
+ raw_output_text,
589
+ file_contents,
590
+ logger,
591
+ file_loc_intervals,
592
+ diff_format=args.diff_format,
593
+ str_replace_format=args.str_replace_format,
594
+ )
595
+
596
+ contents = [file_contents[edited_file] for edited_file in edited_files]
597
+
598
+ git_diff = fake_git_repo("playground", edited_files, contents, new_contents)
599
+
600
+ raw_git_diffs += "\n" + git_diff.replace("\n", "")
601
+
602
+ syntax_success = check_syntax(new_contents)
603
+
604
+ differ_by_empty_lines = check_code_differ_by_just_empty_lines(
605
+ new_contents, contents
606
+ )
607
+
608
+ logger.info(f"{differ_by_empty_lines = }")
609
+ if syntax_success and not differ_by_empty_lines:
610
+ git_diffs = raw_git_diffs
611
+ else:
612
+ git_diffs = "" # no need to evaluate
613
+ except Exception as e:
614
+ print(raw_output_text)
615
+ print(e)
616
+
617
+ return git_diffs, raw_git_diffs, contents, edited_files, new_contents
618
+
619
+
620
+ def post_process_repair(args):
621
+ """
622
+ apply some diff formatting.
623
+ """
624
+ raw_outputs = load_jsonl(args.raw_output_file)
625
+ locs = load_jsonl(args.loc_file)
626
+
627
+ for raw_output in raw_outputs:
628
+ instance_id = raw_output["instance_id"]
629
+ log_file = os.path.join(args.output_folder, "repair_logs", f"{instance_id}.log")
630
+ logger = setup_logger(log_file)
631
+
632
+ if raw_output["raw_output"] == "":
633
+ with open(args.output_file, "a") as f:
634
+ f.write(
635
+ json.dumps(
636
+ {
637
+ "model_name_or_path": "agentless",
638
+ "instance_id": instance_id,
639
+ "model_patch": "",
640
+ }
641
+ )
642
+ + "\n"
643
+ )
644
+ continue
645
+
646
+ if args.select_id == -1:
647
+ # Use the last generation
648
+ assert False, "not implemented for now"
649
+ else:
650
+ # Use the indexed generation
651
+ generation_idx = args.select_id
652
+ try:
653
+ raw_output_text = raw_output["all_generations"][0][generation_idx]
654
+ original_file_content = raw_output["prev_content"][0][generation_idx]
655
+ pred_file = raw_output["file_names"][0][generation_idx]
656
+
657
+ pred_files = [loc for loc in locs if loc["instance_id"] == instance_id][
658
+ 0
659
+ ]["found_files"][: args.top_n]
660
+
661
+ git_diffs = ""
662
+ raw_git_diffs = ""
663
+ if isinstance(raw_output["raw_output"], str):
664
+ # for backward compatibility
665
+ raw_output["raw_output"] = [raw_output["raw_output"]]
666
+
667
+ if isinstance(original_file_content, str):
668
+ original_file_content = [original_file_content]
669
+ pred_file = [pred_file]
670
+
671
+ file_contents = {
672
+ file_name: o_file_content
673
+ for file_name, o_file_content in zip(
674
+ pred_file, original_file_content
675
+ )
676
+ }
677
+
678
+ file_loc_intervals = dict()
679
+
680
+ loc = [loc for loc in locs if loc["instance_id"] == instance_id][0]
681
+
682
+ for i, tmp_pred_file in enumerate(pred_files):
683
+ if tmp_pred_file not in pred_file:
684
+ continue
685
+ if (
686
+ "found_edit_locs" in loc
687
+ and tmp_pred_file in loc["found_edit_locs"]
688
+ ):
689
+ line_locs, context_intervals = transfer_arb_locs_to_locs(
690
+ loc["found_edit_locs"][tmp_pred_file],
691
+ None,
692
+ loc["found_files"][i],
693
+ args.context_window,
694
+ args.loc_interval,
695
+ args.fine_grain_loc_only,
696
+ file_content=file_contents[tmp_pred_file]
697
+ if tmp_pred_file in file_contents
698
+ else "",
699
+ )
700
+ else:
701
+ line_locs, context_intervals = [], [] # default values.
702
+
703
+ file_loc_intervals[tmp_pred_file] = context_intervals
704
+ except Exception as e:
705
+ logger.info(e)
706
+ print(e)
707
+ raw_output_text = ""
708
+
709
+ if raw_output_text:
710
+ (
711
+ git_diffs,
712
+ raw_git_diffs,
713
+ content,
714
+ edited_files,
715
+ new_contents,
716
+ ) = post_process_raw_output(
717
+ raw_output_text, file_contents, logger, file_loc_intervals, args
718
+ )
719
+ else:
720
+ git_diffs = ""
721
+ raw_git_diffs = ""
722
+ content = []
723
+ edited_files = []
724
+ new_contents = []
725
+
726
+ with open(args.output_file, "a") as f:
727
+ f.write(
728
+ json.dumps(
729
+ {
730
+ "model_name_or_path": "agentless",
731
+ "instance_id": instance_id,
732
+ "model_patch": git_diffs.lstrip(),
733
+ "raw_model_patch": raw_git_diffs.lstrip(),
734
+ "original_file_content": content,
735
+ "edited_files": edited_files,
736
+ "new_file_content": new_contents,
737
+ }
738
+ )
739
+ + "\n"
740
+ )
741
+ cleanup_logger(logger)
742
+
743
+
744
+ def main():
745
+ parser = argparse.ArgumentParser()
746
+ parser.add_argument("--loc_file", type=str, required=True)
747
+ parser.add_argument("--top_n", type=int, default=1)
748
+ parser.add_argument("--loc_interval", action="store_true")
749
+ parser.add_argument("--context_window", type=int, default=10)
750
+ parser.add_argument("--gen_and_process", action="store_true")
751
+ parser.add_argument("--max_samples", type=int, default=20, help="Sampling budget.")
752
+ parser.add_argument(
753
+ "--select_id",
754
+ type=int,
755
+ default=-1,
756
+ help="Index the selected samples during post-processing.",
757
+ )
758
+ parser.add_argument(
759
+ "--model",
760
+ type=str,
761
+ default=os.getenv("AGENTLESS_MODEL", "gpt-5.2"),
762
+ help="Model name (defaults to $AGENTLESS_MODEL).",
763
+ )
764
+ parser.add_argument(
765
+ "--backend",
766
+ type=str,
767
+ default="openai",
768
+ choices=["openai", "deepseek", "anthropic"],
769
+ )
770
+ parser.add_argument("--output_folder", type=str, required=True)
771
+ parser.add_argument("--post_process", action="store_true")
772
+ parser.add_argument("--add_space", action="store_true")
773
+ parser.add_argument("--cot", action="store_true")
774
+ parser.add_argument("--fine_grain_loc_only", action="store_true")
775
+ parser.add_argument("--diff_format", action="store_true")
776
+ parser.add_argument("--str_replace_format", action="store_true")
777
+ parser.add_argument("--skip_greedy", action="store_true")
778
+ parser.add_argument("--sticky_scroll", action="store_true")
779
+ parser.add_argument(
780
+ "--num_threads",
781
+ type=int,
782
+ default=1,
783
+ help="Number of threads to use for creating API requests",
784
+ )
785
+ parser.add_argument("--target_id", type=str)
786
+ parser.add_argument(
787
+ "--mock", action="store_true", help="Mock run to compute prompt tokens."
788
+ )
789
+ parser.add_argument(
790
+ "--dataset",
791
+ type=str,
792
+ default="princeton-nlp/SWE-bench_Lite",
793
+ choices=["princeton-nlp/SWE-bench_Lite", "princeton-nlp/SWE-bench_Verified"],
794
+ )
795
+ parser.add_argument(
796
+ "--dataset_path",
797
+ type=str,
798
+ help="Local dataset file (JSON or JSONL) built by build_dataset.py.",
799
+ )
800
+ parser.add_argument(
801
+ "--dataset_split",
802
+ type=str,
803
+ default="test",
804
+ help="Split name when loading an HF dataset.",
805
+ )
806
+
807
+ args = parser.parse_args()
808
+
809
+ assert (not "deepseek" in args.model) or (
810
+ args.backend == "deepseek"
811
+ ), "Must specify `--backend deepseek` if using a DeepSeek model"
812
+
813
+ # diff_format and str_replace_format cannot be both True
814
+ assert not (
815
+ args.diff_format and args.str_replace_format
816
+ ), "Cannot use both diff_format and str_replace_format"
817
+
818
+ # str_replace_format only supported with anthropic backend
819
+ assert not (
820
+ args.str_replace_format and args.backend != "anthropic"
821
+ ), "str_replace_format only supported with anthropic backend"
822
+
823
+ if not os.path.exists(args.output_folder):
824
+ os.makedirs(args.output_folder)
825
+ if not os.path.exists(os.path.join(args.output_folder, "repair_logs")):
826
+ os.makedirs(os.path.join(args.output_folder, "repair_logs"))
827
+
828
+ args.output_file = os.path.join(args.output_folder, "output.jsonl")
829
+
830
+ if args.post_process:
831
+ args.raw_output_file = args.output_file
832
+ if args.select_id == -1:
833
+ args.output_file = args.raw_output_file.replace(
834
+ ".jsonl", "_processed.jsonl"
835
+ )
836
+ else:
837
+ args.output_file = args.raw_output_file.replace(
838
+ ".jsonl", f"_{args.select_id}_processed.jsonl"
839
+ )
840
+ post_process_repair(args)
841
+ elif args.gen_and_process:
842
+ repair(args)
843
+ args.raw_output_file = args.output_file
844
+ for i in range(args.max_samples):
845
+ args.output_file = args.raw_output_file.replace(
846
+ ".jsonl", f"_{i}_processed.jsonl"
847
+ )
848
+ args.select_id = i
849
+ post_process_repair(args)
850
+ else:
851
+ repair(args)
852
+
853
+
854
+ if __name__ == "__main__":
855
+ main()
Repos/HWE/agents/Agentless/agentless/repair/rerank.py ADDED
@@ -0,0 +1,343 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import json
3
+ import os
4
+ from collections import Counter
5
+ from pathlib import Path
6
+
7
+ from agentless.util.postprocess_data import normalize_patch
8
+ from agentless.util.utils import load_json, load_jsonl
9
+
10
+ execution_results = dict()
11
+
12
+
13
+ def _load_results(args):
14
+ global execution_results
15
+
16
+ roots = [Path(folder) for folder in args.patch_folder.split(",")]
17
+
18
+ intervals = [(0, int(args.num_samples / len(roots)) - 1) for _ in range(len(roots))]
19
+
20
+ interval = intervals[0]
21
+ for i in range(interval[0], interval[1] + 1):
22
+ for _, root in enumerate(roots):
23
+ patches = load_jsonl(root / f"output_{i}_normalized.jsonl")
24
+ print(
25
+ f"Loaded {len(patches)} patches from {root / f'output_{i}_normalized.jsonl'}"
26
+ )
27
+ if args.regression:
28
+ regression_test_results = load_jsonl(
29
+ root / f"output_{i}_regression_test_results.jsonl"
30
+ )
31
+ if args.reproduction:
32
+ reproduction_test_results = load_jsonl(
33
+ root / f"output_{i}_reproduction_test_results.jsonl"
34
+ )
35
+
36
+ for patch in patches[:]:
37
+ if args.regression:
38
+ regression_test_result = [
39
+ x
40
+ for x in regression_test_results
41
+ if x["instance_id"] == patch["instance_id"]
42
+ ][0].get("regression", [0] * 10000)
43
+ regression_test_result = len(regression_test_result)
44
+ else:
45
+ regression_test_result = 0
46
+
47
+ if args.reproduction:
48
+ if (
49
+ len(
50
+ [
51
+ x
52
+ for x in reproduction_test_results
53
+ if x["instance_id"] == patch["instance_id"]
54
+ ]
55
+ )
56
+ == 1
57
+ ):
58
+ reproduction_test_result = [
59
+ x
60
+ for x in reproduction_test_results
61
+ if x["instance_id"] == patch["instance_id"]
62
+ ][0].get("reproduction", False)
63
+ else:
64
+ reproduction_test_result = False
65
+ else:
66
+ reproduction_test_result = True
67
+
68
+ execution_results.setdefault(patch["instance_id"], []).append(
69
+ {
70
+ "normalized_patch": patch["normalized_patch"].strip(),
71
+ "patch": patch["model_patch"],
72
+ "regression_test_result": regression_test_result,
73
+ "reproduction_test_result": reproduction_test_result,
74
+ }
75
+ )
76
+
77
+
78
+ def get_sample(instance_id, sample_id) -> tuple[str, bool]:
79
+ """Returns the diff and pass status."""
80
+ return execution_results[instance_id][sample_id]
81
+
82
+
83
+ def get_all_patches(instance_id, num_samples, deduplicate) -> list[str]:
84
+ """Returns all unique patches."""
85
+ patches = [execution_results[instance_id][i]["patch"] for i in range(num_samples)]
86
+ if deduplicate:
87
+ patch_keys = [
88
+ execution_results[instance_id][i]["normalized_patch"]
89
+ for i in range(num_samples)
90
+ ]
91
+ else:
92
+ patch_keys = [
93
+ execution_results[instance_id][i]["patch"] for i in range(num_samples)
94
+ ]
95
+ unique_patches = set()
96
+ patch_ids = []
97
+ for i in range(num_samples):
98
+ patch_key = patch_keys[i].strip()
99
+ if patch_key and patch_key not in unique_patches:
100
+ unique_patches.add(patch_key)
101
+ patch_ids.append(i)
102
+ return [(id, patches[id]) for id in patch_ids]
103
+
104
+
105
+ def get_all_patches_num(instance_id, num_samples, deduplicate) -> list[str]:
106
+ """Returns all unique patches with number."""
107
+ # print(f"{len(execution_results)}")
108
+ patches = [execution_results[instance_id][i]["patch"] for i in range(num_samples)]
109
+ if deduplicate:
110
+ patch_keys = [
111
+ execution_results[instance_id][i]["normalized_patch"]
112
+ for i in range(num_samples)
113
+ ]
114
+ else:
115
+ patch_keys = [
116
+ execution_results[instance_id][i]["patch"] for i in range(num_samples)
117
+ ]
118
+ unique_patches = {}
119
+ total_patch_num = {}
120
+ patch_ids = []
121
+ for i in range(num_samples):
122
+ if patch_keys[i] and patch_keys[i] not in unique_patches:
123
+ unique_patches[patch_keys[i]] = i
124
+ patch_ids.append(i)
125
+ total_patch_num[i] = 0
126
+ if patch_keys[i]:
127
+ total_patch_num[unique_patches[patch_keys[i]]] += 1
128
+
129
+ return [(id, patches[id], total_patch_num[id]) for id in patch_ids]
130
+
131
+
132
+ class SetEncoder(json.JSONEncoder):
133
+ def default(self, obj):
134
+ if isinstance(obj, set):
135
+ return list(obj)
136
+ return json.JSONEncoder.default(self, obj)
137
+
138
+
139
+ def modified_length(normalized_patch):
140
+ changed_length = 0
141
+
142
+ for line in normalized_patch.splitlines():
143
+ if len(line) > 3 and (line.startswith("---") or line.startswith("+++")):
144
+ continue
145
+
146
+ if line.startswith("-"):
147
+ changed_length += 1
148
+ if line.startswith("+"):
149
+ changed_length += 1
150
+
151
+ assert changed_length != 0
152
+
153
+ return changed_length
154
+
155
+
156
+ def majority_voting(args):
157
+
158
+ with open(args.output_file, "w") as f:
159
+
160
+ for instance_id in execution_results:
161
+ if len(execution_results[instance_id]) < args.num_samples:
162
+ print(
163
+ f"There were only {len(execution_results[instance_id])} patches for {instance_id} instead of the full {args.num_samples}"
164
+ )
165
+
166
+ patch_keys = [
167
+ execution_results[instance_id][i]["normalized_patch"]
168
+ for i in range(len(execution_results[instance_id]))
169
+ ]
170
+ regression_tests = [
171
+ execution_results[instance_id][i]["regression_test_result"]
172
+ for i in range(len(execution_results[instance_id]))
173
+ ]
174
+
175
+ min_tests = min(regression_tests)
176
+ regression_tests = [
177
+ True if x == min_tests else False for x in regression_tests
178
+ ]
179
+
180
+ reproduction_tests = [
181
+ execution_results[instance_id][i]["reproduction_test_result"]
182
+ for i in range(len(execution_results[instance_id]))
183
+ ]
184
+ raw_patches = [
185
+ execution_results[instance_id][i]["patch"]
186
+ for i in range(len(execution_results[instance_id]))
187
+ ]
188
+
189
+ if args.regression and not args.reproduction:
190
+ patch_ids = [
191
+ i
192
+ for i in range(len(execution_results[instance_id]))
193
+ if patch_keys[i].strip() and regression_tests[i]
194
+ ]
195
+ elif args.reproduction:
196
+ patch_ids = [
197
+ i
198
+ for i in range(len(execution_results[instance_id]))
199
+ if patch_keys[i].strip()
200
+ and regression_tests[i]
201
+ and reproduction_tests[i]
202
+ ]
203
+ if len(patch_ids) == 0:
204
+ # reset to just using the all regression passing patches
205
+ patch_ids = [
206
+ i
207
+ for i in range(len(execution_results[instance_id]))
208
+ if patch_keys[i].strip() and regression_tests[i]
209
+ ]
210
+ else:
211
+ patch_ids = [
212
+ i
213
+ for i in range(len(execution_results[instance_id]))
214
+ if patch_keys[i].strip()
215
+ ]
216
+
217
+ if not patch_ids:
218
+ # just vote on all patches
219
+ if not all([x.strip() == "" for x in raw_patches]) and not all(
220
+ [x.strip() == "" for x in patch_keys]
221
+ ):
222
+ vote = Counter()
223
+ first_appear_idx = dict()
224
+ valid_indices = []
225
+ for i in range(len(execution_results[instance_id])):
226
+ sample = get_sample(instance_id, i)
227
+ patch_key = sample["normalized_patch"]
228
+ if patch_key != "":
229
+ valid_indices.append(i)
230
+ vote[patch_key] += 1
231
+ if patch_key not in first_appear_idx:
232
+ first_appear_idx[patch_key] = i
233
+ maj_selected_id = max(
234
+ valid_indices,
235
+ key=lambda i: (
236
+ vote[patch_keys[i]],
237
+ -first_appear_idx[patch_keys[i]],
238
+ ),
239
+ )
240
+ patch = get_sample(instance_id, maj_selected_id)["patch"]
241
+ result = {
242
+ "model_name_or_path": "agentless",
243
+ "instance_id": instance_id,
244
+ "model_patch": patch,
245
+ }
246
+ else:
247
+ print(f"No raw patches valid for {instance_id}")
248
+ result = {
249
+ "model_name_or_path": "agentless",
250
+ "instance_id": instance_id,
251
+ "model_patch": "",
252
+ }
253
+ f.write(json.dumps(result) + "\n")
254
+ continue
255
+
256
+ vote = Counter()
257
+ first_appear_idx = dict()
258
+ changed_length_idx = dict()
259
+ for i in patch_ids:
260
+ sample = get_sample(instance_id, i)
261
+ patch_key, patch = sample["normalized_patch"], sample["patch"]
262
+ vote[patch_key] += 1
263
+ if patch_key not in first_appear_idx:
264
+ first_appear_idx[patch_key] = i
265
+ changed_length_idx[patch_key] = modified_length(patch_key)
266
+
267
+ maj_selected_id = max(
268
+ patch_ids,
269
+ key=lambda i: (vote[patch_keys[i]], -first_appear_idx[patch_keys[i]]),
270
+ )
271
+
272
+ if args.target is not None and instance_id == args.target:
273
+ for patch in vote:
274
+ print(
275
+ "=" * 20,
276
+ vote[patch],
277
+ "=" * 20,
278
+ )
279
+ print(patch)
280
+ print("=" * 50)
281
+
282
+ sample = get_sample(instance_id, maj_selected_id)
283
+ result = {
284
+ "model_name_or_path": "agentless",
285
+ "instance_id": instance_id,
286
+ "model_patch": sample["patch"],
287
+ }
288
+
289
+ f.write(json.dumps(result) + "\n")
290
+
291
+
292
+ def normalize_patches(args):
293
+ # separate the patch folders
294
+ output_folders = [Path(folder) for folder in args.patch_folder.split(",")]
295
+ num_folders = len(output_folders)
296
+ selected_ids = list(range(int(args.num_samples / num_folders)))
297
+
298
+ for output_folder in output_folders:
299
+ for i in selected_ids:
300
+ if os.path.exists(output_folder / f"output_{i}_normalized.jsonl"):
301
+ # skip
302
+ continue
303
+ patches = load_jsonl(output_folder / f"output_{i}_processed.jsonl")
304
+ for d in patches:
305
+ instance_id = d["instance_id"]
306
+ patch = d["model_patch"]
307
+ original_file_content = d["original_file_content"]
308
+ new_file_content = d["new_file_content"]
309
+ edited_files = d["edited_files"]
310
+ normalized_patch = normalize_patch(
311
+ instance_id,
312
+ patch,
313
+ original_file_content,
314
+ new_file_content,
315
+ edited_files,
316
+ )
317
+ d["normalized_patch"] = normalized_patch
318
+ with open(output_folder / f"output_{i}_normalized.jsonl", "w") as f:
319
+ for d in patches:
320
+ f.write(json.dumps(d) + "\n")
321
+
322
+
323
+ def main():
324
+ parser = argparse.ArgumentParser()
325
+ parser.add_argument("--patch_folder", type=str)
326
+ parser.add_argument("--target", type=str, default=None)
327
+ parser.add_argument("--num_samples", type=int, default=11)
328
+ parser.add_argument("--deduplicate", action="store_true")
329
+ parser.add_argument("--regression", action="store_true")
330
+ parser.add_argument("--reproduction", action="store_true")
331
+ parser.add_argument("--output_file", type=str, default="all_preds.jsonl")
332
+ args = parser.parse_args()
333
+
334
+ # first normalize
335
+ normalize_patches(args)
336
+ # then load results
337
+ _load_results(args)
338
+ # then rerank
339
+ majority_voting(args)
340
+
341
+
342
+ if __name__ == "__main__":
343
+ main()
Repos/HWE/agents/Agentless/agentless/test/generate_reproduction_tests.py ADDED
@@ -0,0 +1,554 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import ast
3
+ import concurrent.futures
4
+ import json
5
+ import os
6
+ import re
7
+ from collections import Counter
8
+ from threading import Lock
9
+
10
+ from datasets import load_dataset
11
+ from tqdm import tqdm
12
+
13
+ from agentless.util.api_requests import num_tokens_from_messages
14
+ from agentless.util.model import make_model
15
+ from agentless.util.postprocess_data import remove_comments_and_docstrings
16
+ from agentless.util.utils import load_jsonl, setup_logger
17
+
18
+ generate_tests_prompt_template = """
19
+ We are currently solving the following issue within our repository. Here is the issue text:
20
+ --- BEGIN ISSUE ---
21
+ {problem_statement}
22
+ --- END ISSUE ---
23
+
24
+ Please generate a complete test that can be used to reproduce the issue.
25
+
26
+ The complete test should contain the following:
27
+ 1. Necessary imports
28
+ 2. Code to reproduce the issue described in the issue text
29
+ 3. Print "Issue reproduced" if the outcome indicates that the issue is reproduced
30
+ 4. Print "Issue resolved" if the outcome indicates that the issue has been successfully resolved
31
+ 5. Print "Other issues" if the outcome indicates there are other issues with the source code
32
+
33
+ Here is an example:
34
+
35
+ ```python
36
+ from sqlfluff import lint
37
+
38
+ def test__rules__std_L060_raised() -> None:
39
+ try:
40
+ sql = "SELECT IFNULL(NULL, 100),
41
+ NVL(NULL,100);"
42
+ result = lint(sql, rules=["L060"])
43
+ assert len(result) == 2
44
+ except:
45
+ print("Other issues")
46
+ return
47
+
48
+ try:
49
+ assert result[0]["description"] == "Use 'COALESCE' instead of 'IFNULL'."
50
+ assert result[1]["description"] == "Use 'COALESCE' instead of 'NVL'."
51
+ print("Issue resolved")
52
+ except AssertionError:
53
+ print("Issue reproduced")
54
+ return
55
+
56
+ return
57
+
58
+ test__rules__std_L060_raised()
59
+ ```
60
+
61
+ Please ensure the generated test reflects the issue described in the provided issue text.
62
+ The generated test should be able to be used to both reproduce the issue as well as to verify the issue has been fixed.
63
+ Wrap the complete test in ```python...```.
64
+ """
65
+
66
+
67
+ def create_patch_from_code(python_code: str) -> str:
68
+ patch_header = """diff --git a/reproduce_bug.py b/reproduce_bug.py
69
+ new file mode 100644
70
+ index 0000000..e69de29
71
+ """
72
+ patch_body = []
73
+ patch_body.append("--- /dev/null")
74
+ patch_body.append("+++ b/reproduce_bug.py")
75
+
76
+ code_lines = python_code.split("\n")
77
+ patch_body.append(f"@@ -0,0 +1,{len(code_lines)} @@")
78
+
79
+ for line in code_lines:
80
+ patch_body.append(f"+{line}")
81
+
82
+ return patch_header + "\n".join(patch_body) + "\n"
83
+
84
+
85
+ def extract_first_code_block(text):
86
+ pattern = re.compile(r"```python(.*?)```", re.DOTALL)
87
+
88
+ match = pattern.search(text)
89
+
90
+ if match:
91
+ return match.group(1).strip()
92
+
93
+ return None
94
+
95
+
96
+ def gen_test(instance_id, args, swe_bench_data, prev_o, write_lock=None):
97
+
98
+ if args.target_id is not None:
99
+ if args.target_id != instance_id:
100
+ return
101
+
102
+ log_file = os.path.join(
103
+ args.output_folder, "generating_test_logs", f"{instance_id}.log"
104
+ )
105
+ logger = setup_logger(log_file)
106
+ found = False
107
+ for o in prev_o:
108
+ if o["instance_id"] == instance_id:
109
+ found = True
110
+ break
111
+
112
+ if found:
113
+ logger.info(f"skipping {instance_id} since patch already generated")
114
+ return None
115
+
116
+ logger.info(f"================ generating test for {instance_id} ================")
117
+
118
+ bench_data = [x for x in swe_bench_data if x["instance_id"] == instance_id][0]
119
+ problem_statement = bench_data["problem_statement"]
120
+
121
+ raw_outputs, counts, all_generations, traj = (
122
+ [],
123
+ [],
124
+ [],
125
+ [],
126
+ )
127
+
128
+ raw_output = ""
129
+
130
+ prompt_template = generate_tests_prompt_template
131
+ message = prompt_template.format(
132
+ problem_statement=problem_statement,
133
+ ).strip()
134
+
135
+ logger.info(f"prompting with message:\n{message}")
136
+
137
+ all_generations, counts, traj = [], [], []
138
+ sample_responses = []
139
+
140
+ # get greedy sample
141
+ model = make_model(
142
+ model=args.model,
143
+ logger=logger,
144
+ backend=args.backend,
145
+ max_tokens=1024,
146
+ temperature=0,
147
+ batch_size=1,
148
+ )
149
+ if args.skip_greedy:
150
+ greedy_traj = {
151
+ "response": "",
152
+ "usage": {
153
+ "completion_tokens": 0,
154
+ "prompt_tokens": 0,
155
+ },
156
+ }
157
+ else:
158
+ if args.mock:
159
+ greedy_traj = {
160
+ "response": "",
161
+ "usage": {
162
+ "prompt_tokens": num_tokens_from_messages(message, args.model),
163
+ },
164
+ }
165
+ else:
166
+ greedy_traj = model.codegen(
167
+ message, num_samples=1, prompt_cache=args.max_samples > 1
168
+ )[0]
169
+
170
+ sample_responses.append(greedy_traj)
171
+ # get temperature samples
172
+ model = make_model(
173
+ model=args.model,
174
+ logger=logger,
175
+ backend=args.backend,
176
+ max_tokens=1024,
177
+ temperature=0.8,
178
+ batch_size=args.max_samples - 1, # minus the 1 greedy sample
179
+ )
180
+
181
+ if args.mock:
182
+ first_traj = {
183
+ "response": "",
184
+ "usage": {
185
+ "prompt_tokens": num_tokens_from_messages(message, args.model),
186
+ },
187
+ }
188
+ later_traj = {
189
+ "response": "",
190
+ "usage": {"prompt_tokens": 0},
191
+ }
192
+ if args.max_samples - 1:
193
+ sample_trajs = [first_traj] + [later_traj] * (args.max_samples - 2)
194
+ else:
195
+ sample_trajs = []
196
+ else:
197
+ if args.max_samples - 1:
198
+ # always use cached prompt if possible for later samples
199
+ sample_trajs = model.codegen(
200
+ message, num_samples=args.max_samples - 1, prompt_cache=True
201
+ )
202
+ else:
203
+ sample_trajs = []
204
+
205
+ sample_responses.extend(sample_trajs)
206
+
207
+ count = 0
208
+ while count < args.max_samples:
209
+ print(f"trying the {count + 1}-th sample ...")
210
+ ret = sample_responses[count]
211
+ count += 1
212
+ traj.append({**ret, "prompt": message})
213
+
214
+ if args.mock:
215
+ continue
216
+
217
+ raw_output = ret["response"]
218
+ logger.info(f"raw output:\n{raw_output}")
219
+ print((f"raw output:\n{raw_output}"))
220
+ all_generations.append(raw_output)
221
+
222
+ counts.append(count)
223
+ raw_outputs.append(raw_output)
224
+
225
+ if write_lock is not None:
226
+ write_lock.acquire()
227
+ with open(args.output_file, "a") as f:
228
+ f.write(
229
+ json.dumps(
230
+ {
231
+ "instance_id": instance_id,
232
+ "raw_output": raw_outputs,
233
+ "all_generations": [all_generations],
234
+ "try_count": counts,
235
+ "traj": traj,
236
+ "prev_content": [
237
+ [""]
238
+ ], # To make the tests compatible with the repair setup
239
+ "file_names": [["reproduce_bug.py"]],
240
+ }
241
+ )
242
+ + "\n"
243
+ )
244
+ if write_lock is not None:
245
+ write_lock.release()
246
+
247
+
248
+ def generate_tests(args):
249
+ with open(f"{args.output_folder}/args.json", "w") as f:
250
+ json.dump(vars(args), f, indent=4)
251
+
252
+ swe_bench_data = load_dataset(args.dataset, split="test")
253
+ instances = swe_bench_data["instance_id"]
254
+ prev_o = load_jsonl(args.output_file) if os.path.exists(args.output_file) else []
255
+
256
+ if args.num_threads == 1:
257
+ for instance_id in tqdm(instances, total=len(instances), colour="MAGENTA"):
258
+ gen_test(instance_id, args, swe_bench_data, prev_o)
259
+ else:
260
+ write_lock = Lock()
261
+ with concurrent.futures.ThreadPoolExecutor(
262
+ max_workers=args.num_threads
263
+ ) as executor:
264
+ futures = {
265
+ executor.submit(
266
+ gen_test, instance_id, args, swe_bench_data, prev_o, write_lock
267
+ ): instance_id
268
+ for instance_id in instances
269
+ }
270
+ for future in tqdm(
271
+ concurrent.futures.as_completed(futures),
272
+ total=len(instances),
273
+ colour="MAGENTA",
274
+ ):
275
+ future.result()
276
+
277
+
278
+ def post_process_tests(args):
279
+ """
280
+ apply some diff formatting.
281
+ """
282
+ raw_outputs = load_jsonl(args.raw_output_file)
283
+ generation_idx = args.select_id
284
+
285
+ for raw_output in raw_outputs:
286
+ instance_id = raw_output["instance_id"]
287
+
288
+ if (
289
+ raw_output["raw_output"] == ""
290
+ or not raw_output["all_generations"][0][generation_idx]
291
+ ):
292
+ with open(args.output_file, "a") as f:
293
+ f.write(
294
+ json.dumps(
295
+ {
296
+ "model_name_or_path": "agentless",
297
+ "instance_id": instance_id,
298
+ "test_patch": "",
299
+ }
300
+ )
301
+ + "\n"
302
+ )
303
+ continue
304
+
305
+ if args.select_id == -1:
306
+ # Use the last generation
307
+ assert False, "not implemented for now"
308
+ else:
309
+ raw_git_diffs = raw_output["all_generations"][0][generation_idx]
310
+ extracted_code = extract_first_code_block(
311
+ raw_output["all_generations"][0][generation_idx]
312
+ )
313
+ if extracted_code:
314
+ git_diffs = create_patch_from_code(extracted_code)
315
+ else:
316
+ git_diffs = ""
317
+
318
+ with open(args.output_file, "a") as f:
319
+ f.write(
320
+ json.dumps(
321
+ {
322
+ "model_name_or_path": "agentless",
323
+ "instance_id": instance_id,
324
+ "test_patch": git_diffs.lstrip(),
325
+ "raw_test_patch": raw_git_diffs,
326
+ "original_file_content": "",
327
+ }
328
+ )
329
+ + "\n"
330
+ )
331
+
332
+
333
+ def normalize_test(test: str):
334
+ def normalize_code(code):
335
+ try:
336
+ node = ast.parse(code)
337
+ return ast.unparse(node)
338
+ except:
339
+ return code
340
+
341
+ test = normalize_code(test)
342
+
343
+ try:
344
+ remove_docstring_test = remove_comments_and_docstrings(test)
345
+ ast.parse(remove_docstring_test) # check
346
+ except:
347
+ remove_docstring_test = test
348
+
349
+ try:
350
+ test_name = remove_docstring_test.splitlines()[-1].split("(")[0]
351
+ remove_docstring_test = remove_docstring_test.replace(
352
+ test_name, "test_func"
353
+ ) # use generic name
354
+ except:
355
+ pass
356
+
357
+ return remove_docstring_test
358
+
359
+
360
+ def normalize_tests(args):
361
+
362
+ selected_ids = list(range(int(args.max_samples)))
363
+
364
+ for i in selected_ids:
365
+ if os.path.exists(
366
+ f"{args.output_folder}/output_{i}_normalized_reproduction_test.jsonl"
367
+ ):
368
+ continue
369
+
370
+ tests = load_jsonl(
371
+ f"{args.output_folder}/output_{i}_processed_reproduction_test.jsonl"
372
+ )
373
+ for d in tests:
374
+ test = extract_first_code_block(d["raw_test_patch"])
375
+ normalized_test = normalize_test(test)
376
+ d["normalized_test"] = normalized_test
377
+
378
+ with open(
379
+ f"{args.output_folder}/output_{i}_normalized_reproduction_test.jsonl", "w"
380
+ ) as f:
381
+ for d in tests:
382
+ f.write(json.dumps(d) + "\n")
383
+
384
+
385
+ def get_sample(execution_results, instance_id, sample_id) -> tuple[str, bool]:
386
+ """Returns the diff and pass status."""
387
+ return execution_results[instance_id][sample_id]
388
+
389
+
390
+ def test_selection(args):
391
+ from pathlib import Path
392
+
393
+ test_exec_results = {}
394
+
395
+ roots = [Path(folder) for folder in args.output_folder.split(",")]
396
+
397
+ intervals = [(0, int(args.max_samples / len(roots)) - 1) for _ in range(len(roots))]
398
+
399
+ interval = intervals[0]
400
+ for i in range(interval[0], interval[1] + 1):
401
+ for index, root in enumerate(roots):
402
+ test_patches = load_jsonl(
403
+ f"{root}/output_{i}_normalized_reproduction_test.jsonl"
404
+ )
405
+ filtered_results = load_jsonl(
406
+ f"{root}/output_{i}_processed_reproduction_test_verified.jsonl"
407
+ )
408
+ print(
409
+ f"Loaded {len(test_patches)} patches from {root}/output_{i}_normalized.jsonl"
410
+ )
411
+ for test_patch in test_patches[:]:
412
+ filtered = [
413
+ x
414
+ for x in filtered_results
415
+ if x["instance_id"] == test_patch["instance_id"]
416
+ ]
417
+ if len(filtered) != 0:
418
+ filtered_status = filtered[0]["verified"]
419
+ else:
420
+ filtered_status = False
421
+ test_exec_results.setdefault(test_patch["instance_id"], []).append(
422
+ {
423
+ "normalized_test": test_patch["normalized_test"].strip(),
424
+ "test_patch": test_patch["test_patch"],
425
+ "filtered_status": filtered_status,
426
+ }
427
+ )
428
+
429
+ total_count = 0
430
+
431
+ for instance_id in test_exec_results:
432
+ patch_keys = [
433
+ test_exec_results[instance_id][i]["normalized_test"]
434
+ for i in range(len(test_exec_results[instance_id]))
435
+ ]
436
+ verified = [
437
+ test_exec_results[instance_id][i]["filtered_status"]
438
+ for i in range(len(test_exec_results[instance_id]))
439
+ ]
440
+
441
+ patch_ids = [
442
+ i
443
+ for i in range(len(test_exec_results[instance_id]))
444
+ if patch_keys[i].strip() and verified[i]
445
+ ]
446
+
447
+ if not patch_ids:
448
+ continue
449
+
450
+ vote = Counter()
451
+ first_appear_idx = dict()
452
+ unique_patches = set()
453
+ for i in patch_ids:
454
+ sample = get_sample(test_exec_results, instance_id, i)
455
+ patch_key, patch = sample["normalized_test"], sample["test_patch"]
456
+ vote[patch_key] += 1
457
+ if patch_key not in first_appear_idx:
458
+ first_appear_idx[patch_key] = i
459
+
460
+ unique_patches.add(patch_key)
461
+
462
+ maj_selected_id = max(
463
+ patch_ids,
464
+ key=lambda i: (vote[patch_keys[i]], -first_appear_idx[patch_keys[i]]),
465
+ )
466
+
467
+ print([vote[patch_keys[i]] for i in patch_ids])
468
+
469
+ sample = get_sample(test_exec_results, instance_id, maj_selected_id)
470
+
471
+ result = {
472
+ "model_name_or_path": "agentless",
473
+ "instance_id": instance_id,
474
+ "test_patch": sample["test_patch"],
475
+ }
476
+
477
+ total_count += 1
478
+
479
+ with open(f"{args.output_folder}/{args.output_file}", "a") as f:
480
+ f.write(json.dumps(result) + "\n")
481
+
482
+ print(total_count)
483
+
484
+
485
+ def main():
486
+ parser = argparse.ArgumentParser()
487
+ parser.add_argument("--max_samples", type=int, default=20, help="Sampling budget.")
488
+ parser.add_argument(
489
+ "--select_id",
490
+ type=int,
491
+ default=-1,
492
+ help="Index the selected samples during post-processing.",
493
+ )
494
+ parser.add_argument(
495
+ "--model",
496
+ type=str,
497
+ default=os.getenv("AGENTLESS_MODEL", "gpt-5.2"),
498
+ help="Model name (defaults to $AGENTLESS_MODEL).",
499
+ )
500
+ parser.add_argument(
501
+ "--backend",
502
+ type=str,
503
+ default="openai",
504
+ choices=["openai", "deepseek", "anthropic"],
505
+ )
506
+ parser.add_argument("--output_folder", type=str, required=True)
507
+ parser.add_argument("--output_file", type=str)
508
+ parser.add_argument("--skip_greedy", action="store_true")
509
+ parser.add_argument(
510
+ "--num_threads",
511
+ type=int,
512
+ default=1,
513
+ help="Number of threads to use for creating API requests",
514
+ )
515
+ parser.add_argument("--target_id", type=str)
516
+ parser.add_argument(
517
+ "--mock", action="store_true", help="Mock run to compute prompt tokens."
518
+ )
519
+ parser.add_argument("--select", action="store_true")
520
+ parser.add_argument(
521
+ "--dataset",
522
+ type=str,
523
+ default="princeton-nlp/SWE-bench_Lite",
524
+ choices=["princeton-nlp/SWE-bench_Lite", "princeton-nlp/SWE-bench_Verified"],
525
+ )
526
+
527
+ args = parser.parse_args()
528
+
529
+ assert (not "deepseek" in args.model) or (
530
+ args.backend == "deepseek"
531
+ ), "Must specify `--backend deepseek` if using a DeepSeek model"
532
+
533
+ if not os.path.exists(args.output_folder):
534
+ os.makedirs(args.output_folder)
535
+ if not os.path.exists(os.path.join(args.output_folder, "generating_test_logs")):
536
+ os.makedirs(os.path.join(args.output_folder, "generating_test_logs"))
537
+
538
+ if not args.select:
539
+ args.output_file = os.path.join(args.output_folder, "output.jsonl")
540
+ generate_tests(args)
541
+ args.raw_output_file = args.output_file
542
+ for i in range(args.max_samples):
543
+ args.output_file = args.raw_output_file.replace(
544
+ ".jsonl", f"_{i}_processed_reproduction_test.jsonl"
545
+ )
546
+ args.select_id = i
547
+ post_process_tests(args)
548
+ else:
549
+ normalize_tests(args)
550
+ test_selection(args)
551
+
552
+
553
+ if __name__ == "__main__":
554
+ main()
Repos/HWE/agents/Agentless/agentless/test/run_regression_tests.py ADDED
@@ -0,0 +1,254 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import json
3
+ import os
4
+
5
+ import jsonlines
6
+ from datasets import load_dataset
7
+ from swebench.harness.constants import (
8
+ FAIL_TO_PASS,
9
+ KEY_INSTANCE_ID,
10
+ PASS_TO_PASS,
11
+ TestStatus,
12
+ )
13
+ from swebench.harness.grading import get_eval_tests_report, get_logs_eval
14
+
15
+ from agentless.test.run_tests import run_tests
16
+
17
+
18
+ def rewrite_report(instance_id, input_folder_path, regression_tests):
19
+
20
+ log_path = f"{input_folder_path}/test/{instance_id}/test_output.txt"
21
+ eval_sm, found = get_logs_eval(log_path)
22
+
23
+ eval_ref = {
24
+ KEY_INSTANCE_ID: instance_id,
25
+ FAIL_TO_PASS: [],
26
+ PASS_TO_PASS: regression_tests[instance_id],
27
+ }
28
+
29
+ report = get_eval_tests_report(eval_sm, eval_ref)
30
+
31
+ return report["PASS_TO_PASS"]["failure"]
32
+
33
+
34
+ def save_passing_tests(output_jsonl_path, input_folder_path, dataset):
35
+ ds = load_dataset(dataset)
36
+
37
+ with jsonlines.open(output_jsonl_path, mode="w") as writer:
38
+ for entry in ds["test"]:
39
+ instance_id = entry["instance_id"]
40
+
41
+ log_path = f"{input_folder_path}/test/{instance_id}/test_output.txt"
42
+ try:
43
+ # obtain the list of tests that were ran
44
+ eval_sm, found = get_logs_eval(log_path)
45
+ except FileNotFoundError:
46
+ print(f"File not found: {log_path}")
47
+ continue
48
+
49
+ successful_test = []
50
+
51
+ for test_name, status in eval_sm.items():
52
+ # check for tests that passed
53
+ # NOTE: Different from `swebench.harness.grading.test_passed`, we don't collect XFAIL tests
54
+ # because they are expected to fail
55
+ if status in [TestStatus.PASSED.value]:
56
+ successful_test.append(test_name)
57
+
58
+ if successful_test == []:
59
+ print(f"{instance_id} didn't get any passing tests")
60
+
61
+ # Create the dictionary for each entry
62
+ result_entry = {
63
+ "instance_id": instance_id,
64
+ "tests_passing_in_original_repo": successful_test,
65
+ }
66
+
67
+ # Write the entry to the JSONL file
68
+ writer.write(result_entry)
69
+
70
+
71
+ def run_regression_for_each_instance(args, lines, run_id):
72
+
73
+ instance_ids = [line["instance_id"] for line in lines]
74
+ patches = [line["model_patch"] for line in lines]
75
+
76
+ instance_to_plausible = run_tests(
77
+ instance_ids,
78
+ patches,
79
+ args.num_workers,
80
+ run_id,
81
+ args.regression_tests,
82
+ args.instance_ids,
83
+ args.timeout,
84
+ apply_model_patch=True,
85
+ dataset_name=args.dataset,
86
+ )
87
+ return instance_to_plausible
88
+
89
+
90
+ def check_if_all_instances_pass(instance_to_plausible):
91
+ all_passed = True
92
+ not_passing_instances = []
93
+ for key, value in instance_to_plausible.items():
94
+ if not value:
95
+ all_passed = False
96
+ not_passing_instances.append(key)
97
+
98
+ if all_passed:
99
+ print("All the chosen regression tests pass in the base repository")
100
+ else:
101
+ print(
102
+ f"One or more of the regression tests for instances {not_passing_instances} do not pass in the original repository"
103
+ )
104
+ print(len(not_passing_instances))
105
+
106
+
107
+ def _run_regression(args):
108
+ if args.predictions_path == "gold":
109
+ ds = load_dataset(args.dataset)
110
+ instance_ids = ds["test"]["instance_id"]
111
+ patches = ds["test"]["patch"]
112
+
113
+ instance_to_plausible = run_tests(
114
+ instance_ids,
115
+ patches,
116
+ args.num_workers,
117
+ args.run_id,
118
+ args.regression_tests,
119
+ args.instance_ids,
120
+ args.timeout,
121
+ apply_model_patch=True,
122
+ dataset_name=args.dataset,
123
+ )
124
+ check_if_all_instances_pass(instance_to_plausible)
125
+ elif args.predictions_path:
126
+ assert args.predictions_path.endswith("_processed.jsonl")
127
+ with open(args.predictions_path, "r") as file:
128
+ data_lines = [json.loads(line) for line in file]
129
+
130
+ if not args.load:
131
+ run_regression_for_each_instance(args, data_lines, args.run_id)
132
+
133
+ regression_dict = {}
134
+ instance_test_dict = {}
135
+
136
+ with open(args.regression_tests, "r") as file:
137
+ for line in file:
138
+ json_obj = json.loads(line.strip())
139
+ instance_id = json_obj["instance_id"]
140
+ test = json_obj["tests_passing_in_original_repo"]
141
+ instance_test_dict[instance_id] = test
142
+
143
+ for data in data_lines:
144
+ instance_id = data["instance_id"]
145
+ if os.path.isfile(
146
+ f"logs/run_evaluation/{args.run_id}/test/{instance_id}/report.json"
147
+ ):
148
+ regression_dict[instance_id] = rewrite_report(
149
+ instance_id,
150
+ f"logs/run_evaluation/{args.run_id}",
151
+ instance_test_dict,
152
+ )
153
+ else:
154
+ regression_dict[instance_id] = []
155
+
156
+ updated_data_lines = []
157
+ for data in data_lines:
158
+ instance_id = data["instance_id"]
159
+ if instance_id in regression_dict:
160
+ data["regression"] = regression_dict[instance_id]
161
+ updated_data_lines.append(data)
162
+
163
+ with open(
164
+ args.predictions_path.replace(
165
+ "processed.jsonl", "regression_test_results.jsonl"
166
+ ),
167
+ "w",
168
+ ) as file:
169
+ for data in updated_data_lines:
170
+ file.write(json.dumps(data) + "\n")
171
+
172
+ else:
173
+ # this is for generating a list of passing tests from the original repor
174
+ # TODO: some instances don't get any passing tests because some test files
175
+ # are renamed in the test patch and we grabbed the new file names.
176
+ # We can fix this by checking if a test file exists in the base repo.
177
+ ds = load_dataset(args.dataset)
178
+ instance_ids = (
179
+ ds["test"]["instance_id"]
180
+ if args.instance_ids is None
181
+ else args.instance_ids
182
+ )
183
+
184
+ # Feed in a list of blank patches
185
+ patches = [
186
+ {"instance_id": instance_id, "patch": "", "normalized_patch": ""}
187
+ for instance_id in instance_ids
188
+ ]
189
+
190
+ instance_to_plausible = run_tests(
191
+ instance_ids,
192
+ patches,
193
+ args.num_workers,
194
+ args.run_id,
195
+ args.regression_tests,
196
+ args.instance_ids,
197
+ args.timeout,
198
+ apply_model_patch=False,
199
+ dataset_name=args.dataset,
200
+ )
201
+
202
+ if args.regression_tests:
203
+ # check if the base repo all passes on the selected regression tests (should be true)
204
+ check_if_all_instances_pass(instance_to_plausible)
205
+
206
+ else:
207
+ # save the list of passing tests
208
+ save_passing_tests(
209
+ args.output_file,
210
+ os.path.join("logs", "run_evaluation", args.run_id),
211
+ args.dataset,
212
+ )
213
+
214
+
215
+ def main():
216
+ parser = argparse.ArgumentParser()
217
+ parser.add_argument("--run_id", type=str, required=True)
218
+ parser.add_argument(
219
+ "--predictions_path",
220
+ type=str,
221
+ help="Patch file with normalized patches",
222
+ )
223
+ parser.add_argument("--output_file", type=str)
224
+ parser.add_argument("--regression_tests", type=str)
225
+ parser.add_argument("--num_workers", type=int, default=12)
226
+ parser.add_argument(
227
+ "--timeout", type=int, default=1200, help="Timeout for running tests in seconds"
228
+ )
229
+ parser.add_argument(
230
+ "--instance_ids",
231
+ nargs="+",
232
+ type=str,
233
+ help="Instance IDs to run (space separated), if not provided, all instances will be run",
234
+ )
235
+ parser.add_argument("--filter", action="store_true")
236
+ parser.add_argument("--load", action="store_true")
237
+ parser.add_argument(
238
+ "--dataset",
239
+ type=str,
240
+ default="princeton-nlp/SWE-bench_Lite",
241
+ choices=["princeton-nlp/SWE-bench_Lite", "princeton-nlp/SWE-bench_Verified"],
242
+ )
243
+
244
+ args = parser.parse_args()
245
+
246
+ assert not (
247
+ args.predictions_path and args.output_file
248
+ ), "An output file is only required when selecting regression tests"
249
+
250
+ _run_regression(args)
251
+
252
+
253
+ if __name__ == "__main__":
254
+ main()
Repos/HWE/agents/Agentless/agentless/test/run_reproduction_tests.py ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import json
3
+ import os
4
+
5
+ from datasets import load_dataset
6
+
7
+ from agentless.test.run_tests import run_reproduction_tests, txt_file_contains_string
8
+ from agentless.util.utils import load_jsonl
9
+
10
+ execution_results = dict()
11
+
12
+
13
+ def run_reproduction_for_each_instance(args, lines, run_id, test_jsonl):
14
+
15
+ instance_ids = [line["instance_id"] for line in lines]
16
+ patches = [line["model_patch"] for line in lines]
17
+
18
+ results = run_reproduction_tests(
19
+ instance_ids,
20
+ patches,
21
+ args.num_workers,
22
+ run_id,
23
+ args.instance_ids,
24
+ args.timeout,
25
+ testing_patches=False,
26
+ apply_model_patch=True,
27
+ test_jsonl=test_jsonl,
28
+ dataset_name=args.dataset,
29
+ )
30
+ return results
31
+
32
+
33
+ def _run_reproduction_tests(args):
34
+ if args.testing:
35
+ # for reproduction test selection
36
+ # run on original repo to select tests which can reproduce the issue
37
+ ds = load_dataset(args.dataset)
38
+ instance_ids = ds["test"]["instance_id"]
39
+ patches = [
40
+ {"instance_id": instance_id, "patch": "", "normalized_patch": ""}
41
+ for instance_id in instance_ids
42
+ ]
43
+
44
+ evaluation_tests = load_jsonl(args.test_jsonl)
45
+
46
+ results = run_reproduction_tests(
47
+ instance_ids,
48
+ patches,
49
+ args.num_workers,
50
+ args.run_id,
51
+ args.instance_ids,
52
+ args.timeout,
53
+ testing_patches=True,
54
+ apply_model_patch=False,
55
+ test_jsonl=args.test_jsonl,
56
+ dataset_name=args.dataset,
57
+ )
58
+
59
+ with open(args.test_jsonl.replace(".jsonl", "_verified.jsonl"), "w") as file:
60
+ for evaluation_test in evaluation_tests:
61
+ instance_id = evaluation_test["instance_id"]
62
+ if instance_id in results and results[instance_id]:
63
+ evaluation_test["verified"] = True
64
+ file.write(json.dumps(evaluation_test) + "\n")
65
+
66
+ elif args.predictions_path == "gold":
67
+ # check on groundtruth patches
68
+ # for evaluation purposes
69
+ ds = load_dataset(args.dataset)
70
+ instance_ids = ds["test"]["instance_id"]
71
+ patches = ds["test"]["patch"]
72
+
73
+ results = run_reproduction_tests(
74
+ instance_ids,
75
+ patches,
76
+ args.num_workers,
77
+ args.run_id,
78
+ args.instance_ids,
79
+ args.timeout,
80
+ testing_patches=False,
81
+ apply_model_patch=True,
82
+ test_jsonl=args.test_jsonl,
83
+ dataset_name=args.dataset,
84
+ )
85
+
86
+ with open(
87
+ "gold_production_test_results.json",
88
+ "w",
89
+ ) as file:
90
+ file.write(json.dumps(results))
91
+
92
+ else:
93
+ # run on the agentless generated patches
94
+ assert args.predictions_path.endswith("_processed.jsonl")
95
+ with open(args.predictions_path, "r") as file:
96
+ data_lines = [json.loads(line) for line in file]
97
+
98
+ if args.load:
99
+ reproduction_dict = {}
100
+ for data in data_lines:
101
+ instance_id = data["instance_id"]
102
+ expected_output = "Issue resolved"
103
+ path_to_log = f"logs/run_evaluation/{args.run_id}/test/{instance_id}/test_output.txt"
104
+ if os.path.isfile(path_to_log):
105
+ passes_tests = txt_file_contains_string(
106
+ path_to_log, expected_output
107
+ )
108
+ reproduction_dict[instance_id] = passes_tests
109
+ else:
110
+ reproduction_dict[instance_id] = False
111
+ else:
112
+ reproduction_dict = run_reproduction_for_each_instance(
113
+ args, data_lines, args.run_id, args.test_jsonl
114
+ )
115
+
116
+ updated_data_lines = []
117
+ for data in data_lines:
118
+ instance_id = data["instance_id"]
119
+ if instance_id in reproduction_dict:
120
+ data["reproduction"] = reproduction_dict[instance_id]
121
+ updated_data_lines.append(data)
122
+
123
+ with open(
124
+ args.predictions_path.replace(
125
+ "processed.jsonl", "reproduction_test_results.jsonl"
126
+ ),
127
+ "w",
128
+ ) as file:
129
+ for data in updated_data_lines:
130
+ file.write(json.dumps(data) + "\n")
131
+
132
+
133
+ def main():
134
+ parser = argparse.ArgumentParser()
135
+ parser.add_argument("--run_id", type=str, required=True)
136
+ parser.add_argument(
137
+ "--testing", action="store_true", help="If true don't apply the model patch"
138
+ )
139
+ parser.add_argument(
140
+ "--predictions_path",
141
+ type=str,
142
+ help="Patch file",
143
+ )
144
+ parser.add_argument("--num_workers", type=int, default=12)
145
+ parser.add_argument(
146
+ "--timeout", type=int, default=600, help="Timeout for running tests in seconds"
147
+ )
148
+ parser.add_argument(
149
+ "--instance_ids",
150
+ nargs="+",
151
+ type=str,
152
+ help="Instance IDs to run (space separated)",
153
+ )
154
+ parser.add_argument(
155
+ "--dataset",
156
+ type=str,
157
+ default="princeton-nlp/SWE-bench_Lite",
158
+ choices=["princeton-nlp/SWE-bench_Lite", "princeton-nlp/SWE-bench_Verified"],
159
+ )
160
+ parser.add_argument("--test_jsonl", type=str)
161
+ parser.add_argument("--load", action="store_true")
162
+
163
+ args = parser.parse_args()
164
+
165
+ # then load and run production tests on the results
166
+ _run_reproduction_tests(args)
167
+
168
+
169
+ if __name__ == "__main__":
170
+ main()
Repos/HWE/agents/Agentless/agentless/test/run_tests.py ADDED
@@ -0,0 +1,630 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ import platform
4
+ import re
5
+ import resource
6
+ import traceback
7
+ from concurrent.futures import ThreadPoolExecutor, as_completed
8
+ from typing import Any
9
+
10
+ import docker
11
+ from swebench.harness.constants import (
12
+ FAIL_TO_PASS,
13
+ KEY_INSTANCE_ID,
14
+ MAP_REPO_VERSION_TO_SPECS,
15
+ PASS_TO_PASS,
16
+ USE_X86,
17
+ SWEbenchInstance,
18
+ )
19
+ from swebench.harness.docker_build import build_env_images
20
+ from swebench.harness.run_evaluation import get_dataset_from_preds, run_instance
21
+ from swebench.harness.test_spec import (
22
+ TestSpec,
23
+ make_env_script_list,
24
+ make_repo_script_list,
25
+ )
26
+ from swebench.harness.utils import get_test_directives
27
+ from tqdm import tqdm
28
+
29
+ OPEN_FILE_LIMIT = 4096
30
+
31
+ NOOP_PATCH = """diff --git a/this_is_invisible.py b/this_is_invisible.py
32
+ new file mode 100644
33
+ index 0000000..e69de29
34
+ --- /dev/null
35
+ +++ b/this_is_invisible.py
36
+ @@ -0,0 +1 @@
37
+ +# This is a commented out line
38
+ """
39
+
40
+ NOOP_PATCH_2 = """diff --git a/this_is_invisible_2.py b/this_is_invisible_2.py
41
+ new file mode 100644
42
+ index 0000000..e69de29
43
+ --- /dev/null
44
+ +++ b/this_is_invisible_2.py
45
+ @@ -0,0 +1 @@
46
+ +# This is a commented out line
47
+ """
48
+
49
+
50
+ def remove_ansi_sequences(input_string):
51
+ ansi_escape_pattern = r"\x1b\[\d+m"
52
+ clean_string = re.sub(ansi_escape_pattern, "", input_string)
53
+
54
+ return clean_string
55
+
56
+
57
+ def txt_file_contains_string(path_to_txt, expected_output, other_patterns=[]):
58
+ """
59
+ Check if the given text file contains the specified string.
60
+ :param path_to_txt: Path to the text file.
61
+ :param expected_output: The string to search for in the text file.
62
+ :return: True if the string is found in the text file, otherwise False.
63
+ """
64
+ try:
65
+ with open(path_to_txt, "r", encoding="utf-8") as file:
66
+ content = file.read()
67
+ filtered_content = remove_ansi_sequences(content)
68
+ for pattern in other_patterns:
69
+ if pattern in filtered_content:
70
+ return False
71
+ return expected_output in filtered_content
72
+
73
+ except FileNotFoundError:
74
+ pass
75
+ except IOError:
76
+ print(f"An error occurred while reading the file at {path_to_txt}.")
77
+
78
+ return False
79
+
80
+
81
+ def create_instance_test_dict(jsonl_file_path):
82
+ instance_test_dict = {}
83
+
84
+ with open(jsonl_file_path, "r") as file:
85
+ for line in file:
86
+ json_obj = json.loads(line.strip())
87
+ instance_id = json_obj["instance_id"]
88
+ test_patch = json_obj["test_patch"]
89
+ instance_test_dict[instance_id] = test_patch
90
+
91
+ return instance_test_dict
92
+
93
+
94
+ def extract_resolved_info(directory_path):
95
+ # Check if the directory exists
96
+ if not os.path.exists(directory_path) or not os.path.isdir(directory_path):
97
+ return {}
98
+
99
+ result = {}
100
+ for subdir in os.listdir(directory_path):
101
+ subdir_path = os.path.join(directory_path, subdir)
102
+ if os.path.isdir(subdir_path):
103
+ report_path = os.path.join(subdir_path, "report.json")
104
+ if os.path.isfile(report_path):
105
+ try:
106
+ with open(report_path, "r", encoding="utf-8") as report_file:
107
+ data = json.load(report_file)
108
+ resolved_value = data.get(subdir, {}).get("resolved", False)
109
+ result[subdir] = resolved_value
110
+ except (json.JSONDecodeError, KeyError):
111
+ result[subdir] = False
112
+ # else:
113
+ # result[subdir] = False
114
+ return result
115
+
116
+
117
+ def make_reproduction_sec(instance: SWEbenchInstance) -> TestSpec:
118
+ if isinstance(instance, TestSpec):
119
+ return instance
120
+ instance_id = instance[KEY_INSTANCE_ID]
121
+ repo = instance["repo"]
122
+ version = instance["version"]
123
+ base_commit = instance["base_commit"]
124
+ production_test = instance["production_test"]
125
+
126
+ def _from_json_or_obj(key: str) -> Any:
127
+ """If key points to string, load with json"""
128
+ if isinstance(instance[key], str):
129
+ return json.loads(instance[key])
130
+ return instance[key]
131
+
132
+ pass_to_pass = _from_json_or_obj(PASS_TO_PASS)
133
+ fail_to_pass = _from_json_or_obj(FAIL_TO_PASS)
134
+
135
+ env_name = "testbed"
136
+ repo_directory = f"/{env_name}"
137
+ specs = MAP_REPO_VERSION_TO_SPECS[repo][version]
138
+
139
+ repo_script_list = make_repo_script_list(
140
+ specs, repo, repo_directory, base_commit, env_name
141
+ )
142
+ env_script_list = make_env_script_list(instance, specs, env_name)
143
+ eval_script_list = make_reproduction_script_list(
144
+ instance, specs, env_name, repo_directory, base_commit, production_test
145
+ )
146
+ if platform.machine() in {"aarch64", "arm64"}:
147
+ # use arm64 unless explicitly specified
148
+ arch = "arm64" if instance_id not in USE_X86 else "x86_64"
149
+ else:
150
+ arch = "x86_64"
151
+
152
+ return TestSpec(
153
+ instance_id=instance_id,
154
+ repo=repo,
155
+ env_script_list=env_script_list,
156
+ repo_script_list=repo_script_list,
157
+ eval_script_list=eval_script_list,
158
+ version=version,
159
+ arch=arch,
160
+ FAIL_TO_PASS=fail_to_pass,
161
+ PASS_TO_PASS=pass_to_pass,
162
+ )
163
+
164
+
165
+ def make_reproduction_script_list(
166
+ instance, specs, env_name, repo_directory, base_commit, reproduce_patch
167
+ ):
168
+ """
169
+ Applies new production tests and run tests
170
+ """
171
+ # Reset test files to the state they should be in before the patch.
172
+ reset_tests_command = f"git checkout {base_commit}"
173
+
174
+ HEREDOC_DELIMITER = "EOF_114329324912"
175
+ fake_apply_test_patch_command = (
176
+ f"git apply -v - <<'{HEREDOC_DELIMITER}'\n{NOOP_PATCH_2}\n{HEREDOC_DELIMITER}"
177
+ )
178
+
179
+ apply_reproduce_test_command = f"git apply -v - <<'{HEREDOC_DELIMITER}'\n{reproduce_patch}\n{HEREDOC_DELIMITER}"
180
+ reproduce_test_command = "python3 reproduce_bug.py"
181
+
182
+ eval_commands = [
183
+ f"source /opt/miniconda3/bin/activate",
184
+ f"conda activate {env_name}",
185
+ f"cd {repo_directory}",
186
+ ]
187
+ if "eval_commands" in specs:
188
+ eval_commands += specs["eval_commands"]
189
+ eval_commands += [
190
+ f"git config --global --add safe.directory {repo_directory}", # for nonroot user
191
+ f"cd {repo_directory}",
192
+ # This is just informational, so we have a record
193
+ f"git status",
194
+ f"git show",
195
+ f"git diff {base_commit}",
196
+ "source /opt/miniconda3/bin/activate",
197
+ f"conda activate {env_name}",
198
+ ]
199
+ if "install" in specs:
200
+ eval_commands.append(specs["install"])
201
+ eval_commands += [
202
+ reset_tests_command,
203
+ fake_apply_test_patch_command, # If we don't apply some sort of patch the harness won't return the tests which passed
204
+ apply_reproduce_test_command,
205
+ reproduce_test_command,
206
+ # reset_tests_command,
207
+ ]
208
+ return eval_commands
209
+
210
+
211
+ def make_regression_spec(instance: SWEbenchInstance) -> TestSpec:
212
+ if isinstance(instance, TestSpec):
213
+ return instance
214
+ instance_id = instance[KEY_INSTANCE_ID]
215
+ repo = instance["repo"]
216
+ version = instance["version"]
217
+ base_commit = instance["base_commit"]
218
+
219
+ def _from_json_or_obj(key: str) -> Any:
220
+ """If key points to string, load with json"""
221
+ if isinstance(instance[key], str):
222
+ return json.loads(instance[key])
223
+ return instance[key]
224
+
225
+ pass_to_pass = _from_json_or_obj(PASS_TO_PASS)
226
+ fail_to_pass = _from_json_or_obj(FAIL_TO_PASS)
227
+
228
+ env_name = "testbed"
229
+ repo_directory = f"/{env_name}"
230
+ specs = MAP_REPO_VERSION_TO_SPECS[repo][version]
231
+
232
+ repo_script_list = make_repo_script_list(
233
+ specs, repo, repo_directory, base_commit, env_name
234
+ )
235
+ env_script_list = make_env_script_list(instance, specs, env_name)
236
+ eval_script_list = make_regression_script_list(
237
+ instance, specs, env_name, repo_directory, base_commit
238
+ )
239
+ if platform.machine() in {"aarch64", "arm64"}:
240
+ # use arm64 unless explicitly specified
241
+ arch = "arm64" if instance_id not in USE_X86 else "x86_64"
242
+ else:
243
+ arch = "x86_64"
244
+
245
+ return TestSpec(
246
+ instance_id=instance_id,
247
+ repo=repo,
248
+ env_script_list=env_script_list,
249
+ repo_script_list=repo_script_list,
250
+ eval_script_list=eval_script_list,
251
+ version=version,
252
+ arch=arch,
253
+ FAIL_TO_PASS=fail_to_pass, # Remove the fail to pass cases
254
+ PASS_TO_PASS=pass_to_pass,
255
+ )
256
+
257
+
258
+ def make_regression_script_list(instance, specs, env_name, repo_directory, base_commit):
259
+ """
260
+ Applies the test patch and runs the tests.
261
+ """
262
+ # Reset test files to the state they should be in before the patch.
263
+ reset_tests_command = f"git checkout {base_commit}"
264
+
265
+ HEREDOC_DELIMITER = "EOF_114329324912"
266
+ fake_apply_test_patch_command = (
267
+ f"git apply -v - <<'{HEREDOC_DELIMITER}'\n{NOOP_PATCH_2}\n{HEREDOC_DELIMITER}"
268
+ )
269
+
270
+ test_command = " ".join(
271
+ [
272
+ MAP_REPO_VERSION_TO_SPECS[instance["repo"]][instance["version"]][
273
+ "test_cmd"
274
+ ],
275
+ *get_test_directives(instance),
276
+ ]
277
+ )
278
+ eval_commands = [
279
+ "source /opt/miniconda3/bin/activate",
280
+ f"conda activate {env_name}",
281
+ f"cd {repo_directory}",
282
+ ]
283
+ if "eval_commands" in specs:
284
+ eval_commands += specs["eval_commands"]
285
+ eval_commands += [
286
+ f"git config --global --add safe.directory {repo_directory}", # for nonroot user
287
+ f"cd {repo_directory}",
288
+ # This is just informational, so we have a record
289
+ "git status",
290
+ "git show",
291
+ f"git diff {base_commit}",
292
+ "source /opt/miniconda3/bin/activate",
293
+ f"conda activate {env_name}",
294
+ ]
295
+ if "install" in specs:
296
+ eval_commands.append(specs["install"])
297
+ eval_commands += [
298
+ reset_tests_command,
299
+ fake_apply_test_patch_command, # If we don't apply some sort of patch the harness won't return the tests which passed
300
+ test_command,
301
+ reset_tests_command,
302
+ ]
303
+ return eval_commands
304
+
305
+
306
+ def rearrange_patches(test_specs):
307
+ """
308
+ rearrange the patches such that slower instance_ids are evaluated first
309
+ this way pipelining will be faster.
310
+ """
311
+
312
+ slow_instance_ids = ["sympy__sympy-11870"]
313
+
314
+ slow_specs = [
315
+ test_spec
316
+ for test_spec in test_specs
317
+ if test_spec.instance_id in slow_instance_ids
318
+ ]
319
+
320
+ if len(slow_specs) != 0:
321
+ print(
322
+ f"rearrange patches such that {[x.instance_id for x in slow_specs]} are evaluated first"
323
+ )
324
+ rearranged_test_specs = slow_specs
325
+ for test_spec in test_specs:
326
+ if test_spec.instance_id not in slow_instance_ids:
327
+ rearranged_test_specs.append(test_spec)
328
+ return rearranged_test_specs
329
+ else:
330
+ return test_specs
331
+
332
+
333
+ def run_reproduction_tests(
334
+ instance_ids: list,
335
+ model_patches: list,
336
+ max_workers: int,
337
+ run_id: str,
338
+ instances_to_run: list,
339
+ timeout: int,
340
+ testing_patches: bool,
341
+ apply_model_patch=True,
342
+ test_jsonl=None,
343
+ dataset_name="princeton-nlp/SWE-bench_Lite",
344
+ ):
345
+ assert len(instance_ids) == len(
346
+ model_patches
347
+ ), "There must be the same number of instance_ids as model patches"
348
+ resource.setrlimit(resource.RLIMIT_NOFILE, (OPEN_FILE_LIMIT, OPEN_FILE_LIMIT))
349
+
350
+ instance_to_reproduction_code = create_instance_test_dict(test_jsonl)
351
+
352
+ print(f"Using run_id: {run_id}")
353
+
354
+ split = "test"
355
+ client = docker.from_env()
356
+ force_rebuild = False
357
+
358
+ predictions = {}
359
+
360
+ for idx, one_instance_id in enumerate(instance_ids):
361
+ if not apply_model_patch:
362
+ patch_to_apply = NOOP_PATCH
363
+ else:
364
+ patch_to_apply = model_patches[idx]
365
+ if testing_patches:
366
+ predictions[one_instance_id] = {
367
+ "model_name_or_path": "test",
368
+ "model_patch": NOOP_PATCH,
369
+ "instance_id": one_instance_id,
370
+ }
371
+ # instance_to_reproduction_code[one_instance_id] = patch_to_apply
372
+ else:
373
+ predictions[one_instance_id] = {
374
+ "model_name_or_path": "test", # TODO change.
375
+ "model_patch": patch_to_apply,
376
+ "instance_id": one_instance_id,
377
+ }
378
+
379
+ instances = get_dataset_from_preds(
380
+ dataset_name, split, instance_ids, predictions, run_id
381
+ )
382
+
383
+ if not instances:
384
+ print("No instances to run.")
385
+ else:
386
+ build_env_images(client, instances, force_rebuild, max_workers)
387
+
388
+ no_f2p_instances = []
389
+
390
+ for instance in instances:
391
+ revised_instance = instance
392
+ revised_instance["FAIL_TO_PASS"] = "[]"
393
+ revised_instance["PASS_TO_PASS"] = "[]"
394
+
395
+ if instance["instance_id"] in instance_to_reproduction_code:
396
+ revised_instance["production_test"] = instance_to_reproduction_code[
397
+ instance["instance_id"]
398
+ ]
399
+ # only run if there is production test
400
+ no_f2p_instances.append(revised_instance)
401
+
402
+ test_specs = list(map(make_reproduction_sec, no_f2p_instances))
403
+
404
+ test_specs = rearrange_patches(test_specs)
405
+
406
+ instance_image_ids = {x.instance_image_key for x in test_specs}
407
+ existing_images = {
408
+ tag
409
+ for i in client.images.list(all=True)
410
+ for tag in i.tags
411
+ if tag in instance_image_ids
412
+ }
413
+ print(f"Found {len(existing_images)} existing instance images. Will reuse them.")
414
+
415
+ # Load in previously evaluated results
416
+ resolved_dict = extract_resolved_info(
417
+ os.path.join("logs", "run_evaluation", run_id, "test")
418
+ )
419
+
420
+ if instances_to_run:
421
+ ids = instances_to_run
422
+ else:
423
+ ids = [
424
+ test_spec.instance_id
425
+ for test_spec in test_specs
426
+ if test_spec.instance_id not in list(resolved_dict.keys())
427
+ ]
428
+
429
+ results = {}
430
+
431
+ print(
432
+ f"Running {len([test_spec for test_spec in test_specs if test_spec.instance_id in ids])} unevaluated instances..."
433
+ )
434
+
435
+ # Set the empty instances as not resolving the issue
436
+ for index, patch in enumerate(model_patches):
437
+ if patch == "":
438
+ resolved_dict[instance_ids[index]] = False
439
+
440
+ with tqdm(total=len(ids), smoothing=0, colour="MAGENTA") as pbar:
441
+ with ThreadPoolExecutor(max_workers=max_workers) as executor:
442
+ # Create a future for running each instance
443
+ futures = {
444
+ executor.submit(
445
+ run_instance,
446
+ test_spec,
447
+ predictions[test_spec.instance_id],
448
+ False, # do not remove them.
449
+ force_rebuild,
450
+ client,
451
+ run_id,
452
+ timeout,
453
+ ): None
454
+ for test_spec in test_specs
455
+ if test_spec.instance_id in ids
456
+ }
457
+ # Wait for each future to complete
458
+ for future in as_completed(futures):
459
+ pbar.update(1)
460
+ result = future.result()
461
+ if result:
462
+ instance_id = result[0]
463
+ resolved = result[1][instance_id]["resolved"]
464
+ resolved_dict[instance_id] = resolved
465
+ # See if the tests ran successfully
466
+ if testing_patches:
467
+ expected_output = "Issue reproduced"
468
+ other_patterns = ["Issue resolved", "Other issues"]
469
+ else:
470
+ expected_output = "Issue resolved"
471
+ other_patterns = ["Issue reproduced", "Other issues"]
472
+ path_to_log = f"logs/run_evaluation/{run_id}/{split}/{instance_id}/test_output.txt"
473
+ passes_tests = txt_file_contains_string(
474
+ path_to_log, expected_output, other_patterns=other_patterns
475
+ )
476
+ results[instance_id] = passes_tests
477
+ try:
478
+ # Update progress bar, check if instance ran successfully
479
+ future.result()
480
+ except Exception as e:
481
+ traceback.print_exc()
482
+ results[instance_id] = False
483
+ resolved_dict[instance_id] = False
484
+ continue
485
+
486
+ print("All instances run.")
487
+ return results
488
+
489
+
490
+ def run_tests(
491
+ instance_ids: list,
492
+ model_patches: list,
493
+ max_workers: int,
494
+ run_id: str,
495
+ regression_test_file: str,
496
+ instances_to_run: list,
497
+ timeout: int,
498
+ apply_model_patch=True,
499
+ dataset_name="princeton-nlp/SWE-bench_Lite",
500
+ ):
501
+ assert len(instance_ids) == len(
502
+ model_patches
503
+ ), "There must be the same number of instance_ids as model patches"
504
+ resource.setrlimit(resource.RLIMIT_NOFILE, (OPEN_FILE_LIMIT, OPEN_FILE_LIMIT))
505
+
506
+ print(f"Using run_id: {run_id}")
507
+
508
+ split = "test"
509
+ client = docker.from_env()
510
+ force_rebuild = False
511
+
512
+ predictions = {}
513
+
514
+ for idx, one_instance_id in enumerate(instance_ids):
515
+ if not apply_model_patch:
516
+ patch_to_apply = NOOP_PATCH
517
+ else:
518
+ patch_to_apply = model_patches[idx]
519
+ predictions[one_instance_id] = {
520
+ "model_name_or_path": "test",
521
+ "model_patch": patch_to_apply,
522
+ "instance_id": one_instance_id,
523
+ }
524
+
525
+ instances = get_dataset_from_preds(
526
+ dataset_name, split, instance_ids, predictions, run_id
527
+ )
528
+
529
+ print(f"Running {len(instances)} unevaluated instances...")
530
+ if not instances:
531
+ print("No instances to run.")
532
+ else:
533
+ build_env_images(client, instances, force_rebuild, max_workers)
534
+
535
+ instance_test_dict = {}
536
+
537
+ if regression_test_file:
538
+ with open(regression_test_file, "r") as file:
539
+ for line in file:
540
+ json_obj = json.loads(line.strip())
541
+ instance_id = json_obj["instance_id"]
542
+ test = json_obj["tests_passing_in_original_repo"]
543
+ instance_test_dict[instance_id] = test
544
+
545
+ no_f2p_instances = []
546
+ for instance in instances:
547
+ revised_instance = instance
548
+ revised_instance["FAIL_TO_PASS"] = "[]"
549
+ # DO NOT USE any of the PASS_TO_PASS in swebench
550
+ # it is either obtained from all passing tests (after LLM filtering)
551
+ # or all tests are ran
552
+ if regression_test_file:
553
+ revised_instance["PASS_TO_PASS"] = instance_test_dict[
554
+ instance["instance_id"]
555
+ ]
556
+ else:
557
+ revised_instance["PASS_TO_PASS"] = "[]"
558
+
559
+ no_f2p_instances.append(revised_instance)
560
+
561
+ test_specs = list(map(make_regression_spec, no_f2p_instances))
562
+
563
+ test_specs = rearrange_patches(test_specs)
564
+
565
+ instance_image_ids = {x.instance_image_key for x in test_specs}
566
+ existing_images = {
567
+ tag
568
+ for i in client.images.list(all=True)
569
+ for tag in i.tags
570
+ if tag in instance_image_ids
571
+ }
572
+ print(f"Found {len(existing_images)} existing instance images. Will reuse them.")
573
+
574
+ # Load in previously evaluated results
575
+ resolved_dict = extract_resolved_info(
576
+ os.path.join("logs", "run_evaluation", run_id, "test")
577
+ )
578
+
579
+ if instances_to_run:
580
+ ids = instances_to_run
581
+ else:
582
+ ids = [
583
+ test_spec.instance_id
584
+ for test_spec in test_specs
585
+ if test_spec.instance_id not in list(resolved_dict.keys())
586
+ ]
587
+
588
+ results = {}
589
+
590
+ # Set the empty instances as not resolving the issue
591
+ for index, patch in enumerate(model_patches):
592
+ if patch == "":
593
+ resolved_dict[instance_ids[index]] = False
594
+
595
+ with tqdm(total=len(ids), smoothing=0, colour="MAGENTA") as pbar:
596
+ with ThreadPoolExecutor(max_workers=max_workers) as executor:
597
+ # Create a future for running each instance
598
+ futures = {
599
+ executor.submit(
600
+ run_instance,
601
+ test_spec,
602
+ predictions[test_spec.instance_id],
603
+ False, # do not remove them.
604
+ force_rebuild,
605
+ client,
606
+ run_id,
607
+ timeout,
608
+ ): None
609
+ for test_spec in test_specs
610
+ if test_spec.instance_id in ids
611
+ }
612
+ # Wait for each future to complete
613
+ for future in as_completed(futures):
614
+ pbar.update(1)
615
+ result = future.result()
616
+ if result:
617
+ instance_id = result[0]
618
+ resolved = result[1][instance_id]["resolved"]
619
+ resolved_dict[instance_id] = resolved
620
+ try:
621
+ # Update progress bar, check if instance ran successfully
622
+ future.result()
623
+ except Exception as e:
624
+ traceback.print_exc()
625
+ results[instance_id] = False # Or handle the error case as needed
626
+ resolved_dict[instance_id] = False
627
+ continue
628
+
629
+ print("All instances run.")
630
+ return resolved_dict
Repos/HWE/agents/Agentless/agentless/test/select_regression_tests.py ADDED
@@ -0,0 +1,220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import json
3
+ import os
4
+
5
+ from datasets import load_dataset
6
+ from tqdm import tqdm
7
+
8
+ from agentless.util.api_requests import num_tokens_from_messages
9
+ from agentless.util.model import make_model
10
+ from agentless.util.utils import load_jsonl, setup_logger
11
+
12
+ MAX_CONTEXT_LENGTH = 128000
13
+
14
+
15
+ select_tests_prompt_template = """
16
+ We are currently solving the following issue within our repository. Here is the issue text:
17
+ --- BEGIN ISSUE ---
18
+ {problem_statement}
19
+ --- END ISSUE ---
20
+
21
+ Below are a list of existing tests in the repository.
22
+ ```
23
+ {passing_tests}
24
+ ```
25
+
26
+ Please identify the tests that should not be run after applying the patch to fix the issue.
27
+ These tests should be excluded as the original functionality may change due to the patch.
28
+
29
+ ### Example
30
+ ```
31
+ test1
32
+ test2
33
+ test5
34
+ ```
35
+ Return only the selected tests.
36
+ """
37
+
38
+
39
+ def select_test(instance_id, args, swe_bench_data, prev_o, passing_tests):
40
+ def _parse_model_return_lines(content: str) -> list[str]:
41
+ if content:
42
+ return content.strip().split("\n")
43
+
44
+ if args.target_id is not None:
45
+ if args.target_id != instance_id:
46
+ return
47
+
48
+ log_file = os.path.join(
49
+ args.output_folder, "select_test_logs", f"{instance_id}.log"
50
+ )
51
+ logger = setup_logger(log_file)
52
+ found = False
53
+ for o in prev_o:
54
+ if o["instance_id"] == instance_id:
55
+ found = True
56
+ break
57
+
58
+ if found:
59
+ logger.info(f"skipping {instance_id}")
60
+ return None
61
+
62
+ if len(passing_tests) == 0:
63
+ with open(args.output_file, "a") as f:
64
+ f.write(
65
+ json.dumps(
66
+ {
67
+ "instance_id": instance_id,
68
+ "raw_output": "",
69
+ "tests_passing_in_original_repo": passing_tests,
70
+ "original_regressions": passing_tests,
71
+ "traj": {},
72
+ }
73
+ )
74
+ + "\n"
75
+ )
76
+ return
77
+
78
+ logger.info(f"================ selecting test for {instance_id} ================")
79
+
80
+ bench_data = [x for x in swe_bench_data if x["instance_id"] == instance_id][0]
81
+ problem_statement = bench_data["problem_statement"]
82
+
83
+ raw_output = ""
84
+
85
+ prompt_template = select_tests_prompt_template
86
+ message = prompt_template.format(
87
+ problem_statement=problem_statement, passing_tests="\n".join(passing_tests)
88
+ ).strip()
89
+
90
+ logger.info(f"prompting with message:\n{message}")
91
+
92
+ # get greedy sample
93
+ model = make_model(
94
+ model=args.model,
95
+ logger=logger,
96
+ backend=args.backend,
97
+ max_tokens=1024,
98
+ temperature=0,
99
+ batch_size=1,
100
+ )
101
+
102
+ def message_too_long(message):
103
+ return num_tokens_from_messages(message, args.model) >= MAX_CONTEXT_LENGTH
104
+
105
+ while message_too_long(message):
106
+ # half it
107
+ # TODO: we can prompt the model multiple times to select from different subset of tests
108
+ passing_tests = passing_tests[: len(passing_tests) // 2]
109
+ message = prompt_template.format(
110
+ problem_statement=problem_statement, passing_tests="\n".join(passing_tests)
111
+ ).strip()
112
+
113
+ greedy_traj = model.codegen(message, num_samples=1)[0]
114
+ greedy_traj["prompt"] = message
115
+ raw_output = greedy_traj["response"]
116
+
117
+ logger.info(raw_output)
118
+
119
+ model_identified_tests = _parse_model_return_lines(raw_output)
120
+ subset_regression_tests = []
121
+
122
+ for x in passing_tests:
123
+ if x not in model_identified_tests:
124
+ subset_regression_tests.append(x)
125
+
126
+ with open(args.output_file, "a") as f:
127
+ f.write(
128
+ json.dumps(
129
+ {
130
+ "instance_id": instance_id,
131
+ "raw_output": raw_output,
132
+ "tests_passing_in_original_repo": subset_regression_tests,
133
+ "original_regressions": passing_tests,
134
+ "traj": greedy_traj,
135
+ }
136
+ )
137
+ + "\n"
138
+ )
139
+
140
+
141
+ def select_tests(args):
142
+ with open(f"{args.output_folder}/args.json", "w") as f:
143
+ json.dump(vars(args), f, indent=4)
144
+
145
+ instance_test_dict = {}
146
+ with open(args.passing_tests, "r") as file:
147
+ for line in file:
148
+ json_obj = json.loads(line.strip())
149
+ instance_id = json_obj["instance_id"]
150
+ test = json_obj["tests_passing_in_original_repo"]
151
+ instance_test_dict[instance_id] = test
152
+
153
+ swe_bench_data = load_dataset(args.dataset, split="test")
154
+ instance_ids = (
155
+ swe_bench_data["instance_id"]
156
+ if args.instance_ids is None
157
+ else args.instance_ids
158
+ )
159
+ prev_o = load_jsonl(args.output_file) if os.path.exists(args.output_file) else []
160
+
161
+ results = []
162
+
163
+ for instance_id in tqdm(instance_ids, total=len(instance_ids), colour="MAGENTA"):
164
+ result = select_test(
165
+ instance_id, args, swe_bench_data, prev_o, instance_test_dict[instance_id]
166
+ )
167
+ if result is not None:
168
+ results.append(result)
169
+
170
+
171
+ def main():
172
+ parser = argparse.ArgumentParser()
173
+ parser.add_argument(
174
+ "--model",
175
+ type=str,
176
+ default=os.getenv("AGENTLESS_MODEL", "gpt-5.2"),
177
+ help="Model name (defaults to $AGENTLESS_MODEL).",
178
+ )
179
+ parser.add_argument(
180
+ "--backend",
181
+ type=str,
182
+ default="openai",
183
+ choices=["openai", "deepseek", "anthropic"],
184
+ )
185
+ parser.add_argument("--output_folder", type=str, required=True)
186
+ parser.add_argument("--target_id", type=str)
187
+ parser.add_argument(
188
+ "--mock", action="store_true", help="Mock run to compute prompt tokens."
189
+ )
190
+ parser.add_argument(
191
+ "--dataset",
192
+ type=str,
193
+ default="princeton-nlp/SWE-bench_Lite",
194
+ choices=["princeton-nlp/SWE-bench_Lite", "princeton-nlp/SWE-bench_Verified"],
195
+ )
196
+ parser.add_argument(
197
+ "--instance_ids",
198
+ nargs="+",
199
+ type=str,
200
+ help="Instance IDs to run (space separated), if not provided, all instances will be run",
201
+ )
202
+ parser.add_argument("--passing_tests", type=str, required=True)
203
+
204
+ args = parser.parse_args()
205
+
206
+ assert (not "deepseek" in args.model) or (
207
+ args.backend == "deepseek"
208
+ ), "Must specify `--backend deepseek` if using a DeepSeek model"
209
+
210
+ if not os.path.exists(args.output_folder):
211
+ os.makedirs(args.output_folder)
212
+ if not os.path.exists(os.path.join(args.output_folder, "select_test_logs")):
213
+ os.makedirs(os.path.join(args.output_folder, "select_test_logs"))
214
+
215
+ args.output_file = os.path.join(args.output_folder, "output.jsonl")
216
+ select_tests(args)
217
+
218
+
219
+ if __name__ == "__main__":
220
+ main()
Repos/HWE/agents/Agentless/agentless/util/api_requests.py ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import time
3
+ from typing import Dict, Union
4
+
5
+ import anthropic
6
+ import openai
7
+ import tiktoken
8
+
9
+
10
+ DEFAULT_AGENTLESS_MODEL = os.getenv("AGENTLESS_MODEL", "gpt-5.2")
11
+
12
+
13
+ def _resolve_model_name(model: Union[str, None]) -> str:
14
+ return model or os.getenv("AGENTLESS_MODEL", DEFAULT_AGENTLESS_MODEL)
15
+
16
+
17
+ def num_tokens_from_messages(message, model: Union[str, None] = None):
18
+ """Returns the number of tokens used by a list of messages."""
19
+ model = _resolve_model_name(model)
20
+ try:
21
+ encoding = tiktoken.encoding_for_model(model)
22
+ except KeyError:
23
+ encoding = tiktoken.get_encoding("cl100k_base")
24
+ if isinstance(message, list):
25
+ # use last message.
26
+ num_tokens = len(encoding.encode(message[0]["content"]))
27
+ else:
28
+ num_tokens = len(encoding.encode(message))
29
+ return num_tokens
30
+
31
+
32
+ def create_chatgpt_config(
33
+ message: Union[str, list],
34
+ max_tokens: int,
35
+ temperature: float = 1,
36
+ batch_size: int = 1,
37
+ system_message: str = "You are a helpful assistant.",
38
+ model: Union[str, None] = None,
39
+ ) -> Dict:
40
+ model = _resolve_model_name(model)
41
+ if isinstance(message, list):
42
+ config = {
43
+ "model": model,
44
+ "max_tokens": max_tokens,
45
+ "temperature": temperature,
46
+ "n": batch_size,
47
+ "messages": [{"role": "system", "content": system_message}] + message,
48
+ }
49
+ else:
50
+ config = {
51
+ "model": model,
52
+ "max_tokens": max_tokens,
53
+ "temperature": temperature,
54
+ "n": batch_size,
55
+ "messages": [
56
+ {"role": "system", "content": system_message},
57
+ {"role": "user", "content": message},
58
+ ],
59
+ }
60
+ return config
61
+
62
+
63
+ def handler(signum, frame):
64
+ # swallow signum and frame
65
+ raise Exception("end of time")
66
+
67
+
68
+ def request_chatgpt_engine(config, logger, base_url="https://api.openai.com/v1", max_retries=40, timeout=100):
69
+ ret = None
70
+ retries = 0
71
+ last_exception = None
72
+
73
+ base_url = os.getenv("OPENAI_API_BASE", base_url)
74
+
75
+ client = openai.OpenAI(base_url=base_url)
76
+
77
+ while ret is None and retries < max_retries:
78
+ try:
79
+ # Attempt to get the completion
80
+ logger.info("Creating API request")
81
+
82
+ ret = client.chat.completions.create(**config)
83
+
84
+ except openai.OpenAIError as e:
85
+ last_exception = e
86
+ if isinstance(e, openai.BadRequestError):
87
+ logger.info("Request invalid")
88
+ print(e)
89
+ logger.info(e)
90
+ raise Exception("Invalid API Request")
91
+ elif isinstance(e, openai.RateLimitError):
92
+ print("Rate limit exceeded. Waiting...")
93
+ logger.info("Rate limit exceeded. Waiting...")
94
+ print(e)
95
+ logger.info(e)
96
+ time.sleep(5)
97
+ elif isinstance(e, openai.APIConnectionError):
98
+ print("API connection error. Waiting...")
99
+ logger.info("API connection error. Waiting...")
100
+ print(e)
101
+ logger.info(e)
102
+ time.sleep(5)
103
+ else:
104
+ print("Unknown error. Waiting...")
105
+ logger.info("Unknown error. Waiting...")
106
+ print(e)
107
+ logger.info(e)
108
+ time.sleep(1)
109
+ except Exception as e:
110
+ last_exception = e
111
+ logger.exception("Unexpected exception during API request")
112
+ time.sleep(1)
113
+
114
+ retries += 1
115
+
116
+ if ret is None:
117
+ if last_exception is not None:
118
+ logger.error(
119
+ "API request failed after %s retries; last error: %s",
120
+ retries,
121
+ repr(last_exception),
122
+ )
123
+ else:
124
+ logger.error("API request failed after %s retries with no response.", retries)
125
+ logger.info(f"API response {ret}")
126
+ return ret
127
+
128
+
129
+ def create_anthropic_config(
130
+ message: str,
131
+ max_tokens: int,
132
+ temperature: float = 1,
133
+ batch_size: int = 1,
134
+ system_message: str = "You are a helpful assistant.",
135
+ model: Union[str, None] = None,
136
+ tools: list = None,
137
+ ) -> Dict:
138
+ model = _resolve_model_name(model)
139
+ if isinstance(message, list):
140
+ config = {
141
+ "model": model,
142
+ "temperature": temperature,
143
+ "max_tokens": max_tokens,
144
+ "messages": message,
145
+ }
146
+ else:
147
+ config = {
148
+ "model": model,
149
+ "temperature": temperature,
150
+ "max_tokens": max_tokens,
151
+ "messages": [
152
+ {"role": "user", "content": [{"type": "text", "text": message}]},
153
+ ],
154
+ }
155
+
156
+ if tools:
157
+ config["tools"] = tools
158
+
159
+ return config
160
+
161
+
162
+ def request_anthropic_engine(
163
+ config, logger, max_retries=40, timeout=500, prompt_cache=False
164
+ ):
165
+ ret = None
166
+ retries = 0
167
+
168
+ client = anthropic.Anthropic()
169
+
170
+ while ret is None and retries < max_retries:
171
+ try:
172
+ start_time = time.time()
173
+ if prompt_cache:
174
+ # following best practice to cache mainly the reused content at the beginning
175
+ # this includes any tools, system messages (which is already handled since we try to cache the first message)
176
+ config["messages"][0]["content"][0]["cache_control"] = {
177
+ "type": "ephemeral"
178
+ }
179
+ ret = client.beta.prompt_caching.messages.create(**config)
180
+ else:
181
+ ret = client.messages.create(**config)
182
+ except Exception as e:
183
+ logger.error("Unknown error. Waiting...", exc_info=True)
184
+ # Check if the timeout has been exceeded
185
+ if time.time() - start_time >= timeout:
186
+ logger.warning("Request timed out. Retrying...")
187
+ else:
188
+ logger.warning("Retrying after an unknown error...")
189
+ time.sleep(10 * retries)
190
+ retries += 1
191
+
192
+ return ret
Repos/HWE/agents/Agentless/agentless/util/compress_file.py ADDED
@@ -0,0 +1,220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+
3
+ import libcst as cst
4
+ import libcst.matchers as m
5
+
6
+
7
+ class CompressTransformer(cst.CSTTransformer):
8
+ DESCRIPTION = str = "Replaces function body with ..."
9
+ replacement_string = '"__FUNC_BODY_REPLACEMENT_STRING__"'
10
+
11
+ def __init__(self, keep_constant=True, keep_indent=False):
12
+ self.keep_constant = keep_constant
13
+ self.keep_indent = keep_indent
14
+
15
+ def leave_Module(
16
+ self, original_node: cst.Module, updated_node: cst.Module
17
+ ) -> cst.Module:
18
+ new_body = [
19
+ stmt
20
+ for stmt in updated_node.body
21
+ if m.matches(stmt, m.ClassDef())
22
+ or m.matches(stmt, m.FunctionDef())
23
+ or (
24
+ self.keep_constant
25
+ and m.matches(stmt, m.SimpleStatementLine())
26
+ and m.matches(stmt.body[0], m.Assign())
27
+ )
28
+ ]
29
+ return updated_node.with_changes(body=new_body)
30
+
31
+ def leave_ClassDef(
32
+ self, original_node: cst.ClassDef, updated_node: cst.ClassDef
33
+ ) -> cst.ClassDef:
34
+ # Remove docstring in the class body
35
+ new_body = [
36
+ stmt
37
+ for stmt in updated_node.body.body
38
+ if not (
39
+ m.matches(stmt, m.SimpleStatementLine())
40
+ and m.matches(stmt.body[0], m.Expr())
41
+ and m.matches(stmt.body[0].value, m.SimpleString())
42
+ )
43
+ ]
44
+ return updated_node.with_changes(body=cst.IndentedBlock(body=new_body))
45
+
46
+ def leave_FunctionDef(
47
+ self, original_node: cst.FunctionDef, updated_node: cst.FunctionDef
48
+ ) -> cst.CSTNode:
49
+ if not self.keep_indent:
50
+ # replace with unindented statement
51
+ new_expr = cst.Expr(value=cst.SimpleString(value=self.replacement_string))
52
+ new_body = cst.IndentedBlock((new_expr,))
53
+ return updated_node.with_changes(body=new_body)
54
+ else:
55
+ # replace with indented statement
56
+ # new_expr = [cst.Pass()]
57
+ new_expr = [
58
+ cst.Expr(value=cst.SimpleString(value=self.replacement_string)),
59
+ ]
60
+ return updated_node.with_changes(
61
+ body=cst.IndentedBlock(body=[cst.SimpleStatementLine(body=new_expr)])
62
+ )
63
+
64
+
65
+ class GlobalVariableVisitor(cst.CSTVisitor):
66
+ METADATA_DEPENDENCIES = (cst.metadata.PositionProvider,)
67
+
68
+ def __init__(self):
69
+ self.assigns = []
70
+
71
+ def leave_Assign(self, original_node: cst.Module) -> list:
72
+ stmt = original_node
73
+ start_pos = self.get_metadata(cst.metadata.PositionProvider, stmt).start
74
+ end_pos = self.get_metadata(cst.metadata.PositionProvider, stmt).end
75
+ self.assigns.append([stmt, start_pos, end_pos])
76
+
77
+
78
+ code = """
79
+ \"\"\"
80
+ this is a module
81
+ ...
82
+ \"\"\"
83
+ const = {1,2,3}
84
+ import os
85
+
86
+ class fooClass:
87
+ '''this is a class'''
88
+
89
+ def __init__(self, x):
90
+ '''initialization.'''
91
+ self.x = x
92
+
93
+ def print(self):
94
+ print(self.x)
95
+
96
+ large_var = {
97
+ 1: 2,
98
+ 2: 3,
99
+ 3: 4,
100
+ 4: 5,
101
+ 5: 6,
102
+ 6: 7,
103
+ 7: 8,
104
+ 8: 9,
105
+ 9: 10,
106
+ 10: 11,
107
+ 11: 12,
108
+ 12: 13,
109
+ 13: 14,
110
+ 14: 15,
111
+ 15: 16,
112
+ 16: 17,
113
+ 17: 18,
114
+ 18: 19,
115
+ 19: 20,
116
+ 20: 21,
117
+ }
118
+
119
+ def test():
120
+ a = fooClass(3)
121
+ a.print()
122
+
123
+ """
124
+
125
+
126
+ def remove_lines(raw_code, remove_line_intervals):
127
+ # TODO: speed up this function
128
+ # remove_line_intervals.sort()
129
+
130
+ # Remove lines
131
+ new_code = ""
132
+ for i, line in enumerate(raw_code.splitlines()):
133
+ # intervals are one-based
134
+ if not any(start <= i + 1 <= end for start, end in remove_line_intervals):
135
+ new_code += line + "\n"
136
+ if any(start == i + 1 for start, _ in remove_line_intervals):
137
+ new_code += "...\n"
138
+ return new_code
139
+
140
+
141
+ def compress_assign_stmts(raw_code, total_lines=30, prefix_lines=10, suffix_lines=10):
142
+ try:
143
+ tree = cst.parse_module(raw_code)
144
+ except Exception as e:
145
+ print(e.__class__.__name__, e)
146
+ return raw_code
147
+
148
+ wrapper = cst.metadata.MetadataWrapper(tree)
149
+ visitor = GlobalVariableVisitor()
150
+ wrapper.visit(visitor)
151
+
152
+ remove_line_intervals = []
153
+ for stmt in visitor.assigns:
154
+ if stmt[2].line - stmt[1].line > total_lines:
155
+ remove_line_intervals.append(
156
+ (stmt[1].line + prefix_lines, stmt[2].line - suffix_lines)
157
+ )
158
+ return remove_lines(raw_code, remove_line_intervals)
159
+
160
+
161
+ def get_skeleton(
162
+ raw_code,
163
+ keep_constant: bool = True,
164
+ keep_indent: bool = False,
165
+ compress_assign: bool = False,
166
+ total_lines=30,
167
+ prefix_lines=10,
168
+ suffix_lines=10,
169
+ ):
170
+ try:
171
+ tree = cst.parse_module(raw_code)
172
+ except:
173
+ return raw_code
174
+
175
+ transformer = CompressTransformer(keep_constant=keep_constant, keep_indent=True)
176
+ modified_tree = tree.visit(transformer)
177
+ code = modified_tree.code
178
+
179
+ if compress_assign:
180
+ code = compress_assign_stmts(
181
+ code,
182
+ total_lines=total_lines,
183
+ prefix_lines=prefix_lines,
184
+ suffix_lines=suffix_lines,
185
+ )
186
+
187
+ if keep_indent:
188
+ code = code.replace(CompressTransformer.replacement_string + "\n", "...\n")
189
+ code = code.replace(CompressTransformer.replacement_string, "...\n")
190
+ else:
191
+ pattern = f"\\n[ \\t]*{CompressTransformer.replacement_string}"
192
+ replacement = "\n..."
193
+ code = re.sub(pattern, replacement, code)
194
+
195
+ return code
196
+
197
+
198
+ def test_compress():
199
+ skeleton = get_skeleton(code, True)
200
+ print(skeleton)
201
+
202
+
203
+ def test_compress_var():
204
+ print("LOC: ", len(code.split("\n")))
205
+ skeleton = get_skeleton(
206
+ code,
207
+ True,
208
+ keep_indent=False,
209
+ compress_assign=True,
210
+ total_lines=10,
211
+ prefix_lines=5,
212
+ suffix_lines=5,
213
+ )
214
+ print(skeleton)
215
+ print("LOC: ", len(skeleton.split("\n")))
216
+
217
+
218
+ if __name__ == "__main__":
219
+ # test_compress()
220
+ test_compress_var()
Repos/HWE/agents/Agentless/agentless/util/index_skeleton.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import libcst as cst
2
+ import libcst.matchers as m
3
+
4
+
5
+ class GlobalVisitor(cst.CSTVisitor):
6
+ METADATA_DEPENDENCIES = (cst.metadata.PositionProvider,)
7
+
8
+ def __init__(self):
9
+ # includes both imports and assigns
10
+ self.global_stmt = []
11
+ self.global_imports = []
12
+
13
+ def leave_Module(self, original_node: cst.Module) -> list:
14
+ for stmt in original_node.body:
15
+ if m.matches(stmt, m.SimpleStatementLine()) and (
16
+ m.matches(stmt.body[0], m.Assign())
17
+ ):
18
+ expr = cst.parse_module("").code_for_node(stmt).strip()
19
+ self.global_stmt.append(expr)
20
+
21
+ if m.matches(stmt, m.SimpleStatementLine()) and (
22
+ m.matches(stmt.body[0], m.Import())
23
+ or m.matches(stmt.body[0], m.ImportFrom())
24
+ ):
25
+ expr = cst.parse_module("").code_for_node(stmt).strip()
26
+ self.global_imports.append(expr)
27
+
28
+
29
+ def parse_global_stmt_from_code(file_content: str) -> tuple[str, str]:
30
+ """Parse global variables."""
31
+ try:
32
+ tree = cst.parse_module(file_content)
33
+ wrapper = cst.metadata.MetadataWrapper(tree)
34
+ visitor = GlobalVisitor()
35
+ wrapper.visit(visitor)
36
+
37
+ return "\n".join(visitor.global_stmt), "\n".join(visitor.global_imports)
38
+ except:
39
+ return "", ""
40
+
41
+
42
+ code = """
43
+ \"\"\"
44
+ this is a module
45
+ ...
46
+ \"\"\"
47
+ const = {1,2,3}
48
+ import os
49
+ from ds import get
50
+ from ds import *
51
+ class fooClass:
52
+ '''this is a class'''
53
+
54
+ def __init__(self, x):
55
+ '''initialization.'''
56
+ self.x = x
57
+
58
+ def print(self):
59
+ print(self.x)
60
+
61
+ def test():
62
+ a = fooClass(3)
63
+ a.print()
64
+ """
65
+
66
+
67
+ def test_parse():
68
+ global_stmt = parse_global_stmt_from_code(code)
69
+ print(global_stmt)
70
+
71
+
72
+ if __name__ == "__main__":
73
+ test_parse()
Repos/HWE/agents/Agentless/agentless/util/model.py ADDED
@@ -0,0 +1,421 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from abc import ABC, abstractmethod
3
+ from typing import List
4
+
5
+ from agentless.util.api_requests import (
6
+ create_anthropic_config,
7
+ create_chatgpt_config,
8
+ request_anthropic_engine,
9
+ request_chatgpt_engine,
10
+ )
11
+
12
+
13
+ class DecoderBase(ABC):
14
+ def __init__(
15
+ self,
16
+ name: str,
17
+ logger,
18
+ batch_size: int = 1,
19
+ temperature: float = 0.8,
20
+ max_new_tokens: int = 1024,
21
+ ) -> None:
22
+ logger.info("Initializing a decoder model: {} ...".format(name))
23
+ self.name = name
24
+ self.logger = logger
25
+ self.batch_size = batch_size
26
+ self.temperature = temperature
27
+ self.max_new_tokens = max_new_tokens
28
+
29
+ @abstractmethod
30
+ def codegen(
31
+ self, message: str, num_samples: int = 1, prompt_cache: bool = False
32
+ ) -> List[dict]:
33
+ pass
34
+
35
+ @abstractmethod
36
+ def is_direct_completion(self) -> bool:
37
+ pass
38
+
39
+ def __repr__(self) -> str:
40
+ return self.name
41
+
42
+ def __str__(self) -> str:
43
+ return self.name
44
+
45
+
46
+ class OpenAIChatDecoder(DecoderBase):
47
+ def __init__(self, name: str, logger, **kwargs) -> None:
48
+ super().__init__(name, logger, **kwargs)
49
+
50
+ def codegen(
51
+ self, message: str, num_samples: int = 1, prompt_cache: bool = False
52
+ ) -> List[dict]:
53
+ if self.temperature == 0:
54
+ assert num_samples == 1
55
+ batch_size = min(self.batch_size, num_samples)
56
+
57
+ config = create_chatgpt_config(
58
+ message=message,
59
+ max_tokens=self.max_new_tokens,
60
+ temperature=self.temperature,
61
+ batch_size=batch_size,
62
+ model=self.name,
63
+ )
64
+ ret = request_chatgpt_engine(config, self.logger)
65
+ if ret:
66
+ responses = [choice.message.content for choice in ret.choices]
67
+ completion_tokens = ret.usage.completion_tokens
68
+ prompt_tokens = ret.usage.prompt_tokens
69
+ else:
70
+ self.logger.error("No API response returned; see prior logs for errors.")
71
+ responses = [""]
72
+ completion_tokens = 0
73
+ prompt_tokens = 0
74
+
75
+ # The nice thing is, when we generate multiple samples from the same input (message),
76
+ # the input tokens are only charged once according to openai API.
77
+ # Therefore, we assume the request cost is only counted for the first sample.
78
+ # More specifically, the `prompt_tokens` is for one input message,
79
+ # and the `completion_tokens` is the sum of all returned completions.
80
+ # Therefore, for the second and later samples, the cost is zero.
81
+ trajs = [
82
+ {
83
+ "response": responses[0],
84
+ "usage": {
85
+ "completion_tokens": completion_tokens,
86
+ "prompt_tokens": prompt_tokens,
87
+ },
88
+ }
89
+ ]
90
+ for response in responses[1:]:
91
+ trajs.append(
92
+ {
93
+ "response": response,
94
+ "usage": {
95
+ "completion_tokens": 0,
96
+ "prompt_tokens": 0,
97
+ },
98
+ }
99
+ )
100
+ return trajs
101
+
102
+ def is_direct_completion(self) -> bool:
103
+ return False
104
+
105
+
106
+ class AnthropicChatDecoder(DecoderBase):
107
+ def __init__(self, name: str, logger, **kwargs) -> None:
108
+ super().__init__(name, logger, **kwargs)
109
+
110
+ _STR_REPLACE_EDITOR_DESCRIPTION = """Custom editing tool for editing files
111
+ * State is persistent across command calls and discussions with the user
112
+
113
+ Notes for using the `str_replace` command:
114
+ * The `old_str` parameter should match EXACTLY one or more consecutive lines from the original file. Be mindful of whitespaces!
115
+ * If the `old_str` parameter is not unique in the file, the replacement will not be performed. Make sure to include enough context in `old_str` to make it unique
116
+ * The `new_str` parameter should contain the edited lines that should replace the `old_str`
117
+ """
118
+
119
+ _USER_REPLY_EDIT_MESSAGE = """File is successfully edited"""
120
+
121
+ tools = [
122
+ {
123
+ "name": "str_replace_editor",
124
+ "description": _STR_REPLACE_EDITOR_DESCRIPTION,
125
+ "input_schema": {
126
+ "type": "object",
127
+ "properties": {
128
+ "path": {
129
+ "description": "Full path to file, e.g. `folder/file.py`.",
130
+ "type": "string",
131
+ },
132
+ "old_str": {
133
+ "description": "Required parameter containing the string in `path` to replace.",
134
+ "type": "string",
135
+ },
136
+ "new_str": {
137
+ "description": "Optional parameter containing the new string (if not given, no string will be added).",
138
+ "type": "string",
139
+ },
140
+ },
141
+ "required": ["path", "old_str"],
142
+ },
143
+ }
144
+ ]
145
+
146
+ MAX_CODEGEN_ITERATIONS = 10
147
+
148
+ # specialized codegen with tool
149
+ def codegen_w_tool(
150
+ self, message: str, num_samples: int = 1, prompt_cache: bool = False
151
+ ) -> List[dict]:
152
+ def _build_response_and_extract(response, messages, iter):
153
+ json_response = response.to_dict()
154
+
155
+ contains_tool = False
156
+ # formulate the messages
157
+ json_response.pop("id")
158
+ json_response.pop("model")
159
+ json_response.pop("stop_reason")
160
+ json_response.pop("stop_sequence")
161
+ json_response.pop("type")
162
+ json_response.pop("usage")
163
+
164
+ messages.append(json_response)
165
+
166
+ response_content = []
167
+
168
+ for json_message in json_response["content"]:
169
+ if json_message["type"] == "tool_use":
170
+ contains_tool = True
171
+ # each tool use requires a response
172
+ response_content.append(
173
+ {
174
+ "type": "tool_result",
175
+ "tool_use_id": json_message["id"],
176
+ "content": self._USER_REPLY_EDIT_MESSAGE,
177
+ }
178
+ )
179
+
180
+ if contains_tool:
181
+ messages.append(
182
+ {
183
+ "role": "user",
184
+ "content": response_content,
185
+ }
186
+ )
187
+ else:
188
+ if iter == 0:
189
+ # if the first iteration does not contain the tool, likely the model is doing some CoT for debugging
190
+ # append encouraging message
191
+ messages.append(
192
+ {
193
+ "role": "user",
194
+ "content": [
195
+ {
196
+ "type": "text",
197
+ "text": "Please generate editing commands to fix the issue",
198
+ }
199
+ ],
200
+ }
201
+ )
202
+ contains_tool = True
203
+
204
+ return messages, contains_tool
205
+
206
+ if self.temperature == 0:
207
+ assert num_samples == 1
208
+
209
+ trajs = []
210
+ for _ in range(num_samples):
211
+ self.logger.info(f" === Generating ====")
212
+ # initialized the traj
213
+ traj = {
214
+ "response": [],
215
+ "usage": {
216
+ "completion_tokens": 0,
217
+ "prompt_tokens": 0,
218
+ "cache_creation_token": 0,
219
+ "cache_read_input_tokens": 0,
220
+ },
221
+ }
222
+
223
+ # create the initial config and messages
224
+ messages = [
225
+ {"role": "user", "content": [{"type": "text", "text": message}]}
226
+ ]
227
+
228
+ for iteration in range(self.MAX_CODEGEN_ITERATIONS):
229
+ config = create_anthropic_config(
230
+ message=messages,
231
+ max_tokens=self.max_new_tokens,
232
+ temperature=self.temperature,
233
+ batch_size=1,
234
+ model=self.name,
235
+ tools=self.tools,
236
+ )
237
+ ret = request_anthropic_engine(
238
+ config,
239
+ self.logger,
240
+ prompt_cache=True, # prompt cache should be always true as we at least should query twice
241
+ )
242
+
243
+ if ret:
244
+ # add the response to the traj
245
+ traj["response"].append([reply.to_dict() for reply in ret.content])
246
+
247
+ # pretty dump the response
248
+ for reply in ret.content:
249
+ self.logger.info(json.dumps(reply.to_dict(), indent=2))
250
+
251
+ # update the usage
252
+ traj["usage"]["completion_tokens"] += ret.usage.output_tokens
253
+ traj["usage"]["prompt_tokens"] += ret.usage.input_tokens
254
+ traj["usage"][
255
+ "cache_creation_token"
256
+ ] += ret.usage.cache_creation_input_tokens
257
+ traj["usage"][
258
+ "cache_read_input_tokens"
259
+ ] += ret.usage.cache_read_input_tokens
260
+
261
+ messages, contains_tool = _build_response_and_extract(
262
+ ret, messages, iteration
263
+ )
264
+
265
+ if not contains_tool:
266
+ break
267
+ else:
268
+ assert (
269
+ False
270
+ ), "No response from the engine" # this should not happen
271
+
272
+ if ret:
273
+ trajs.append(traj)
274
+ else:
275
+ trajs.append(
276
+ {
277
+ "response": "",
278
+ "usage": {
279
+ "completion_tokens": 0,
280
+ "prompt_tokens": 0,
281
+ },
282
+ }
283
+ )
284
+
285
+ return trajs
286
+
287
+ def codegen(
288
+ self, message: str, num_samples: int = 1, prompt_cache: bool = False
289
+ ) -> List[dict]:
290
+ if self.temperature == 0:
291
+ assert num_samples == 1
292
+
293
+ trajs = []
294
+ for _ in range(num_samples):
295
+ config = create_anthropic_config(
296
+ message=message,
297
+ max_tokens=self.max_new_tokens,
298
+ temperature=self.temperature,
299
+ batch_size=1,
300
+ model=self.name,
301
+ )
302
+ ret = request_anthropic_engine(
303
+ config, self.logger, prompt_cache=prompt_cache
304
+ )
305
+
306
+ if ret:
307
+ trajs.append(
308
+ {
309
+ "response": ret.content[0].text,
310
+ "usage": {
311
+ "completion_tokens": ret.usage.output_tokens,
312
+ "prompt_tokens": ret.usage.input_tokens,
313
+ "cache_creation_token": 0
314
+ if not prompt_cache
315
+ else ret.usage.cache_creation_input_tokens,
316
+ "cache_read_input_tokens": 0
317
+ if not prompt_cache
318
+ else ret.usage.cache_read_input_tokens,
319
+ },
320
+ }
321
+ )
322
+ else:
323
+ trajs.append(
324
+ {
325
+ "response": "",
326
+ "usage": {
327
+ "completion_tokens": 0,
328
+ "prompt_tokens": 0,
329
+ },
330
+ }
331
+ )
332
+
333
+ return trajs
334
+
335
+ def is_direct_completion(self) -> bool:
336
+ return False
337
+
338
+
339
+ class DeepSeekChatDecoder(DecoderBase):
340
+ def __init__(self, name: str, logger, **kwargs) -> None:
341
+ super().__init__(name, logger, **kwargs)
342
+
343
+ def codegen(
344
+ self, message: str, num_samples: int = 1, prompt_cache: bool = False
345
+ ) -> List[dict]:
346
+ if self.temperature == 0:
347
+ assert num_samples == 1
348
+
349
+ trajs = []
350
+ for _ in range(num_samples):
351
+ config = create_chatgpt_config(
352
+ message=message,
353
+ max_tokens=self.max_new_tokens,
354
+ temperature=self.temperature,
355
+ batch_size=1,
356
+ model=self.name,
357
+ )
358
+ ret = request_chatgpt_engine(
359
+ config, self.logger, base_url="https://api.deepseek.com"
360
+ )
361
+ if ret:
362
+ trajs.append(
363
+ {
364
+ "response": ret.choices[0].message.content,
365
+ "usage": {
366
+ "completion_tokens": ret.usage.completion_tokens,
367
+ "prompt_tokens": ret.usage.prompt_tokens,
368
+ },
369
+ }
370
+ )
371
+ else:
372
+ trajs.append(
373
+ {
374
+ "response": "",
375
+ "usage": {
376
+ "completion_tokens": 0,
377
+ "prompt_tokens": 0,
378
+ },
379
+ }
380
+ )
381
+
382
+ return trajs
383
+
384
+ def is_direct_completion(self) -> bool:
385
+ return False
386
+
387
+
388
+ def make_model(
389
+ model: str,
390
+ backend: str,
391
+ logger,
392
+ batch_size: int = 1,
393
+ max_tokens: int = 1024,
394
+ temperature: float = 0.0,
395
+ ):
396
+ if backend == "openai":
397
+ return OpenAIChatDecoder(
398
+ name=model,
399
+ logger=logger,
400
+ batch_size=batch_size,
401
+ max_new_tokens=max_tokens,
402
+ temperature=temperature,
403
+ )
404
+ elif backend == "anthropic":
405
+ return AnthropicChatDecoder(
406
+ name=model,
407
+ logger=logger,
408
+ batch_size=batch_size,
409
+ max_new_tokens=max_tokens,
410
+ temperature=temperature,
411
+ )
412
+ elif backend == "deepseek":
413
+ return DeepSeekChatDecoder(
414
+ name=model,
415
+ logger=logger,
416
+ batch_size=batch_size,
417
+ max_new_tokens=max_tokens,
418
+ temperature=temperature,
419
+ )
420
+ else:
421
+ raise NotImplementedError
Repos/HWE/agents/Agentless/agentless/util/parse_global_var.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import libcst as cst
2
+ import libcst.matchers as m
3
+ from libcst.display import dump
4
+
5
+
6
+ class GlobalVariableVisitor(cst.CSTVisitor):
7
+ METADATA_DEPENDENCIES = (cst.metadata.PositionProvider,)
8
+
9
+ def __init__(self):
10
+ self.global_assigns = []
11
+
12
+ def leave_Module(self, original_node: cst.Module) -> list:
13
+ assigns = []
14
+ for stmt in original_node.body:
15
+ if m.matches(stmt, m.SimpleStatementLine()) and m.matches(
16
+ stmt.body[0], m.Assign()
17
+ ):
18
+ start_pos = self.get_metadata(cst.metadata.PositionProvider, stmt).start
19
+ end_pos = self.get_metadata(cst.metadata.PositionProvider, stmt).end
20
+ assigns.append([stmt, start_pos, end_pos])
21
+ self.global_assigns.extend(assigns)
22
+
23
+
24
+ def parse_global_var_from_code(file_content: str) -> dict[str, dict]:
25
+ """Parse global variables."""
26
+ try:
27
+ tree = cst.parse_module(file_content)
28
+ except:
29
+ return file_content
30
+
31
+ wrapper = cst.metadata.MetadataWrapper(tree)
32
+ visitor = GlobalVariableVisitor()
33
+ wrapper.visit(visitor)
34
+
35
+ global_assigns = {}
36
+ for assign_stmt, start_pos, end_pos in visitor.global_assigns:
37
+ for t in assign_stmt.body:
38
+ try:
39
+ targets = [t.targets[0].target.value]
40
+ except:
41
+ try:
42
+ targets = t.targets[0].target.elements
43
+ targets = [x.value.value for x in targets]
44
+ except:
45
+ targets = []
46
+ for target_var in targets:
47
+ global_assigns[target_var] = {
48
+ "start_line": start_pos.line,
49
+ "end_line": end_pos.line,
50
+ }
51
+ return global_assigns
52
+
53
+
54
+ def test_parse_global_var_from_file():
55
+ code = """
56
+ \"\"\"
57
+ this is a module
58
+ ...
59
+ \"\"\"
60
+ const_var = {1,2,3}
61
+ const_dict = {
62
+ 'day': 'Monday',
63
+ 'month': 'January',
64
+ }
65
+ a, b = 1, 2
66
+ import os
67
+
68
+ class fooClass:
69
+ '''this is a class'''
70
+
71
+ def __init__(self, x):
72
+ '''initialization.'''
73
+ self.x = x
74
+
75
+ def print(self):
76
+ print(self.x)
77
+
78
+ def test():
79
+ a = fooClass(3)
80
+ a.print()
81
+
82
+ """
83
+ res = parse_global_var_from_code(code)
84
+ assert res == {
85
+ "const_var": {"start_line": 6, "end_line": 6},
86
+ "const_dict": {"start_line": 7, "end_line": 10},
87
+ "a": {"start_line": 11, "end_line": 11},
88
+ "b": {"start_line": 11, "end_line": 11},
89
+ }
90
+
91
+
92
+ if __name__ == "__main__":
93
+ test_parse_global_var_from_file()
Repos/HWE/agents/Agentless/agentless/util/postprocess_data.py ADDED
@@ -0,0 +1,1176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import ast
2
+ import os
3
+ import re
4
+ import subprocess
5
+ import uuid
6
+ from collections import OrderedDict
7
+
8
+ from get_repo_structure.get_patch_info import parse_patch
9
+
10
+ SOURCE_EXTENSIONS = {".py", ".v", ".sv", ".vh", ".svh"}
11
+ LOC_PREFIXES = (
12
+ "line:",
13
+ "function:",
14
+ "task:",
15
+ "method:",
16
+ "class:",
17
+ "module:",
18
+ "interface:",
19
+ "package:",
20
+ "program:",
21
+ "checker:",
22
+ "config:",
23
+ "primitive:",
24
+ "udp:",
25
+ "variable:",
26
+ )
27
+
28
+
29
+ def _looks_like_verilog(code: str) -> bool:
30
+ sample = "\n".join(code.splitlines()[:50]).lower()
31
+ if "`timescale" in sample or "`include" in sample:
32
+ return True
33
+ return re.search(
34
+ r"\b(module|endmodule|interface|endinterface|package|endpackage|always_ff|always_comb|logic|wire|reg|assign)\b",
35
+ sample,
36
+ ) is not None
37
+
38
+
39
+ def _is_source_path(line, file_names):
40
+ if line in file_names:
41
+ return True
42
+ _, ext = os.path.splitext(line)
43
+ return ext.lower() in SOURCE_EXTENSIONS
44
+
45
+
46
+ def check_syntax(code):
47
+ if not isinstance(code, list):
48
+ code = [code]
49
+
50
+ for c in code:
51
+ if (
52
+ not c.strip()
53
+ ): # Check for cases where the model didn't return a python block
54
+ return False
55
+ try:
56
+ ast.parse(c)
57
+ except SyntaxError as e:
58
+ if _looks_like_verilog(c):
59
+ continue
60
+ return False
61
+ return True
62
+
63
+
64
+ def remove_empty_lines(code: str) -> str:
65
+ # Split the code into lines
66
+ lines = code.splitlines()
67
+ # Remove empty lines
68
+ filtered_lines = [line for line in lines if line.strip() != ""]
69
+ return "\n".join(filtered_lines)
70
+
71
+
72
+ def check_code_differ_by_just_empty_lines(codes, prev_codes) -> bool:
73
+
74
+ if not isinstance(codes, list):
75
+ codes = [codes]
76
+ prev_codes = [prev_codes]
77
+
78
+ normalized_code1 = ""
79
+ normalized_code2 = ""
80
+
81
+ for code, prev_code in zip(codes, prev_codes):
82
+ # Normalize both code snippets
83
+ normalized_code1 += remove_empty_lines(code)
84
+ normalized_code2 += remove_empty_lines(prev_code)
85
+
86
+ return normalized_code1 == normalized_code2
87
+
88
+
89
+ def lint_code(repo_playground, temp_name, code, prev_code="") -> tuple[bool, set, set]:
90
+
91
+ # Generate a temperary folder and add uuid to avoid collision
92
+ repo_playground = os.path.join(repo_playground, str(uuid.uuid4()))
93
+
94
+ # assert playground doesn't exist
95
+ assert not os.path.exists(repo_playground), f"{repo_playground} already exists"
96
+
97
+ # create playground
98
+ os.makedirs(repo_playground)
99
+
100
+ with open(f"{repo_playground}/{temp_name}", "w") as f:
101
+ f.write(prev_code)
102
+
103
+ # lint the code
104
+ # check for fatal errors
105
+ fatal = "E9,F821,F823,F831,F406,F407,F701,F702,F704,F706"
106
+ o = subprocess.run(
107
+ f"flake8 --select={fatal} --isolated {repo_playground}/{temp_name}",
108
+ shell=True,
109
+ capture_output=True,
110
+ )
111
+ s = o.stdout.decode("utf-8")
112
+
113
+ prev_errors = set()
114
+ if s != "":
115
+ for error in s.split(f"{repo_playground}/{temp_name}:")[1:]:
116
+ num_free_error = ":".join(error.split(":")[2:]).strip()
117
+ prev_errors.add(num_free_error)
118
+
119
+ with open(f"{repo_playground}/{temp_name}", "w") as f:
120
+ f.write(code)
121
+
122
+ o = subprocess.run(
123
+ f"flake8 --select={fatal} --isolated {repo_playground}/{temp_name}",
124
+ shell=True,
125
+ capture_output=True,
126
+ )
127
+ s = o.stdout.decode("utf-8")
128
+
129
+ # remove playground
130
+ subprocess.run(f"rm -rf {repo_playground}", shell=True)
131
+
132
+ errors = set()
133
+ if s != "":
134
+ for error in s.split(f"{repo_playground}/{temp_name}:")[1:]:
135
+ num_free_error = ":".join(error.split(":")[2:]).strip()
136
+ errors.add(num_free_error)
137
+
138
+ if len(errors - prev_errors) > 0:
139
+ return False, prev_errors, errors
140
+
141
+ return True, set(), set()
142
+
143
+
144
+ def fake_git_repo(repo_playground, file_pathes, old_contents, new_contents) -> str:
145
+ """create a fake git repo to obtain git diff format"""
146
+
147
+ if not isinstance(file_pathes, list):
148
+ # for backwards compatibility
149
+ file_pathes = [file_pathes]
150
+ old_contents = [old_contents]
151
+ new_contents = [new_contents]
152
+
153
+ # Generate a temperary folder and add uuid to avoid collision
154
+ repo_playground = os.path.join(repo_playground, str(uuid.uuid4()))
155
+
156
+ # assert playground doesn't exist
157
+ assert not os.path.exists(repo_playground), f"{repo_playground} already exists"
158
+
159
+ # create playground
160
+ os.makedirs(repo_playground)
161
+
162
+ # create a fake git repo
163
+ subprocess.run(f"cd {repo_playground} && git init", shell=True)
164
+
165
+ for file_path, old_content, new_content in zip(
166
+ file_pathes, old_contents, new_contents
167
+ ):
168
+ # create a file
169
+ subprocess.run(
170
+ f"mkdir -p {repo_playground}/{os.path.dirname(file_path)}", shell=True
171
+ )
172
+
173
+ with open(f"{repo_playground}/{file_path}", "w") as f:
174
+ f.write(old_content)
175
+
176
+ # add file to git
177
+ # same message is okay
178
+ subprocess.run(
179
+ f"cd {repo_playground} && git add {file_path} && git commit -m 'initial commit'",
180
+ shell=True,
181
+ )
182
+
183
+ for file_path, old_content, new_content in zip(
184
+ file_pathes, old_contents, new_contents
185
+ ):
186
+ # edit file
187
+ with open(f"{repo_playground}/{file_path}", "w") as f:
188
+ f.write(new_content)
189
+
190
+ # get git diff
191
+ o = subprocess.run(
192
+ f"cd {repo_playground} && git diff .", shell=True, capture_output=True
193
+ )
194
+
195
+ s = o.stdout.decode("utf-8")
196
+
197
+ # remove playground
198
+ subprocess.run(f"rm -rf {repo_playground}", shell=True)
199
+
200
+ return s
201
+
202
+
203
+ def fake_git_apply(repo_playground, file_path, old_content, patch) -> str:
204
+ """create a fake git repo to obtain new file content"""
205
+
206
+ # Generate a temperary folder and add uuid to avoid collision
207
+ repo_playground = os.path.join(repo_playground, str(uuid.uuid4()))
208
+
209
+ # assert playground doesn't exist
210
+ assert not os.path.exists(repo_playground), f"{repo_playground} already exists"
211
+
212
+ # create playground
213
+ os.makedirs(repo_playground)
214
+
215
+ # create a fake git repo
216
+ subprocess.run(f"cd {repo_playground} && git init", shell=True)
217
+
218
+ # create a file
219
+ subprocess.run(
220
+ f"mkdir -p {repo_playground}/{os.path.dirname(file_path)}", shell=True
221
+ )
222
+
223
+ with open(f"{repo_playground}/{file_path}", "w") as f:
224
+ f.write(old_content)
225
+
226
+ # add file to git
227
+ subprocess.run(
228
+ f"cd {repo_playground} && git add {file_path} && git commit -m 'initial commit'",
229
+ shell=True,
230
+ )
231
+
232
+ # apply patch file
233
+ patch_file = f"{str(uuid.uuid4())}.patch"
234
+ with open(f"{repo_playground}/{patch_file}", "w") as f:
235
+ f.write(patch)
236
+ o = subprocess.run(
237
+ f"cd {repo_playground} && git apply --whitespace=nowarn {patch_file}",
238
+ shell=True,
239
+ capture_output=True,
240
+ )
241
+ if o.stderr.decode("utf-8"):
242
+ print("stderr> ", o.stderr.decode("utf-8"))
243
+ # TODO: This rarely happen but the patch should be valid, needs to look into it
244
+
245
+ with open(f"{repo_playground}/{file_path}", "w") as f:
246
+ f.write(old_content + "\n")
247
+
248
+ o = subprocess.run(
249
+ f"cd {repo_playground} && git apply --whitespace=nowarn {patch_file}",
250
+ shell=True,
251
+ capture_output=True,
252
+ )
253
+
254
+ if o.stderr.decode("utf-8"):
255
+ print("stderr> ", o.stderr.decode("utf-8"))
256
+ assert False, "shouldn't happen"
257
+
258
+ # get git diff
259
+ o = subprocess.run(
260
+ f"cd {repo_playground} && cat {file_path}", shell=True, capture_output=True
261
+ )
262
+
263
+ s = o.stdout.decode("utf-8")
264
+
265
+ # remove playground
266
+ subprocess.run(f"rm -rf {repo_playground}", shell=True)
267
+
268
+ return s
269
+
270
+
271
+ def fake_git_apply_multiple(repo_playground, file_path_contents, patch) -> dict:
272
+ """create a fake git repo to obtain new file contents (multiple)"""
273
+
274
+ # Generate a temperary folder and add uuid to avoid collision
275
+ repo_playground = os.path.join(repo_playground, str(uuid.uuid4()))
276
+
277
+ # assert playground doesn't exist
278
+ assert not os.path.exists(repo_playground), f"{repo_playground} already exists"
279
+
280
+ # create playground
281
+ os.makedirs(repo_playground)
282
+
283
+ # create a fake git repo
284
+ subprocess.run(f"cd {repo_playground} && git init", shell=True)
285
+
286
+ # create files
287
+ for file_path, old_content in file_path_contents.items():
288
+ subprocess.run(
289
+ f"mkdir -p {repo_playground}/{os.path.dirname(file_path)}", shell=True
290
+ )
291
+
292
+ with open(f"{repo_playground}/{file_path}", "w") as f:
293
+ f.write(old_content)
294
+
295
+ # add file to git
296
+ subprocess.run(
297
+ f"cd {repo_playground} && git add {file_path} && git commit -m 'initial commit'",
298
+ shell=True,
299
+ )
300
+
301
+ # apply patch file
302
+ patch_file = f"{str(uuid.uuid4())}.patch"
303
+ with open(f"{repo_playground}/{patch_file}", "w") as f:
304
+ f.write(patch)
305
+ o = subprocess.run(
306
+ f"cd {repo_playground} && git apply --whitespace=nowarn {patch_file}",
307
+ shell=True,
308
+ capture_output=True,
309
+ )
310
+ if o.stderr.decode("utf-8"):
311
+ print("stderr> ", o.stderr.decode("utf-8"))
312
+ # TODO: This rarely happen but the patch should be valid, needs to look into it
313
+ for file_path, old_content in file_path_contents.items():
314
+ with open(f"{repo_playground}/{file_path}", "w") as f:
315
+ f.write(old_content + "\n")
316
+
317
+ o = subprocess.run(
318
+ f"cd {repo_playground} && git apply --whitespace=nowarn {patch_file}",
319
+ shell=True,
320
+ capture_output=True,
321
+ )
322
+
323
+ if o.stderr.decode("utf-8"):
324
+ print("stderr> ", o.stderr.decode("utf-8"))
325
+ assert False, "shouldn't happen"
326
+
327
+ new_file_path_contents = {}
328
+
329
+ # get git diff
330
+ for file_path, old_content in file_path_contents.items():
331
+ o = subprocess.run(
332
+ f"cd {repo_playground} && cat {file_path}", shell=True, capture_output=True
333
+ )
334
+
335
+ s = o.stdout.decode("utf-8")
336
+
337
+ new_file_path_contents[file_path] = s
338
+
339
+ # remove playground
340
+ subprocess.run(f"rm -rf {repo_playground}", shell=True)
341
+
342
+ return new_file_path_contents
343
+
344
+
345
+ def get_functions(tree):
346
+ """Get a set of function and method names from the AST tree."""
347
+ functions = {}
348
+
349
+ class FunctionVisitor(ast.NodeVisitor):
350
+ def __init__(self):
351
+ self.parents = []
352
+
353
+ def visit(self, node):
354
+ self.parents.append(node)
355
+ super().visit(node)
356
+ self.parents.pop()
357
+
358
+ def visit_FunctionDef(self, node):
359
+ if not any(isinstance(parent, ast.ClassDef) for parent in self.parents):
360
+ functions[node.name] = ast.unparse(node)
361
+ self.generic_visit(node)
362
+
363
+ def visit_AsyncFunctionDef(self, node):
364
+ if not any(isinstance(parent, ast.ClassDef) for parent in self.parents):
365
+ functions[node.name] = ast.unparse(node)
366
+ self.generic_visit(node)
367
+
368
+ class ClassVisitor(ast.NodeVisitor):
369
+ def visit_ClassDef(self, node):
370
+ class_name = node.name
371
+ for body_item in node.body:
372
+ if isinstance(body_item, ast.FunctionDef) or isinstance(
373
+ body_item, ast.AsyncFunctionDef
374
+ ):
375
+ functions[f"{class_name}.{body_item.name}"] = ast.unparse(body_item)
376
+ self.generic_visit(node)
377
+
378
+ FunctionVisitor().visit(tree)
379
+ ClassVisitor().visit(tree)
380
+ return functions
381
+
382
+
383
+ def is_just_new_function(code1, code2):
384
+ tree1 = ast.parse(code1)
385
+ tree2 = ast.parse(code2)
386
+
387
+ functions1 = get_functions(tree1)
388
+ functions2 = get_functions(tree2)
389
+
390
+ # The new functions in the second code
391
+ if len(set(list(functions1.keys())) - set(list(functions2.keys()))) > 0:
392
+ # removes functions
393
+ return False
394
+
395
+ for func in functions1:
396
+ if functions1[func] != functions2[func]:
397
+ # modifies existing functions
398
+ return False
399
+
400
+ if len(set(list(functions2.keys())) - set(list(functions1.keys()))) > 0:
401
+ return True
402
+
403
+ # modifying global stuff is okay, because its actually same as functions almost.
404
+
405
+ return False
406
+
407
+
408
+ import io
409
+ import re
410
+ import tokenize
411
+
412
+
413
+ def remove_comments_and_docstrings(source):
414
+ io_obj = io.StringIO(source)
415
+ out = ""
416
+ prev_toktype = tokenize.INDENT
417
+ last_lineno = -1
418
+ last_col = 0
419
+ for tok in tokenize.generate_tokens(io_obj.readline):
420
+ token_type = tok[0]
421
+ token_string = tok[1]
422
+ start_line, start_col = tok[2]
423
+ end_line, end_col = tok[3]
424
+ ltext = tok[4]
425
+ if start_line > last_lineno:
426
+ last_col = 0
427
+ if start_col > last_col:
428
+ out += " " * (start_col - last_col)
429
+ if token_type == tokenize.COMMENT:
430
+ pass
431
+ elif token_type == tokenize.STRING:
432
+ if prev_toktype != tokenize.INDENT:
433
+ if prev_toktype != tokenize.NEWLINE:
434
+ if start_col > 0:
435
+ out += token_string
436
+ else:
437
+ out += token_string
438
+ prev_toktype = token_type
439
+ last_col = end_col
440
+ last_lineno = end_line
441
+ out = "\n".join(l for l in out.splitlines() if l.strip())
442
+ return out
443
+
444
+
445
+ def normalize_patch(
446
+ instance_id,
447
+ patch: str,
448
+ original_file_content: list,
449
+ new_file_content: list,
450
+ edited_files: list,
451
+ ) -> str:
452
+ "Remove edits to trailing spaces and comments in the patch."
453
+ if not patch.strip():
454
+ return ""
455
+
456
+ normalized_diff = ""
457
+
458
+ for o_file_content, n_file_content, edited_file in zip(
459
+ original_file_content, new_file_content, edited_files
460
+ ):
461
+ old_content = o_file_content
462
+ new_content = n_file_content
463
+
464
+ # Normalize file contents
465
+ def normalize_code(code):
466
+ try:
467
+ node = ast.parse(code)
468
+ return ast.unparse(node)
469
+ except:
470
+ return code
471
+
472
+ old_content = normalize_code(old_content)
473
+ new_content = normalize_code(new_content)
474
+
475
+ try:
476
+ remove_docstring_old_content = remove_comments_and_docstrings(old_content)
477
+ ast.parse(remove_docstring_old_content) # check
478
+ remove_docstring_new_content = remove_comments_and_docstrings(new_content)
479
+ ast.parse(remove_docstring_new_content) # check
480
+ except:
481
+ # when does this exception happen?
482
+ # when the code has some class or function with empty docstring (thats valid python code)
483
+ # but removing it is not, to be save we just use the original.
484
+ remove_docstring_old_content = old_content
485
+ remove_docstring_new_content = new_content
486
+
487
+ diff = fake_git_repo(
488
+ "playground",
489
+ edited_file,
490
+ remove_docstring_old_content,
491
+ remove_docstring_new_content,
492
+ )
493
+
494
+ if is_just_new_function(
495
+ remove_docstring_old_content, remove_docstring_new_content
496
+ ):
497
+ # modify the diff to ignore context.
498
+ new_diff = []
499
+ for line in diff.splitlines():
500
+ if line.startswith("-") or line.startswith("+"):
501
+ new_diff.append(line)
502
+ diff = "\n".join(new_diff)
503
+
504
+ normalized_diff += diff
505
+
506
+ # Note that the normalized diff may not be applied to the original file.
507
+ return normalized_diff
508
+
509
+
510
+ def extract_python_blocks(text):
511
+ # Regular expression pattern to match ```python\n{text}\n```
512
+ pattern = r"```python\n(.*?)\n```"
513
+
514
+ # Use re.findall to find all matches
515
+ matches = re.findall(pattern, text, re.DOTALL)
516
+
517
+ return matches
518
+
519
+
520
+ def extract_code_blocks(text):
521
+ pattern = r"```\n(.*?)\n```"
522
+ matches = re.findall(pattern, text, re.DOTALL)
523
+ if len(matches) == 0:
524
+ if "```" in text:
525
+ # handle the case where the code block is not complete
526
+ return [text.split("```", 1)[-1].strip()]
527
+ return matches
528
+
529
+
530
+ def extract_locs_for_files(locs, file_names, keep_old_order=False):
531
+ if keep_old_order:
532
+ results = {fn: [] for fn in file_names}
533
+ else:
534
+ results = {} # dict is insertion ordered
535
+ current_file_name = None
536
+ for loc in locs:
537
+ for line in loc.splitlines():
538
+ stripped = line.strip()
539
+ if not stripped:
540
+ continue
541
+ if _is_source_path(stripped, file_names):
542
+ current_file_name = stripped
543
+ elif any(stripped.startswith(w) for w in LOC_PREFIXES):
544
+ if current_file_name in file_names:
545
+ if current_file_name not in results:
546
+ results[current_file_name] = []
547
+ results[current_file_name].append(stripped)
548
+
549
+ for file_name in file_names:
550
+ if file_name not in results: # guard for new order case
551
+ results[file_name] = []
552
+
553
+ return {fn: ["\n".join(results[fn])] for fn in results.keys()}
554
+
555
+
556
+ def extract_starting_number(subcommand):
557
+ return int(subcommand.split(",")[0].split("start=")[-1])
558
+
559
+
560
+ def extract_ending_number(subcommand):
561
+ return int(subcommand.split(",")[1].split("end=")[-1])
562
+
563
+
564
+ def overlap(subcommand1, subcommand2):
565
+ start1, end1 = extract_starting_number(subcommand1), extract_ending_number(
566
+ subcommand1
567
+ )
568
+ start2, end2 = extract_starting_number(subcommand2), extract_ending_number(
569
+ subcommand2
570
+ )
571
+ return not (end1 < start2 or end2 < start1)
572
+
573
+
574
+ def split_edit_multifile_commands(
575
+ commands, diff_format=False, str_replace_format=False
576
+ ) -> dict[str, str]:
577
+ """Split commands based on edited files."""
578
+ file_to_commands = OrderedDict()
579
+ if str_replace_format:
580
+ for command in commands:
581
+ file_name = None
582
+ for json_message in command:
583
+ if json_message["type"] == "tool_use":
584
+ str_replace_command = json_message["input"]
585
+
586
+ if "command" not in str_replace_command:
587
+ str_replace_command["command"] = "str_replace"
588
+
589
+ if "path" not in str_replace_command:
590
+ continue
591
+
592
+ if "command" not in str_replace_command:
593
+ continue
594
+
595
+ if str_replace_command["command"] == "str_replace":
596
+ if "old_str" not in str_replace_command:
597
+ continue
598
+
599
+ if "new_str" not in str_replace_command:
600
+ # add empty string
601
+ str_replace_command["new_str"] = ""
602
+
603
+ if str_replace_command["command"] == "insert":
604
+ if (
605
+ "insert_line" not in str_replace_command
606
+ or "new_str" not in str_replace_command
607
+ ):
608
+ continue
609
+
610
+ file_name = "'" + str_replace_command["path"] + "'"
611
+ # deduplicate
612
+ if (
613
+ file_name not in file_to_commands
614
+ or str_replace_command not in file_to_commands[file_name]
615
+ ):
616
+ file_to_commands.setdefault(file_name, []).append(
617
+ str_replace_command
618
+ )
619
+
620
+ elif diff_format:
621
+ for command in commands:
622
+ file_name = None
623
+ for subcommand in command.split(">>>>>>> REPLACE")[:-1]:
624
+ subcommand = subcommand.strip()
625
+ if "<<<<<<< SEARCH" in subcommand:
626
+ fn = subcommand.split("<<<<<<< SEARCH")[0].lstrip("#").strip()
627
+ if fn:
628
+ file_name = "'" + fn + "'"
629
+
630
+ if len(subcommand.split("<<<<<<< SEARCH")) != 2:
631
+ continue
632
+ converted_command = (
633
+ "<<<<<<< SEARCH"
634
+ + subcommand.split("<<<<<<< SEARCH")[1]
635
+ + "\n"
636
+ + ">>>>>>> REPLACE"
637
+ )
638
+ # deduplicate
639
+ if (
640
+ file_name not in file_to_commands
641
+ or converted_command not in file_to_commands[file_name]
642
+ ):
643
+ file_to_commands.setdefault(file_name, []).append(converted_command)
644
+
645
+ else:
646
+ for command in commands:
647
+ for subcommand in command.split("edit_file(")[1:]:
648
+ file_name, start, end, content = subcommand.split(",", 3)
649
+ converted_command = "edit_file(" + ",".join([start, end, content])
650
+ # deduplicate
651
+ if (
652
+ file_name not in file_to_commands
653
+ or converted_command not in file_to_commands[file_name]
654
+ ):
655
+ file_to_commands.setdefault(file_name, []).append(converted_command)
656
+
657
+ return file_to_commands
658
+
659
+
660
+ def parse_str_replace_edit_commands(
661
+ commands, content, file_loc_intervals: list[tuple[int, int]]
662
+ ):
663
+ """
664
+ Original implementation: https://github.com/anthropics/anthropic-quickstarts/blob/main/computer-use-demo/computer_use_demo/tools/edit.py
665
+ """
666
+ # let's first make sure the intervals are sorted
667
+ file_loc_intervals.sort()
668
+ replaced = False
669
+ # apply the edits from the end of file to the beginning of file
670
+ # this is to make sure context is correct
671
+ for interval in file_loc_intervals[::-1]:
672
+ start, end = interval
673
+ start = max(start - 1, 0)
674
+ # intervals are 1-indexed
675
+
676
+ context_segment = "\n".join(content.splitlines()[start:end])
677
+ context_segment = "\n" + context_segment + "\n"
678
+
679
+ # since we want to replace the original context, let's first check for all edits.
680
+ can_apply = []
681
+ for subcommand in commands:
682
+
683
+ if subcommand["command"] == "str_replace":
684
+ original, replace = subcommand["old_str"], subcommand["new_str"]
685
+
686
+ if original in context_segment:
687
+ can_apply.append(subcommand)
688
+
689
+ elif subcommand["command"] == "insert":
690
+ insert_line = subcommand["insert_line"]
691
+ # TODO check this
692
+ if insert_line > start and insert_line <= end:
693
+ can_apply.append(subcommand)
694
+
695
+ # apply edits backwards
696
+ for subcommand in can_apply[::-1]:
697
+
698
+ if subcommand["command"] == "str_replace":
699
+ original, replace = subcommand["old_str"], subcommand["new_str"]
700
+
701
+ if (
702
+ original in context_segment
703
+ ): # This may not be true after some previously applied edits
704
+ context_segment = context_segment.replace(original, replace)
705
+ replaced = True
706
+
707
+ elif subcommand["command"] == "insert":
708
+ insert_line = subcommand["insert_line"]
709
+ replace = subcommand["new_str"]
710
+ # TODO check this
711
+ if insert_line > start and insert_line <= end:
712
+
713
+ if insert_line != start - 1:
714
+ replace = "\n" + replace
715
+ if insert_line != end:
716
+ replace = replace + "\n"
717
+ context_segment = (
718
+ "\n".join(
719
+ context_segment.splitlines()[: insert_line - start + 1]
720
+ )
721
+ + replace
722
+ + "\n".join(
723
+ context_segment.splitlines()[insert_line - start + 1 :]
724
+ )
725
+ )
726
+ context_segment = context_segment + "\n"
727
+ replaced = True
728
+
729
+ # reassembly
730
+ content = (
731
+ "\n".join(content.splitlines()[:start])
732
+ + context_segment
733
+ + "\n".join(content.splitlines()[end:])
734
+ )
735
+
736
+ if not replaced:
737
+ print("not replaced")
738
+
739
+ return content
740
+
741
+
742
+ def parse_diff_edit_commands(
743
+ commands, content, file_loc_intervals: list[tuple[int, int]]
744
+ ):
745
+ def parse_for_threedots(original, replace, file_loc_intervals, content):
746
+ # if dot dot dot in replace, its always safe to remove it
747
+ if replace.startswith("...\n") and len(replace) > 4:
748
+ # im parsing this first because its used later on
749
+ replace = replace[4:]
750
+
751
+ # just dot dot dot, then need to do something special
752
+ if original == "...":
753
+ if not replace[0].isspace():
754
+ # this is okay
755
+ # find a suitable original string to replace
756
+ for interval in file_loc_intervals:
757
+ start, end = interval
758
+ start = max(start - 1, 0)
759
+ context_segment = "\n".join(content.splitlines()[start:end])
760
+
761
+ for line in context_segment.splitlines():
762
+ if len(line) > 0 and not line[0].isspace():
763
+ if content.count(line) == 1:
764
+ original = line
765
+ # keep the line
766
+ replace = replace + "\n\n" + line
767
+ break
768
+
769
+ if original != "...":
770
+ break
771
+
772
+ if original == "...":
773
+ print("cannot find suitable location")
774
+
775
+ # dot dot dot with something else in original, then its safe to replace
776
+ if original.startswith("...\n") and len(original) > 4:
777
+ # remove dot dot dot from original
778
+ original = original[4:]
779
+
780
+ return original, replace
781
+
782
+ if len(file_loc_intervals) == 0:
783
+ if original in content:
784
+ content = content.replace(original, replace)
785
+ replaced = True
786
+ else:
787
+ print("not replaced")
788
+ return content
789
+ # let's first make sure the intervals are sorted
790
+ file_loc_intervals.sort()
791
+ replaced = False
792
+ # apply the edits from the end of file to the beginning of file
793
+ # this is to make sure context is correct
794
+ for interval in file_loc_intervals[::-1]:
795
+ start, end = interval
796
+ start = max(start - 1, 0)
797
+ context_segment = "\n".join(content.splitlines()[start:end])
798
+ context_segment = "\n" + context_segment + "\n"
799
+
800
+ # since we want to replace the original context, let's first check for all edits.
801
+ can_apply = []
802
+ for subcommand in commands:
803
+ if not subcommand.startswith("<<<<<<< SEARCH") and subcommand.endswith(
804
+ ">>>>>>> REPLACE"
805
+ ):
806
+ continue
807
+
808
+ subcommand = "\n".join(subcommand.splitlines()[1:-1])
809
+ if len(subcommand.split("\n=======\n")) != 2:
810
+ continue
811
+
812
+ original, replace = subcommand.split("\n=======\n")
813
+
814
+ original, replace = parse_for_threedots(
815
+ original, replace, file_loc_intervals, content
816
+ )
817
+
818
+ original = "\n" + original + "\n"
819
+ replace = "\n" + replace + "\n"
820
+
821
+ if original in context_segment:
822
+ can_apply.append(subcommand)
823
+
824
+ # apply edits backwards
825
+ for subcommand in can_apply[::-1]:
826
+ original, replace = subcommand.split("\n=======\n")
827
+
828
+ original, replace = parse_for_threedots(
829
+ original, replace, file_loc_intervals, content
830
+ )
831
+
832
+ original = "\n" + original + "\n"
833
+ replace = "\n" + replace + "\n"
834
+ if (
835
+ original in context_segment
836
+ ): # This may not be true after some previously applied edits
837
+ context_segment = context_segment.replace(original, replace)
838
+ replaced = True
839
+ # reassembly
840
+ content = (
841
+ "\n".join(content.splitlines()[:start])
842
+ + context_segment
843
+ + "\n".join(content.splitlines()[end:])
844
+ )
845
+
846
+ if not replaced:
847
+ print("not replaced")
848
+
849
+ return content
850
+
851
+
852
+ def parse_edit_commands(commands, content):
853
+ content_lines = content.splitlines()
854
+ map_content_lines_to_line_num = [i for i in range(0, len(content_lines) + 1)]
855
+
856
+ # Make a list of the subcommands
857
+ subcommands = []
858
+
859
+ for command in commands:
860
+ for subcommand in command.split("edit_file(")[1:]:
861
+ subcommands.append(subcommand)
862
+
863
+ # Remove duplicates while preserving order
864
+ seen = set()
865
+ unique_subcommands = []
866
+ for subcommand in subcommands:
867
+ if subcommand not in seen:
868
+ unique_subcommands.append(subcommand)
869
+ seen.add(subcommand)
870
+
871
+ # Sort the unique subcommands by the starting number in reverse order
872
+ unique_sorted_subcommands = sorted(
873
+ unique_subcommands, key=extract_starting_number, reverse=True
874
+ )
875
+
876
+ for subcommand in unique_sorted_subcommands:
877
+ command_start = int(subcommand.split(",")[0].split("start=")[-1])
878
+ command_end = int(subcommand.split(",")[1].split("end=")[-1])
879
+
880
+ start = map_content_lines_to_line_num.index(command_start)
881
+ end = map_content_lines_to_line_num.index(command_end)
882
+
883
+ try:
884
+ changed_content = eval(
885
+ ")".join(",".join(subcommand.split(",")[2:]).split(")")[:-1])
886
+ )
887
+ # small thing to ensure right white space indent
888
+ if (
889
+ start == end
890
+ and len(changed_content.splitlines()) == 1
891
+ and (len(changed_content) - len(changed_content.lstrip())) == 0
892
+ ):
893
+ indent_length = len(content_lines[start - 1]) - len(
894
+ content_lines[start - 1].lstrip()
895
+ )
896
+ changed_content = " " * indent_length + changed_content.lstrip()
897
+
898
+ # catch syntax error
899
+ except:
900
+ # try to fix, specially for case where there are """ or ''' in the string, that cannot be
901
+ # easily evaluated.
902
+ eval_str = ")".join(
903
+ ",".join(subcommand.split(",")[2:]).split(")")[:-1]
904
+ ).strip()
905
+
906
+ if eval_str.startswith("content="):
907
+ eval_str = eval_str[8:]
908
+
909
+ if eval_str.startswith('"""') or eval_str.startswith("'''"):
910
+ eval_str = eval_str[3:-3]
911
+ if eval_str.startswith('"') or eval_str.startswith("'"):
912
+ eval_str = eval_str[1:-1]
913
+
914
+ changed_content = eval_str
915
+
916
+ content_lines[start - 1 : end] = changed_content.splitlines()
917
+
918
+ content = "\n".join(content_lines)
919
+
920
+ return content
921
+
922
+
923
+ def test_parse_str_replace():
924
+
925
+ content = """A
926
+ B
927
+ C
928
+ D
929
+ E
930
+ F
931
+ """.strip()
932
+
933
+ from agentless.util.preprocess_data import line_wrap_content
934
+
935
+ shown_content = line_wrap_content(content, context_intervals=[(3, 5)])
936
+ print(shown_content)
937
+
938
+ commands = [
939
+ {"command": "insert", "path": "test", "insert_line": 1, "new_str": "test_str"}
940
+ ]
941
+ new_content = parse_str_replace_edit_commands(
942
+ commands, content, file_loc_intervals=[(1, 5)]
943
+ )
944
+ print(new_content)
945
+
946
+
947
+ def test_parse():
948
+ raw_output = """
949
+ ```python
950
+ edit_file(1, 1, "import os")
951
+ ```
952
+ """
953
+
954
+ content = """
955
+ import sys
956
+ """.strip()
957
+
958
+ commands = extract_python_blocks(raw_output)
959
+
960
+ content = parse_edit_commands(commands, content)
961
+
962
+ assert content == "import os", content
963
+
964
+ raw_output = """
965
+ ```python
966
+ edit_file(1, 1, '''import os\nimport sys''')
967
+ ```
968
+ """
969
+
970
+ content = """
971
+ import sys
972
+ """.strip()
973
+
974
+ commands = extract_python_blocks(raw_output)
975
+
976
+ content = parse_edit_commands(commands, content)
977
+
978
+ assert content == "import os\nimport sys", content
979
+
980
+ raw_output = """
981
+ ```python
982
+ edit_file(1, 1, '''import os''')
983
+ edit_file(1, 1, '''import sys''')
984
+ ```
985
+ """
986
+
987
+ content = """
988
+ import sys
989
+ """.strip()
990
+
991
+ commands = extract_python_blocks(raw_output)
992
+
993
+ content = parse_edit_commands(commands, content)
994
+
995
+ assert content == "import sys", content
996
+
997
+ content = """
998
+ test
999
+ testing
1000
+ """.strip()
1001
+ raw_output = """
1002
+ ```python
1003
+ edit_file(1, 1, "testing\ntesting2")
1004
+ edit_file(2, 2, "testing3")
1005
+ ```
1006
+ """
1007
+ content = parse_edit_commands(extract_python_blocks(raw_output), content)
1008
+
1009
+ assert content == "testing\ntesting2\ntesting3", content
1010
+
1011
+ content = """
1012
+ test
1013
+ testing
1014
+ testinging
1015
+ """.strip()
1016
+
1017
+ raw_output = """
1018
+ ```python
1019
+ edit_file(1, 2, "testing")
1020
+ edit_file(3, 3, "testing3")
1021
+ ```
1022
+ """
1023
+ content = parse_edit_commands(extract_python_blocks(raw_output), content)
1024
+
1025
+ assert content == "testing\ntesting3", content
1026
+
1027
+ content = """
1028
+ test
1029
+ testing
1030
+ testinging
1031
+ test
1032
+ testing
1033
+ """.strip()
1034
+
1035
+ raw_output = """
1036
+ ```python
1037
+ edit_file(1, 2, "testing")
1038
+ edit_file(3, 3, "testing3")
1039
+ edit_file(4, 4, "testing\ntesting2")
1040
+ edit_file(5, 5, "testing3")
1041
+ ```
1042
+ """
1043
+
1044
+ edited_content = """
1045
+ testing
1046
+ testing3
1047
+ testing
1048
+ testing2
1049
+ testing3
1050
+ """.strip()
1051
+ content = parse_edit_commands(extract_python_blocks(raw_output), content)
1052
+
1053
+ assert content == edited_content, content
1054
+
1055
+ # Test for if command is present twice in the output (adapted from real output)
1056
+ content = """
1057
+ test
1058
+ testing
1059
+ testinging
1060
+ test
1061
+ testing
1062
+ """.strip()
1063
+
1064
+ raw_output = (
1065
+ """
1066
+ "To fix the issue where `viewcode`
1067
+ 1. Add a condition
1068
+
1069
+ ```python
1070
+ edit_file(4, 4, """
1071
+ """
1072
+ test4
1073
+ """
1074
+ """)
1075
+ ```
1076
+
1077
+ 2. Ensure that the `doctree_read`
1078
+
1079
+ ```python
1080
+ edit_file(2, 3, """
1081
+ """
1082
+ test-2-3
1083
+ """
1084
+ """)
1085
+ ```
1086
+
1087
+ Here is the complete set of commands to address the issue:
1088
+
1089
+ ```python
1090
+ edit_file(4, 4, """
1091
+ """
1092
+ test4
1093
+ """
1094
+ """)
1095
+ ```
1096
+
1097
+ ```python
1098
+ edit_file(2, 3, """
1099
+ """
1100
+ test-2-3
1101
+ """
1102
+ """)
1103
+ ```
1104
+ """
1105
+ )
1106
+ content = parse_edit_commands(extract_python_blocks(raw_output), content)
1107
+
1108
+ revised_content = """
1109
+ test
1110
+ test-2-3
1111
+ test4
1112
+ testing
1113
+ """.strip()
1114
+
1115
+ assert content == revised_content, content
1116
+
1117
+ raw_output = """
1118
+ ```
1119
+ django/db/migrations/optimizer.py
1120
+ function: MigrationOptimizer.optimize_inner
1121
+
1122
+ django/db/migrations/operations/fields.py
1123
+ function: AlterField.reduce
1124
+ ```
1125
+ """
1126
+ files = [
1127
+ "django/db/migrations/optimizer.py",
1128
+ "django/db/migrations/operations/fields.py",
1129
+ "django/db/migrations/operations/models.py",
1130
+ ]
1131
+ extracted_locs = extract_locs_for_files([raw_output], files)
1132
+ print(extracted_locs)
1133
+ assert extracted_locs == [
1134
+ ["function: MigrationOptimizer.optimize_inner"],
1135
+ ["function: AlterField.reduce"],
1136
+ [""],
1137
+ ]
1138
+
1139
+ raw_output = """
1140
+ ```python
1141
+ edit_file(start=1, end=1, content="testing not")
1142
+ ```
1143
+ """
1144
+
1145
+ content = """
1146
+ testing
1147
+ """.strip()
1148
+
1149
+ edited_content = """
1150
+ testing not
1151
+ """.strip()
1152
+
1153
+ content = parse_edit_commands(extract_python_blocks(raw_output), content)
1154
+ assert content == edited_content, edited_content
1155
+
1156
+
1157
+ if __name__ == "__main__":
1158
+ # test_parse()
1159
+
1160
+ # Example Usage
1161
+ code1 = """
1162
+ class MyClass:
1163
+ def existing_method(self):
1164
+ pass
1165
+ """
1166
+
1167
+ code2 = """
1168
+ class MyClass:
1169
+ def existing_method(self):
1170
+ pass
1171
+
1172
+ async def new_method(self):
1173
+ pass
1174
+ """
1175
+
1176
+ print(is_just_new_function(code1, code2)) # Output: True
Repos/HWE/agents/Agentless/agentless/util/preprocess_data.py ADDED
@@ -0,0 +1,868 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+
4
+ from get_repo_structure.get_repo_structure import get_project_structure_from_scratch
5
+
6
+ try:
7
+ from get_repo_structure.get_repo_structure import parse_verilog_file as parse_source_file
8
+ except ImportError:
9
+ from get_repo_structure.get_repo_structure import parse_python_file as parse_source_file
10
+
11
+ SOURCE_EXTENSIONS = {".v", ".sv", ".vh", ".svh", ".py"}
12
+ MODULE_PREFIXES = (
13
+ "module:",
14
+ "interface:",
15
+ "package:",
16
+ "program:",
17
+ "class:",
18
+ "checker:",
19
+ "config:",
20
+ "primitive:",
21
+ "udp:",
22
+ )
23
+ FUNCTION_PREFIXES = ("function:", "task:", "method:")
24
+
25
+
26
+ def _get_global_vars(file_content: str) -> dict:
27
+ try:
28
+ from agentless.util.parse_global_var import parse_global_var_from_code
29
+ except Exception:
30
+ return {}
31
+ global_vars = parse_global_var_from_code(file_content)
32
+ return global_vars if isinstance(global_vars, dict) else {}
33
+
34
+ def line_wrap_content(
35
+ content: str,
36
+ context_intervals=None,
37
+ add_space=False,
38
+ no_line_number=False,
39
+ sticky_scroll=False,
40
+ ):
41
+ """add n| to each line, where n increases"""
42
+
43
+ def is_scope(line):
44
+ # TODO: this might not be precise, can improve with syntax parsing
45
+ stripped = line.strip()
46
+ return stripped.startswith("def ") or stripped.startswith("class ") or any(
47
+ stripped.startswith(token)
48
+ for token in (
49
+ "module ",
50
+ "interface ",
51
+ "package ",
52
+ "program ",
53
+ "class ",
54
+ "function ",
55
+ "task ",
56
+ )
57
+ )
58
+
59
+ lines = content.split("\n")
60
+ new_lines = []
61
+ if context_intervals is None or context_intervals == []:
62
+ context_intervals = [(0, len(lines))]
63
+
64
+ prev_scopes = []
65
+ line_format = "{line}"
66
+ if not no_line_number:
67
+ line_format = (
68
+ "{line_number}|{line}" if not add_space else "{line_number}| {line} "
69
+ )
70
+ for interval in context_intervals:
71
+ min_line, max_line = interval
72
+
73
+ if min_line != 0:
74
+ new_lines.append("...")
75
+
76
+ scopes = []
77
+ for i, line in enumerate(lines):
78
+ if sticky_scroll:
79
+ # add current line to scope if necessary
80
+ if is_scope(line):
81
+ indent_level = len(line) - len(line.lstrip())
82
+ while scopes and scopes[-1]["indent_level"] >= indent_level:
83
+ scopes.pop()
84
+ scopes.append(
85
+ {"line": line, "line_number": i, "indent_level": indent_level}
86
+ )
87
+
88
+ if min_line != -1 and i < min_line - 1:
89
+ continue
90
+ if sticky_scroll and i == min_line - 1:
91
+ # add scope lines
92
+ last_scope_line = None
93
+ for j, scope_line in enumerate(scopes):
94
+ # don't repeat previous scopes
95
+ if (
96
+ len(prev_scopes) > j
97
+ and prev_scopes[j]["line_number"] == scope_line["line_number"]
98
+ ):
99
+ continue
100
+ # don't repeat current line
101
+ if i == scope_line["line_number"]:
102
+ continue
103
+ new_lines.append(
104
+ line_format.format(
105
+ line_number=scope_line["line_number"] + 1,
106
+ line=scope_line["line"],
107
+ )
108
+ )
109
+ last_scope_line = scope_line["line_number"]
110
+ if last_scope_line is not None and last_scope_line < i - 1:
111
+ new_lines.append("...")
112
+
113
+ new_lines.append(line_format.format(line_number=i + 1, line=line))
114
+ if max_line != -1 and i >= max_line - 1:
115
+ break
116
+ prev_scopes = scopes
117
+
118
+ if max_line != len(lines):
119
+ new_lines.append("...")
120
+
121
+ return "\n".join(new_lines)
122
+
123
+
124
+ def merge_intervals(intervals):
125
+ # intervals inclusive
126
+ if not intervals:
127
+ return []
128
+
129
+ # Sort the intervals based on the starting value of each tuple
130
+ intervals.sort(key=lambda interval: interval[0])
131
+
132
+ merged_intervals = [intervals[0]]
133
+
134
+ for current in intervals[1:]:
135
+ last = merged_intervals[-1]
136
+
137
+ # Check if there is overlap
138
+ if current[0] <= last[1]:
139
+ # If there is overlap, merge the intervals
140
+ merged_intervals[-1] = (last[0], max(last[1], current[1]))
141
+ else:
142
+ # If there is no overlap, just add the current interval to the result list
143
+ merged_intervals.append(current)
144
+
145
+ return merged_intervals
146
+
147
+
148
+ def transfer_arb_locs_to_locs(
149
+ locs,
150
+ structure,
151
+ pred_file,
152
+ context_window=10,
153
+ loc_interval=False,
154
+ fine_grain_only=False,
155
+ remove_line=False,
156
+ file_content="",
157
+ verbose=False,
158
+ ) -> tuple[list, list]:
159
+ if structure is None:
160
+ class_info, function_names, file_lines = parse_source_file("", file_content)
161
+ structure = {}
162
+ structure[pred_file] = {
163
+ "classes": class_info,
164
+ "functions": function_names,
165
+ "text": file_lines,
166
+ }
167
+
168
+ files, classes, functions = get_full_file_paths_and_classes_and_functions(structure)
169
+
170
+ line_loc = []
171
+ if isinstance(locs, str):
172
+ # if its a single loc
173
+ locs = [locs]
174
+ # TODO: parse it in advance
175
+ global_vars = _get_global_vars(file_content)
176
+ unrecognized_locs = []
177
+
178
+ for model_pred_locs in locs:
179
+ current_class_name = ""
180
+ for loc in model_pred_locs.splitlines():
181
+ # handle cases like "class: MyClass.my_method"
182
+ module_prefix = next(
183
+ (prefix for prefix in MODULE_PREFIXES if loc.startswith(prefix)), None
184
+ )
185
+ if module_prefix and "." not in loc:
186
+ loc = loc[len(module_prefix) :].strip()
187
+ relevant_class = [
188
+ clazz
189
+ for clazz in classes
190
+ if clazz["file"] == pred_file and clazz["name"] == loc
191
+ ]
192
+
193
+ if len(relevant_class) == 0:
194
+ unrecognized_locs.append(loc)
195
+ else:
196
+ line_loc.append(
197
+ (relevant_class[0]["start_line"], relevant_class[0]["end_line"])
198
+ )
199
+ current_class_name = loc
200
+
201
+ elif loc.startswith(FUNCTION_PREFIXES) or "." in loc:
202
+ full_loc = loc
203
+ loc = loc.split(":", 1)[-1].strip()
204
+
205
+ if "." in loc:
206
+ # assume its a method within a class
207
+ method_name = loc.split(".")[1]
208
+ class_name = loc.split(".")[0]
209
+
210
+ relevant_class = [
211
+ clazz
212
+ for clazz in classes
213
+ if clazz["file"] == pred_file and clazz["name"] == class_name
214
+ ]
215
+ if len(relevant_class) == 0:
216
+ unrecognized_locs.append(loc)
217
+ else:
218
+ relevant_method = [
219
+ method
220
+ for method in relevant_class[0]["methods"]
221
+ if method["name"] == method_name
222
+ ]
223
+ if len(relevant_method) == 0:
224
+ unrecognized_locs.append(loc)
225
+ else:
226
+ line_loc.append(
227
+ (
228
+ relevant_method[0]["start_line"],
229
+ relevant_method[0]["end_line"],
230
+ )
231
+ )
232
+
233
+ else:
234
+ relevant_function = [
235
+ function
236
+ for function in functions
237
+ if function["file"] == pred_file and function["name"] == loc
238
+ ]
239
+ if len(relevant_function) == 0:
240
+ if current_class_name != "":
241
+ # check if its a method
242
+ relevant_class = [
243
+ clazz
244
+ for clazz in classes
245
+ if clazz["file"] == pred_file
246
+ and clazz["name"] == current_class_name
247
+ ]
248
+ relevant_method = [
249
+ method
250
+ for method in relevant_class[0]["methods"]
251
+ if method["name"] == loc
252
+ ]
253
+ if len(relevant_method) == 0:
254
+ unrecognized_locs.append(loc)
255
+ else:
256
+ line_loc.append(
257
+ (
258
+ relevant_method[0]["start_line"],
259
+ relevant_method[0]["end_line"],
260
+ )
261
+ )
262
+ else:
263
+ # look for it in any class
264
+ relevant_method = []
265
+ for clazz in classes:
266
+ if clazz["file"] == pred_file:
267
+ relevant_method.extend(
268
+ [
269
+ method
270
+ for method in clazz["methods"]
271
+ if method["name"] == loc
272
+ ]
273
+ )
274
+
275
+ if len(relevant_method) == 1:
276
+ line_loc.append(
277
+ (
278
+ relevant_method[0]["start_line"],
279
+ relevant_method[0]["end_line"],
280
+ )
281
+ )
282
+ else:
283
+ line_loc.append(
284
+ (
285
+ relevant_function[0]["start_line"],
286
+ relevant_function[0]["end_line"],
287
+ )
288
+ )
289
+ elif loc.startswith("line: "):
290
+ if remove_line:
291
+ # TODO: can recover the corresponding function instead of throwing it away
292
+ continue
293
+ loc = loc[len("line: ") :].strip().split()[0]
294
+ try:
295
+ # line_loc.append(int(loc))
296
+ line_loc.append((int(loc), int(loc)))
297
+ except:
298
+ continue
299
+ elif loc.startswith("variable:"):
300
+ vars = loc[len("variable:") :].strip().split()
301
+ for v in vars:
302
+ if v in global_vars:
303
+ line_loc.append(
304
+ (global_vars[v]["start_line"], global_vars[v]["end_line"])
305
+ )
306
+ else:
307
+ if loc.strip():
308
+ unrecognized_locs.append(loc)
309
+ # assert False
310
+
311
+ # Fine-grained-only loc: Remove intervals that are supersets of another.
312
+ if fine_grain_only:
313
+ filtered_line_loc = []
314
+ for st, en in line_loc:
315
+ if filtered_line_loc:
316
+ last_st, last_en = filtered_line_loc[-1]
317
+ # If the current interval is a more fine-grained loc, remove the superset.
318
+ if last_st <= st and en <= last_en:
319
+ filtered_line_loc.pop()
320
+ filtered_line_loc.append((st, en))
321
+ line_loc = filtered_line_loc
322
+
323
+ # compute max min
324
+ # TODO: think of strategies to do bunched up lines
325
+ # TODO: e.g., we can have multiple code segments (right now, its just one)
326
+
327
+ for file_content in files:
328
+ if file_content[0] == pred_file:
329
+ content = file_content[1]
330
+ break
331
+
332
+ if len(line_loc) == 0:
333
+ return [], []
334
+
335
+ # max_line = min(max(line_loc) + context_window, len(content))
336
+ # min_line = max(min(line_loc) - context_window, 0)
337
+ #
338
+ # return line_loc, max_line, min_line
339
+
340
+ if verbose:
341
+ print("Unrecognized locs:")
342
+ for loc in unrecognized_locs:
343
+ print(loc)
344
+
345
+ # compute overlapping locations instead
346
+ if loc_interval:
347
+ contextual_line_loc = []
348
+ for loc in line_loc:
349
+ # Clip the context window to the beginning and end of the file
350
+ max_line = max(min(loc[1] + context_window, len(content)), 0)
351
+ min_line = min(max(loc[0] - context_window, 0), len(content))
352
+ contextual_line_loc.append((min_line, max_line))
353
+
354
+ return line_loc, merge_intervals(contextual_line_loc)
355
+ else:
356
+ # defaulting to max min
357
+ max_line = min(max([loc[1] for loc in line_loc]) + context_window, len(content))
358
+ min_line = max(min([loc[0] for loc in line_loc]) - context_window, 0)
359
+
360
+ return line_loc, [(min_line, max_line)]
361
+
362
+
363
+ def check_contains_valid_loc(file_to_locs, structure):
364
+ """checks if the llm generated locations have at least one location valid"""
365
+
366
+ file_contents = get_repo_files(structure, list(file_to_locs.keys()))
367
+
368
+ for pred_file, locs in file_to_locs.items():
369
+ line_locs, _ = transfer_arb_locs_to_locs(
370
+ locs,
371
+ structure,
372
+ pred_file,
373
+ 0, # these parameters do not matter for checking purposes
374
+ True, # these parameters do not matter for checking purposes
375
+ False, # these parameters do not matter for checking purposes
376
+ file_content=file_contents[pred_file] if pred_file in file_contents else "",
377
+ )
378
+
379
+ if len(line_locs) > 0:
380
+ return True
381
+
382
+ return False
383
+
384
+
385
+ def compile_gt_locations(gt_location: dict) -> tuple[list, set, set, set]:
386
+ """mostly serves a way to check what are the gt locations in gt patch"""
387
+ edits = gt_location["edits"]
388
+
389
+ lines, classes, methods, functions = [], set(), set(), set()
390
+
391
+ adds = set()
392
+
393
+ for edit in edits:
394
+ for clazz in edit["class_names"]:
395
+ classes.add(clazz)
396
+
397
+ for method in edit["method_names"]:
398
+ methods.add(method)
399
+
400
+ for function in edit["function_names"]:
401
+ functions.add(function)
402
+
403
+ if edit["type"] == "add":
404
+ adds.add(edit["line"])
405
+ else:
406
+ lines.append(edit["line"])
407
+
408
+ # handle the added lines
409
+ add_intervals = [(i, i + 1) for i in adds]
410
+ add_intervals = merge_intervals(add_intervals)
411
+ for st, en in add_intervals:
412
+ lines.append(st)
413
+ lines = list(set(lines))
414
+
415
+ # sort the lines
416
+ lines = sorted(lines)
417
+
418
+ return lines, classes, methods, functions
419
+
420
+
421
+ def show_project_structure(structure, spacing=0) -> str:
422
+ """pprint the project structure"""
423
+
424
+ pp_string = ""
425
+
426
+ for key, value in structure.items():
427
+ if "." in key:
428
+ _, ext = os.path.splitext(key)
429
+ if ext.lower() not in SOURCE_EXTENSIONS:
430
+ continue # skip non-source files
431
+ if "." in key:
432
+ pp_string += " " * spacing + str(key) + "\n"
433
+ else:
434
+ pp_string += " " * spacing + str(key) + "/" + "\n"
435
+ if "classes" not in value:
436
+ pp_string += show_project_structure(value, spacing + 4)
437
+
438
+ return pp_string
439
+
440
+
441
+ def filter_out_test_files(structure):
442
+ """filter out test files from the project structure"""
443
+ for key, value in list(structure.items()):
444
+ if key.startswith("test"):
445
+ del structure[key]
446
+ elif isinstance(value, dict):
447
+ filter_out_test_files(value)
448
+
449
+
450
+ def filter_none_python(structure):
451
+ for key, value in list(structure.items()):
452
+ if (
453
+ not "functions" in value.keys()
454
+ and not "classes" in value.keys()
455
+ and not "text" in value.keys()
456
+ ) or not len(value.keys()) == 3:
457
+ filter_none_python(value)
458
+
459
+ if structure[key] == {}:
460
+ del structure[key]
461
+ else:
462
+ _, ext = os.path.splitext(key)
463
+ if ext.lower() not in SOURCE_EXTENSIONS:
464
+ del structure[key]
465
+
466
+
467
+ def filter_non_source(structure):
468
+ filter_none_python(structure)
469
+
470
+
471
+ def filter_proposed_files(proposed_files, repo_structure):
472
+ """
473
+ Filter proposed files against a given repository structure.
474
+
475
+ Arguments:
476
+ proposed_files -- list of proposed files with instance IDs
477
+ repo_structure -- list of repository structures with instance IDs
478
+
479
+ Returns:
480
+ A list of dictionaries with instance IDs and valid files matching the repository structure.
481
+ """
482
+ instance_to_files = {
483
+ entry["instance_id"]: entry["files"] for entry in proposed_files
484
+ }
485
+ instance_to_structure = {
486
+ entry["instance_id"]: entry["structure"] for entry in repo_structure
487
+ }
488
+ filtered_files = []
489
+ for instance_id, files in instance_to_files.items():
490
+ if instance_id in instance_to_structure:
491
+ repo_files, _, _ = get_full_file_paths_and_classes_and_functions(
492
+ instance_to_structure[instance_id]
493
+ )
494
+ repo_files_set = set(repo_files)
495
+ valid_files = []
496
+ for repo_file in repo_files_set:
497
+ for proposed_file in files:
498
+ if proposed_file == repo_file.split("/")[-1]:
499
+ valid_files.append(repo_file)
500
+ if valid_files:
501
+ filtered_files.append(
502
+ {"instance_id": instance_id, "files": valid_files}
503
+ )
504
+ return filtered_files
505
+
506
+
507
+ def filter_proposed_classes(proposed_classes, repo_structure):
508
+ """
509
+ Filter proposed classes against a given repository structure.
510
+
511
+ Arguments:
512
+ proposed_classes -- list of proposed classes with instance IDs
513
+ repo_structure -- list of repository structures with instance IDs
514
+
515
+ Returns:
516
+ A list of dictionaries with instance IDs and valid classes matching the repository structure.
517
+ """
518
+ instance_to_classes = {
519
+ entry["instance_id"]: entry["classes"] for entry in proposed_classes
520
+ }
521
+ instance_to_structure = {
522
+ entry["instance_id"]: entry["structure"] for entry in repo_structure
523
+ }
524
+ filtered_classes = []
525
+ for instance_id, classes in instance_to_classes.items():
526
+ if instance_id in instance_to_structure:
527
+ _, repo_classes, _ = get_full_file_paths_and_classes_and_functions(
528
+ instance_to_structure[instance_id]
529
+ )
530
+ repo_classes_set = {clazz["name"]: clazz["file"] for clazz in repo_classes}
531
+ valid_classes = []
532
+ for proposed_class in classes:
533
+ if proposed_class in repo_classes_set:
534
+ valid_classes.append(
535
+ {
536
+ "name": proposed_class,
537
+ "file": repo_classes_set[proposed_class],
538
+ }
539
+ )
540
+ if valid_classes:
541
+ filtered_classes.append(
542
+ {"instance_id": instance_id, "classes": valid_classes}
543
+ )
544
+ return filtered_classes
545
+
546
+
547
+ def filter_proposed_methods(proposed_methods, repo_structure):
548
+ """
549
+ Filter proposed methods against a given repository structure.
550
+
551
+ Arguments:
552
+ proposed_methods -- list of proposed methods with instance IDs
553
+ repo_structure -- list of repository structures with instance IDs
554
+
555
+ Returns:
556
+ A list of dictionaries with instance IDs and valid methods matching the repository structure.
557
+ """
558
+ instance_to_methods = {
559
+ entry["instance_id"]: entry["methods"] for entry in proposed_methods
560
+ }
561
+ instance_to_structure = {
562
+ entry["instance_id"]: entry["structure"] for entry in repo_structure
563
+ }
564
+ filtered_methods = []
565
+ for instance_id, methods in instance_to_methods.items():
566
+ if instance_id in instance_to_structure:
567
+ _, repo_classes, _ = get_full_file_paths_and_classes_and_functions(
568
+ instance_to_structure[instance_id]
569
+ )
570
+ valid_methods = []
571
+ for repo_class in repo_classes:
572
+ for method in methods:
573
+ if method in repo_class["methods"]:
574
+ valid_methods.append(
575
+ {
576
+ "class": repo_class["name"],
577
+ "method": method,
578
+ "file": repo_class["file"],
579
+ }
580
+ )
581
+ if valid_methods:
582
+ filtered_methods.append(
583
+ {"instance_id": instance_id, "methods": valid_methods}
584
+ )
585
+ return filtered_methods
586
+
587
+
588
+ def filter_proposed_functions(proposed_functions, repo_structure):
589
+ """
590
+ Filter proposed functions against a given repository structure.
591
+
592
+ Arguments:
593
+ proposed_functions -- list of proposed functions with instance IDs
594
+ repo_structure -- list of repository structures with instance IDs
595
+
596
+ Returns:
597
+ A list of dictionaries with instance IDs and valid functions matching the repository structure.
598
+ """
599
+ instance_to_functions = {
600
+ entry["instance_id"]: entry["functions"] for entry in proposed_functions
601
+ }
602
+ instance_to_structure = {
603
+ entry["instance_id"]: entry["structure"] for entry in repo_structure
604
+ }
605
+ filtered_functions = []
606
+ for instance_id, functions in instance_to_functions.items():
607
+ if instance_id in instance_to_structure:
608
+ _, _, repo_functions = get_full_file_paths_and_classes_and_functions(
609
+ instance_to_structure[instance_id]
610
+ )
611
+ valid_functions = []
612
+ for repo_function in repo_functions:
613
+ for function in functions:
614
+ if isinstance(
615
+ repo_function["name"], dict
616
+ ): # Why are there cases where this is not a dict?
617
+ if function == repo_function["name"].get("name", []):
618
+ valid_functions.append(
619
+ {"function": function, "file": repo_function["file"]}
620
+ )
621
+ if valid_functions:
622
+ filtered_functions.append(
623
+ {"instance_id": instance_id, "functions": valid_functions}
624
+ )
625
+ return filtered_functions
626
+
627
+
628
+ def get_full_file_paths_and_classes_and_functions(structure, current_path=""):
629
+ """
630
+ Recursively retrieve all file paths, classes, and functions within a directory structure.
631
+
632
+ Arguments:
633
+ structure -- a dictionary representing the directory structure
634
+ current_path -- the path accumulated so far, used during recursion (default="")
635
+
636
+ Returns:
637
+ A tuple containing:
638
+ - files: list of full file paths
639
+ - classes: list of class details with file paths
640
+ - functions: list of function details with file paths
641
+ """
642
+ files = []
643
+ classes = []
644
+ functions = []
645
+ for name, content in structure.items():
646
+ if isinstance(content, dict):
647
+ if (
648
+ not "functions" in content.keys()
649
+ and not "classes" in content.keys()
650
+ and not "text" in content.keys()
651
+ ) or not len(content.keys()) == 3:
652
+ # or guards against case where functions and classes are somehow part of the structure.
653
+ next_path = f"{current_path}/{name}" if current_path else name
654
+ (
655
+ sub_files,
656
+ sub_classes,
657
+ sub_functions,
658
+ ) = get_full_file_paths_and_classes_and_functions(content, next_path)
659
+ files.extend(sub_files)
660
+ classes.extend(sub_classes)
661
+ functions.extend(sub_functions)
662
+ else:
663
+ next_path = f"{current_path}/{name}" if current_path else name
664
+ files.append((next_path, content["text"]))
665
+ if "classes" in content:
666
+ for clazz in content["classes"]:
667
+ classes.append(
668
+ {
669
+ "file": next_path,
670
+ "name": clazz["name"],
671
+ "start_line": clazz["start_line"],
672
+ "end_line": clazz["end_line"],
673
+ "methods": [
674
+ {
675
+ "name": method["name"],
676
+ "start_line": method["start_line"],
677
+ "end_line": method["end_line"],
678
+ }
679
+ for method in clazz.get("methods", [])
680
+ ],
681
+ }
682
+ )
683
+ if "functions" in content:
684
+ for function in content["functions"]:
685
+ function["file"] = next_path
686
+ functions.append(function)
687
+ else:
688
+ next_path = f"{current_path}/{name}" if current_path else name
689
+ files.append(next_path)
690
+ return files, classes, functions
691
+
692
+
693
+ PROJECT_FILE_LOC = os.environ.get("PROJECT_FILE_LOC", None)
694
+
695
+
696
+ def get_repo_structure(instance_id: str, repo_name, base_commit, playground):
697
+
698
+ if PROJECT_FILE_LOC is not None:
699
+ with open(PROJECT_FILE_LOC + "/" + instance_id + ".json") as f:
700
+ d = json.load(f)
701
+ repo_structure = d["structure"]
702
+ else:
703
+ d = get_project_structure_from_scratch(
704
+ repo_name, base_commit, instance_id, playground
705
+ )
706
+ repo_structure = d["structure"]
707
+
708
+ return repo_structure
709
+
710
+
711
+ def get_repo_files(structure, filepaths: list[str]):
712
+ files, classes, functions = get_full_file_paths_and_classes_and_functions(structure)
713
+ file_contents = dict()
714
+ for filepath in filepaths:
715
+ content = None
716
+
717
+ for file_content in files:
718
+ if file_content[0] == filepath:
719
+ content = "\n".join(file_content[1])
720
+ file_contents[filepath] = content
721
+ break
722
+
723
+ assert content is not None, "file not found"
724
+ return file_contents
725
+
726
+
727
+ def correct_file_paths(model_found_files, files):
728
+ found_files = []
729
+ if model_found_files:
730
+ for model_file in model_found_files:
731
+ for file_content in files:
732
+ file = file_content[0]
733
+ if model_file == file:
734
+ found_files.append(file)
735
+ return found_files
736
+ else:
737
+ return []
738
+
739
+
740
+ def clean_method_left_space(method_code: str) -> str:
741
+ indent_space = len(method_code.splitlines()[0]) - len(
742
+ method_code.splitlines()[0].lstrip()
743
+ )
744
+ # remove indent_space in each line
745
+ return "\n".join([line[indent_space:] for line in method_code.splitlines()])
746
+
747
+
748
+ def test_correct_file_paths():
749
+ # Test case 1: Exact match
750
+ model_files1 = ["data.txt", "analysis/report.pdf"]
751
+ files1 = [("data.txt",), ("notes.txt",), ("report/report.pdf",)]
752
+ result1 = correct_file_paths(model_files1, files1)
753
+ assert result1 == ["data.txt"], f"Expected ['data.txt'], but got {result1}"
754
+
755
+ # Test case 2: Subdirectories in model files
756
+ model_files2 = ["subdir/data.txt", "notes/info.txt"]
757
+ files2 = [
758
+ ("work/subdir/data.txt",),
759
+ ("notes/info.txt",),
760
+ ("extras/notes/info.txt",),
761
+ ]
762
+ result2 = correct_file_paths(model_files2, files2)
763
+ assert result2 == [
764
+ "work/subdir/data.txt",
765
+ "notes/info.txt",
766
+ ], f"Expected ['work/subdir/data.txt', 'notes/info.txt'], but got {result2}"
767
+
768
+ # Test case 3: No match
769
+ model_files3 = ["missing.txt"]
770
+ files3 = [("data.txt",), ("notes.txt",), ("analysis/report.pdf",)]
771
+ result3 = correct_file_paths(model_files3, files3)
772
+ assert result3 == [], f"Expected [], but got {result3}"
773
+
774
+ # Test case 4: Multiple potential matches but only first match counts
775
+ model_files4 = ["report.doc"]
776
+ files4 = [("work/report.doc",), ("work/rr/report.docg",)]
777
+ result4 = correct_file_paths(model_files4, files4)
778
+ assert result4 == [
779
+ "work/report.doc"
780
+ ], f"Expected ['work/report.doc'], but got {result4}"
781
+
782
+ # Test case 5: Model file is a subset
783
+ model_files5 = ["data"]
784
+ files5 = [("project/data_analysis/data.txt",), ("data/config.yaml",)]
785
+ result5 = correct_file_paths(model_files5, files5)
786
+ assert result5 == [], f"Expected [], but got {result5}"
787
+
788
+ # Test case 6: File without any folders with two matches
789
+ model_files6 = ["data.txt"]
790
+ files6 = [("project/data_analysis/data.txt",), ("data/config.yaml",), ("data.txt",)]
791
+ result6 = correct_file_paths(model_files6, files6)
792
+ assert result6 == ["data.txt"], f"Expected ['data.txt'], but got {result6}"
793
+
794
+ # Test case 7: File without any folders with only a subdirectory match
795
+ model_files7 = ["data.txt"]
796
+ files7 = [("project/data_analysis/data.txt",), ("data/config.yaml",)]
797
+ result7 = correct_file_paths(model_files7, files7)
798
+ assert result7 == [
799
+ "project/data_analysis/data.txt"
800
+ ], f"Expected ['project/data_analysis/data.txt'], but got {result7}"
801
+
802
+ print("All test cases passed!")
803
+
804
+
805
+ def test_merge():
806
+ # Example usage:
807
+ input_tuples = [(1, 3), (2, 4), (5, 7), (6, 8)]
808
+ merged_tuples = merge_intervals(input_tuples)
809
+ assert merged_tuples == [(1, 4), (5, 8)]
810
+
811
+ input_tuples = [(1, 5), (2, 3)]
812
+ merged_tuples = merge_intervals(input_tuples)
813
+ assert merged_tuples == [(1, 5)]
814
+
815
+ input_tuples = [(1, 1)]
816
+ merged_tuples = merge_intervals(input_tuples)
817
+ assert merged_tuples == [(1, 1)]
818
+
819
+ input_tuples = [(1, 1), (2, 3)]
820
+ merged_tuples = merge_intervals(input_tuples)
821
+ assert merged_tuples == [(1, 1), (2, 3)]
822
+
823
+
824
+ def test_merge():
825
+ # Example usage:
826
+ input_tuples = [(1, 3), (2, 4), (5, 7), (6, 8)]
827
+ merged_tuples = merge_intervals(input_tuples)
828
+ assert merged_tuples == [(1, 4), (5, 8)]
829
+
830
+ input_tuples = [(1, 5), (2, 3)]
831
+ merged_tuples = merge_intervals(input_tuples)
832
+ assert merged_tuples == [(1, 5)]
833
+
834
+ input_tuples = [(1, 1)]
835
+ merged_tuples = merge_intervals(input_tuples)
836
+ assert merged_tuples == [(1, 1)]
837
+
838
+ input_tuples = [(1, 1), (2, 3)]
839
+ merged_tuples = merge_intervals(input_tuples)
840
+ assert merged_tuples == [(1, 1), (2, 3)]
841
+
842
+
843
+ def test_interval_display():
844
+
845
+ content = """
846
+ one
847
+ two
848
+ three
849
+ four
850
+ five
851
+ six
852
+ seven
853
+ eight
854
+ """.strip()
855
+
856
+ x = line_wrap_content(content, [])
857
+ print(x)
858
+
859
+ print("============")
860
+
861
+ x = line_wrap_content(content, [(1, 2), (4, 6), (7, 8)])
862
+ print(x)
863
+
864
+
865
+ if __name__ == "__main__":
866
+ test_merge()
867
+ test_correct_file_paths()
868
+ test_interval_display()
Repos/HWE/agents/Agentless/agentless/util/utils.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import logging
3
+ import os
4
+
5
+
6
+ def load_jsonl(filepath):
7
+ """
8
+ Load a JSONL file from the given filepath.
9
+
10
+ Arguments:
11
+ filepath -- the path to the JSONL file to load
12
+
13
+ Returns:
14
+ A list of dictionaries representing the data in each line of the JSONL file.
15
+ """
16
+ with open(filepath, "r") as file:
17
+ return [json.loads(line) for line in file]
18
+
19
+
20
+ def write_jsonl(data, filepath):
21
+ """
22
+ Write data to a JSONL file at the given filepath.
23
+
24
+ Arguments:
25
+ data -- a list of dictionaries to write to the JSONL file
26
+ filepath -- the path to the JSONL file to write
27
+ """
28
+ with open(filepath, "w") as file:
29
+ for entry in data:
30
+ file.write(json.dumps(entry) + "\n")
31
+
32
+
33
+ def load_json(filepath):
34
+ return json.load(open(filepath, "r"))
35
+
36
+
37
+ def combine_by_instance_id(data):
38
+ """
39
+ Combine data entries by their instance ID.
40
+
41
+ Arguments:
42
+ data -- a list of dictionaries with instance IDs and other information
43
+
44
+ Returns:
45
+ A list of combined dictionaries by instance ID with all associated data.
46
+ """
47
+ combined_data = defaultdict(lambda: defaultdict(list))
48
+ for item in data:
49
+ instance_id = item.get("instance_id")
50
+ if not instance_id:
51
+ continue
52
+ for key, value in item.items():
53
+ if key != "instance_id":
54
+ combined_data[instance_id][key].extend(
55
+ value if isinstance(value, list) else [value]
56
+ )
57
+ return [
58
+ {**{"instance_id": iid}, **details} for iid, details in combined_data.items()
59
+ ]
60
+
61
+
62
+ def setup_logger(log_file):
63
+ logger = logging.getLogger(log_file)
64
+ logger.setLevel(logging.DEBUG)
65
+
66
+ fh = logging.FileHandler(log_file)
67
+ fh.setLevel(logging.DEBUG)
68
+
69
+ formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
70
+ fh.setFormatter(formatter)
71
+
72
+ logger.addHandler(fh)
73
+ return logger
74
+
75
+
76
+ def cleanup_logger(logger):
77
+ handlers = logger.handlers[:]
78
+ for handler in handlers:
79
+ logger.removeHandler(handler)
80
+ handler.close()
81
+
82
+
83
+ def load_existing_instance_ids(output_file):
84
+ instance_ids = set()
85
+ if os.path.exists(output_file):
86
+ with open(output_file, "r") as f:
87
+ for line in f:
88
+ try:
89
+ data = json.loads(line.strip())
90
+ instance_ids.add(data["instance_id"])
91
+ except json.JSONDecodeError:
92
+ continue
93
+ return instance_ids
Repos/HWE/agents/Agentless/agentless_solutions.tar.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d18df3fd3da6ce0a0867f94f82bc98973b2594db37cb702a30617c0e2f6c4dc1
3
+ size 85267
Repos/HWE/agents/Agentless/batch_run.sh ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+
3
+ #export AGENTLESS_MODEL="gpt-5.2"
4
+ #bash run_agentless.sh
5
+ #export AGENTLESS_MODEL="gemini-3-pro"
6
+ #bash run_agentless.sh
7
+ #export AGENTLESS_MODEL="glm-4.6"
8
+ #bash run_agentless.sh
9
+ #export AGENTLESS_MODEL="minimax-m2"
10
+ #bash run_agentless.sh
11
+ export AGENTLESS_MODEL="deepseek-v3.2"
12
+ bash run_agentless.sh
13
+ #export AGENTLESS_MODEL="qwen3-coder-plus"
14
+ #bash run_agentless.sh
Repos/HWE/agents/Agentless/build_dataset.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import json
3
+ import os
4
+ import sys
5
+
6
+
7
+ DEFAULT_DATASET_DIR = "/workspace/phoenix-bench/data/snapshots"
8
+ DEFAULT_ISSUES_DIR = "/workspace/phoenix-bench/data/issues"
9
+
10
+
11
+ def read_issue_text(issues_dir, instance_id):
12
+ issue_path = os.path.join(issues_dir, instance_id)
13
+ if not os.path.isfile(issue_path):
14
+ return None
15
+ with open(issue_path, "r", encoding="utf-8") as f:
16
+ return f.read().strip()
17
+
18
+
19
+ def build_dataset(dataset_dir, issues_dir):
20
+ entries = []
21
+ missing = []
22
+
23
+ for name in sorted(os.listdir(dataset_dir)):
24
+ repo_path = os.path.join(dataset_dir, name)
25
+ if not os.path.isdir(repo_path):
26
+ continue
27
+
28
+ problem_statement = read_issue_text(issues_dir, name)
29
+ if problem_statement is None:
30
+ missing.append(name)
31
+ continue
32
+
33
+ entries.append(
34
+ {
35
+ "instance_id": name,
36
+ "repo": repo_path,
37
+ "base_commit": None,
38
+ "problem_statement": problem_statement,
39
+ }
40
+ )
41
+
42
+ return entries, missing
43
+
44
+
45
+ def write_output(entries, output_path, jsonl=False):
46
+ if jsonl:
47
+ with open(output_path, "w", encoding="utf-8") as f:
48
+ for entry in entries:
49
+ f.write(json.dumps(entry) + "\n")
50
+ return
51
+
52
+ with open(output_path, "w", encoding="utf-8") as f:
53
+ json.dump(entries, f, indent=2)
54
+
55
+
56
+ def parse_args():
57
+ parser = argparse.ArgumentParser(
58
+ description="Build Agentless dataset JSON/JSONL from local repos and issue text."
59
+ )
60
+ parser.add_argument(
61
+ "--dataset-dir",
62
+ default=DEFAULT_DATASET_DIR,
63
+ help="Directory containing repo subdirectories.",
64
+ )
65
+ parser.add_argument(
66
+ "--issues-dir",
67
+ default=DEFAULT_ISSUES_DIR,
68
+ help="Directory containing issue text files named by instance_id.",
69
+ )
70
+ parser.add_argument(
71
+ "--output",
72
+ default="/workspace/phoenix-bench/Agentless/agentless_dataset.json",
73
+ help="Output path (.json or .jsonl). Defaults next to dataset dir.",
74
+ )
75
+ parser.add_argument(
76
+ "--jsonl",
77
+ action="store_true",
78
+ help="Write JSONL instead of JSON array.",
79
+ )
80
+ return parser.parse_args()
81
+
82
+
83
+ def main():
84
+ args = parse_args()
85
+
86
+ dataset_dir = os.path.abspath(args.dataset_dir)
87
+ issues_dir = os.path.abspath(args.issues_dir)
88
+ if args.output:
89
+ output_path = args.output
90
+ else:
91
+ suffix = ".jsonl" if args.jsonl else ".json"
92
+ output_path = os.path.join(
93
+ os.path.dirname(dataset_dir), os.path.basename(dataset_dir) + suffix
94
+ )
95
+
96
+ entries, missing = build_dataset(dataset_dir, issues_dir)
97
+ write_output(entries, output_path, jsonl=args.jsonl)
98
+
99
+ print(f"Wrote {len(entries)} entries to {output_path}")
100
+ if missing:
101
+ print(
102
+ "Missing issue files for: " + ", ".join(missing),
103
+ file=sys.stderr,
104
+ )
105
+
106
+
107
+ if __name__ == "__main__":
108
+ main()
Repos/HWE/agents/Agentless/build_solutions.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ import argparse
3
+ import json
4
+ from pathlib import Path
5
+
6
+
7
+ def _safe_name(name: str) -> str:
8
+ return name.replace("/", "__")
9
+
10
+
11
+ def _resolve_input_path(results_root: Path, model_name: str) -> Path:
12
+ candidates = []
13
+ for candidate_dir in [model_name, _safe_name(model_name), ""]:
14
+ if candidate_dir:
15
+ candidate = (
16
+ results_root / candidate_dir / "output_0_processed.jsonl"
17
+ ).resolve()
18
+ else:
19
+ candidate = (results_root / "output_0_processed.jsonl").resolve()
20
+ candidates.append(candidate)
21
+ if candidate.exists():
22
+ return candidate
23
+
24
+ joined = "\n".join(str(p) for p in candidates)
25
+ raise FileNotFoundError(
26
+ "Could not find output_0_processed.jsonl for model. Checked:\n" + joined
27
+ )
28
+
29
+
30
+ def _load_jsonl(path: Path) -> list[dict]:
31
+ rows = []
32
+ with path.open("r", encoding="utf-8") as f:
33
+ for line in f:
34
+ line = line.strip()
35
+ if not line:
36
+ continue
37
+ rows.append(json.loads(line))
38
+ return rows
39
+
40
+
41
+ def main() -> None:
42
+ parser = argparse.ArgumentParser(
43
+ description=(
44
+ "Build OpenHands-style solutions jsonl from Agentless repair outputs."
45
+ )
46
+ )
47
+ parser.add_argument("--model_name", required=True, help="Model name to collect.")
48
+ parser.add_argument(
49
+ "--results_root",
50
+ default="/workspace/phoenix-bench/Agentless/results/hwe-bench-lite/repair_sample_verilog",
51
+ help="Root folder containing <model_name>/output_0_processed.jsonl.",
52
+ )
53
+ parser.add_argument(
54
+ "--dataset_path",
55
+ default="/workspace/phoenix-bench/Agentless/agentless_dataset.json",
56
+ help="Agentless dataset json used for repo_name mapping.",
57
+ )
58
+ parser.add_argument(
59
+ "--output_path",
60
+ default="",
61
+ help=(
62
+ "Output jsonl path. Defaults to "
63
+ "agentless_solutions_<model_name>_<dataset_size>.jsonl in Agentless root."
64
+ ),
65
+ )
66
+ args = parser.parse_args()
67
+
68
+ script_dir = Path(__file__).resolve().parent
69
+ results_root = Path(args.results_root).resolve()
70
+ dataset_path = Path(args.dataset_path).resolve()
71
+
72
+ input_path = _resolve_input_path(results_root, args.model_name)
73
+
74
+ with dataset_path.open("r", encoding="utf-8") as f:
75
+ dataset = json.load(f)
76
+
77
+ patches = _load_jsonl(input_path)
78
+ patch_by_instance = {}
79
+ for row in patches:
80
+ instance_id = row.get("instance_id")
81
+ if not instance_id:
82
+ continue
83
+ patch_by_instance[instance_id] = row.get("model_patch", "")
84
+
85
+ output_path = (
86
+ Path(args.output_path).resolve()
87
+ if args.output_path
88
+ else (
89
+ script_dir
90
+ / f"agentless_solutions_{_safe_name(args.model_name)}_{len(dataset)}.jsonl"
91
+ ).resolve()
92
+ )
93
+ output_path.parent.mkdir(parents=True, exist_ok=True)
94
+
95
+ missing = 0
96
+ with output_path.open("w", encoding="utf-8") as f:
97
+ for item in dataset:
98
+ instance_id = item["instance_id"]
99
+ solution = patch_by_instance.get(instance_id, "")
100
+ if instance_id not in patch_by_instance:
101
+ missing += 1
102
+ out = {
103
+ "repo_name": item["repo"],
104
+ "solution": solution,
105
+ }
106
+ f.write(json.dumps(out, ensure_ascii=False) + "\n")
107
+
108
+ print(f"Input: {input_path}")
109
+ print(f"Output: {output_path}")
110
+ print(f"Rows: {len(dataset)}")
111
+ print(f"Missing patches filled with empty solution: {missing}")
112
+
113
+
114
+ if __name__ == "__main__":
115
+ main()
Repos/HWE/agents/Agentless/classification/README.md ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SWE-bench Lite-*S* and problem classifications
2
+
3
+ Here we provide our manual classifications of the problems in SWE-bench lite
4
+
5
+ > [!NOTE]
6
+ >
7
+ > The classification results differ slightly with the paper as we have performed further manual checking and modified the classifications of few problems.
8
+
9
+ ## Quick Setup
10
+
11
+ First install the neccessary graphing utilizies:
12
+
13
+ ```shell
14
+ cd classification
15
+ pip install -r requirements_graph.txt
16
+ ```
17
+
18
+ ## Graphing
19
+
20
+ Run the following command to produce Figure 5 in the paper:
21
+
22
+ ```shell
23
+ python graph_classification.py
24
+ ```
25
+
26
+ This will produce various graphs: `benchmark_bar_location.pdf`, `benchmark_pie_description.pdf`, and `benchmark_pie_patch.pdf`
27
+
28
+ For the detailed classifications, we have released our raw classifications for each problem and can be access in `swebench_lite_classifications.csv`
29
+
30
+ ## SWE-bench Lite-*S* problems
31
+
32
+ To obtain the problems in SWE-bench Lite-*S*, run the following command:
33
+
34
+ ```shell
35
+ python load_filtered_benchmark.py
36
+ ```
37
+
38
+ This produces the `swebench_lite_s_problems.txt` which contains the instance_ids of the subset of problems
39
+
40
+ Note: we filter out the problems that contain the exact patch in the problem description, misleading solutions, or do not provide enough information in the original issue description.
Repos/HWE/agents/Agentless/classification/graph_classification.py ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import matplotlib as mpl
2
+ from matplotlib import pyplot as plt
3
+
4
+ plt.style.use(
5
+ "https://github.com/dhaitz/matplotlib-stylesheets/raw/master/pacoty.mplstyle"
6
+ )
7
+ plt.rcParams["font.family"] = "monospace"
8
+ plt.rcParams["font.weight"] = "bold"
9
+ plt.rcParams.update({"font.size": 10})
10
+
11
+ plt.rcParams["axes.facecolor"] = "#FFFFFF"
12
+ plt.rcParams["axes.edgecolor"] = "black"
13
+
14
+ mpl.rcParams["axes.prop_cycle"] = mpl.cycler(
15
+ color=[
16
+ "#9fc5e8",
17
+ "#b4a7d6",
18
+ "#b6d7a8",
19
+ "#ea9999",
20
+ "#d5a6bd",
21
+ "#8c564b",
22
+ "#e377c2",
23
+ "#7f7f7f",
24
+ "#bcbd22",
25
+ "#17becf",
26
+ ]
27
+ )
28
+
29
+ from load_filtered_benchmark import load_classification_results
30
+
31
+
32
+ def graph_benchmark_classification():
33
+
34
+ instance_id_to_type = load_classification_results()
35
+
36
+ description_to_count = {}
37
+ description_patch_to_count = {}
38
+ location_to_count = {}
39
+ location_function_to_count = {}
40
+ location_file_to_count = {}
41
+ location_line_to_count = {}
42
+
43
+ for instance_id, classification in instance_id_to_type.items():
44
+ description = classification["description_classification"]
45
+ description_patch = classification["solution_classification"]
46
+ location_line = classification["line_location"]
47
+ location_function = classification["function_location"]
48
+ location_file = classification["file_location"]
49
+ location = classification["line_location"]
50
+
51
+ if description in description_to_count:
52
+ description_to_count[description] += 1
53
+ else:
54
+ description_to_count[description] = 1
55
+
56
+ if description_patch in description_patch_to_count:
57
+ description_patch_to_count[description_patch] += 1
58
+ else:
59
+ description_patch_to_count[description_patch] = 1
60
+
61
+ if (
62
+ location_line == "Natural language"
63
+ or location_function == "Natural language"
64
+ or location_file == "Natural language"
65
+ ):
66
+ location = "Natural language"
67
+ elif (
68
+ location_line == "Stacktrace"
69
+ or location_function == "Stacktrace"
70
+ or location_file == "Stacktrace"
71
+ ):
72
+ location = "Stacktrace"
73
+ elif (
74
+ location_line == "Keywords"
75
+ or location_function == "Keywords"
76
+ or location_file == "Keywords"
77
+ ):
78
+ location = "Keywords"
79
+ else:
80
+ location = "None"
81
+
82
+ if location in location_to_count:
83
+ location_to_count[location] += 1
84
+ else:
85
+ location_to_count[location] = 1
86
+
87
+ if location_line in location_line_to_count:
88
+ location_line_to_count[location_line] += 1
89
+ else:
90
+ location_line_to_count[location_line] = 1
91
+
92
+ if location_function in location_function_to_count:
93
+ location_function_to_count[location_function] += 1
94
+ else:
95
+ location_function_to_count[location_function] = 1
96
+
97
+ if location_file in location_file_to_count:
98
+ location_file_to_count[location_file] += 1
99
+ else:
100
+ location_file_to_count[location_file] = 1
101
+
102
+ fig, ax = plt.subplots(1, 1, figsize=(6, 5))
103
+
104
+ wdges, labels, autopct = ax.pie(
105
+ description_to_count.values(),
106
+ labels=[x.replace(" ", "\n") for x in description_to_count.keys()],
107
+ explode=[
108
+ 0.1 if x == "Not enough info" else 0.02 for x in description_to_count.keys()
109
+ ],
110
+ autopct="%1.1f%%",
111
+ shadow={"ox": -0.04, "edgecolor": "none", "shade": 0.5},
112
+ textprops={"fontsize": 18},
113
+ )
114
+ plt.setp(labels, fontsize=12)
115
+ fig.tight_layout()
116
+ plt.savefig("benchmark_pie_description.pdf")
117
+
118
+ fig, ax = plt.subplots(1, 1, figsize=(6, 5))
119
+
120
+ wdges, labels, autopct = ax.pie(
121
+ description_patch_to_count.values(),
122
+ labels=[x.replace(" ", "\n") for x in description_patch_to_count.keys()],
123
+ explode=[
124
+ 0.1 if x == "Exact patch" else 0.02
125
+ for x in description_patch_to_count.keys()
126
+ ],
127
+ autopct="%1.1f%%",
128
+ shadow={"ox": -0.04, "edgecolor": "none", "shade": 0.5},
129
+ startangle=90,
130
+ textprops={"fontsize": 18},
131
+ )
132
+ plt.setp(labels, fontsize=12)
133
+
134
+ fig.tight_layout()
135
+ plt.savefig("benchmark_pie_patch.pdf")
136
+
137
+ # 4 stack bar plots
138
+ fig, ax = plt.subplots(1, 1, figsize=(6, 5))
139
+
140
+ bottom = [0, 0, 0, 0]
141
+ counts = {}
142
+
143
+ width = 0.5
144
+
145
+ for loc in ["None", "Stacktrace", "Natural language", "Keywords"]:
146
+ if loc == "Stacktrace":
147
+ counts["Stack trace"] = []
148
+ if loc in location_line_to_count:
149
+ counts["Stack trace"].append(location_line_to_count[loc] / 3)
150
+ else:
151
+ counts["Stack trace"].append(0)
152
+
153
+ counts["Stack trace"].append(location_function_to_count[loc] / 3)
154
+ counts["Stack trace"].append(location_file_to_count[loc] / 3)
155
+ counts["Stack trace"].append(location_to_count[loc] / 3)
156
+ else:
157
+ counts[loc] = []
158
+
159
+ if loc in location_line_to_count:
160
+ counts[loc].append(location_line_to_count[loc] / 3)
161
+ else:
162
+ counts[loc].append(0)
163
+
164
+ counts[loc].append(location_function_to_count[loc] / 3)
165
+ counts[loc].append(location_file_to_count[loc] / 3)
166
+ counts[loc].append(location_to_count[loc] / 3)
167
+
168
+ for label, count in counts.items():
169
+ ax.bar(
170
+ ["Line", "Function", "File", "Overall"],
171
+ count,
172
+ bottom=bottom,
173
+ label=label,
174
+ width=width,
175
+ )
176
+ bottom = [sum(x) for x in zip(bottom, count)]
177
+
178
+ # write text
179
+ for i, v in enumerate(count):
180
+ if v == 0:
181
+ continue
182
+ ax.text(
183
+ i,
184
+ bottom[i] - v / 1.5,
185
+ str(round(v, 1)) + "%",
186
+ color="black",
187
+ fontweight="bold",
188
+ ha="center",
189
+ fontsize=15,
190
+ )
191
+
192
+ ax.set_ylabel("Percentage")
193
+ ax.legend(fancybox=True, shadow=True, prop={"size": 10}, frameon=True)
194
+ fig.tight_layout()
195
+ plt.savefig("benchmark_bar_location.pdf")
196
+
197
+
198
+ if __name__ == "__main__":
199
+ graph_benchmark_classification()
Repos/HWE/agents/Agentless/classification/load_filtered_benchmark.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ def load_classification_results():
2
+ import csv
3
+
4
+ instance_id_to_type = {}
5
+
6
+ with open("swebench_lite_classifications.csv", "r") as f:
7
+ reader = csv.reader(f)
8
+ # skip first row
9
+ next(reader)
10
+ for row in reader:
11
+ instance_id = row[0]
12
+
13
+ instance_id_to_type[instance_id] = {
14
+ "problem_statement": row[1],
15
+ "gt_patch": row[2],
16
+ "test_patch": row[3],
17
+ "description_classification": row[4],
18
+ "solution_classification": row[5],
19
+ "line_location": row[6],
20
+ "function_location": row[7],
21
+ "file_location": row[8],
22
+ }
23
+
24
+ return instance_id_to_type
25
+
26
+
27
+ def load_swebench_s_problems():
28
+
29
+ instance_id_to_type = load_classification_results()
30
+ description_to_instance_id = {}
31
+ description_patch_to_instance_id = {}
32
+
33
+ for instance_id, instance_type in instance_id_to_type.items():
34
+ if (
35
+ instance_type["description_classification"]
36
+ not in description_to_instance_id
37
+ ):
38
+ description_to_instance_id[instance_type["description_classification"]] = []
39
+
40
+ description_to_instance_id[instance_type["description_classification"]].append(
41
+ instance_id
42
+ )
43
+
44
+ if (
45
+ instance_type["solution_classification"]
46
+ not in description_patch_to_instance_id
47
+ ):
48
+ description_patch_to_instance_id[
49
+ instance_type["solution_classification"]
50
+ ] = []
51
+
52
+ description_patch_to_instance_id[
53
+ instance_type["solution_classification"]
54
+ ].append(instance_id)
55
+
56
+ filtered_set = set([instance_id for instance_id in instance_id_to_type.keys()])
57
+
58
+ filtered_set = (
59
+ filtered_set
60
+ - set(description_to_instance_id["Not enough info"])
61
+ - set(description_patch_to_instance_id["Misleading"])
62
+ - set(description_patch_to_instance_id["Exact patch"])
63
+ )
64
+
65
+ with open("swebench_lite_s_problems.txt", "w") as f:
66
+ for instance_id in filtered_set:
67
+ f.write(instance_id + "\n")
68
+
69
+
70
+ if __name__ == "__main__":
71
+ load_swebench_s_problems()
Repos/HWE/agents/Agentless/classification/requirements_graph.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ matplotlib
2
+ venn
Repos/HWE/agents/Agentless/classification/swebench_lite_classifications.csv ADDED
The diff for this file is too large to render. See raw diff
 
Repos/HWE/agents/Agentless/get_repo_structure/get_patch_info.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import json
3
+ import re
4
+ from collections import defaultdict
5
+
6
+
7
+ def parse_patch(patch):
8
+ """
9
+ Parse a git patch into a structured format.
10
+
11
+ Parameters:
12
+ patch (str): The git patch as a string.
13
+
14
+ Returns:
15
+ list: A list of dictionaries representing the file changes and hunks.
16
+ """
17
+ file_changes = []
18
+ current_file = None
19
+ current_hunk = None
20
+ deleted_lines = 0
21
+
22
+ patch_lines = patch.split("\n")
23
+ for line in patch_lines:
24
+ if line.startswith("diff --git"):
25
+ # Reset for new files
26
+ if current_file:
27
+ file_changes.append(current_file)
28
+ current_file = {"file": "", "hunks": []}
29
+ elif line.startswith("--- a/"):
30
+ pass
31
+ elif line.startswith("+++ b/"):
32
+ if current_file is not None:
33
+ current_file["file"] = line[6:]
34
+ elif line.startswith("@@ "):
35
+ if current_file is not None:
36
+ match = re.match(r"@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@", line)
37
+ if match:
38
+ current_hunk = {"start_line": int(match.group(2)), "changes": []}
39
+ current_file["hunks"].append(current_hunk)
40
+ deleted_lines = 0
41
+ added_lines = 0
42
+ elif line.startswith("+") or line.startswith("-"):
43
+ if current_hunk is not None:
44
+ change_type = "add" if line.startswith("+") else "delete"
45
+ if change_type == "delete":
46
+ deleted_lines += 1
47
+ current_hunk["changes"].append(
48
+ {
49
+ "type": change_type,
50
+ "content": line[1:].strip(),
51
+ "line": current_hunk["start_line"] - added_lines,
52
+ }
53
+ )
54
+ current_hunk["start_line"] += 1
55
+ else:
56
+ added_lines += 1
57
+ current_hunk["changes"].append(
58
+ {
59
+ "type": change_type,
60
+ "content": line[1:].strip(),
61
+ "line": current_hunk["start_line"] - deleted_lines,
62
+ }
63
+ )
64
+ current_hunk["start_line"] += 1
65
+ else:
66
+ if current_hunk is not None:
67
+ current_hunk["start_line"] += 1
68
+
69
+ if current_file:
70
+ file_changes.append(current_file)
71
+
72
+ return file_changes
Repos/HWE/agents/Agentless/get_repo_structure/get_repo_structure.py ADDED
@@ -0,0 +1,376 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import json
3
+ import os
4
+ import subprocess
5
+ import uuid
6
+
7
+ import pandas as pd
8
+ from tqdm import tqdm
9
+ from tree_sitter import Language, Parser
10
+
11
+ repo_to_top_folder = {
12
+ "django/django": "django",
13
+ "sphinx-doc/sphinx": "sphinx",
14
+ "scikit-learn/scikit-learn": "scikit-learn",
15
+ "sympy/sympy": "sympy",
16
+ "pytest-dev/pytest": "pytest",
17
+ "matplotlib/matplotlib": "matplotlib",
18
+ "astropy/astropy": "astropy",
19
+ "pydata/xarray": "xarray",
20
+ "mwaskom/seaborn": "seaborn",
21
+ "psf/requests": "requests",
22
+ "pylint-dev/pylint": "pylint",
23
+ "pallets/flask": "flask",
24
+ }
25
+
26
+ _PARSER = None
27
+ _MODULE_NODE_TYPES = {
28
+ "module_declaration",
29
+ "interface_declaration",
30
+ "program_declaration",
31
+ "package_declaration",
32
+ "class_declaration",
33
+ "interface_class_declaration",
34
+ "checker_declaration",
35
+ "config_declaration",
36
+ "primitive_declaration",
37
+ "udp_declaration",
38
+ }
39
+ _FUNC_NODE_TYPES = {
40
+ "function_declaration",
41
+ "task_declaration",
42
+ "function_prototype",
43
+ "task_prototype",
44
+ "method_declaration",
45
+ "method_prototype",
46
+ "class_constructor_declaration",
47
+ "class_constructor_prototype",
48
+ }
49
+ _VERILOG_EXTENSIONS = {".v", ".sv", ".vh", ".svh"}
50
+ _ATTRIBUTE_NODE_TYPES = {"attribute_instance"}
51
+ _SIMPLE_IDENTIFIER_NODE_TYPES = {
52
+ "simple_identifier",
53
+ "escaped_identifier",
54
+ "module_identifier",
55
+ "udp_identifier",
56
+ }
57
+
58
+
59
+ def _get_verilog_parser():
60
+ global _PARSER
61
+ if _PARSER is None:
62
+ so_path = os.environ.get("TREE_SITTER_VERILOG_SO")
63
+ language_name = os.environ.get("TREE_SITTER_VERILOG_LANGUAGE", "verilog")
64
+ if not so_path:
65
+ raise RuntimeError(
66
+ "TREE_SITTER_VERILOG_SO must point to a tree-sitter-verilog .so file"
67
+ )
68
+ if not os.path.isfile(so_path):
69
+ raise RuntimeError(f"tree-sitter .so not found: {so_path}")
70
+ try:
71
+ language = Language(so_path, language_name)
72
+ except TypeError:
73
+ import ctypes
74
+
75
+ symbol = os.environ.get(
76
+ "TREE_SITTER_VERILOG_SYMBOL", f"tree_sitter_{language_name}"
77
+ )
78
+ lib = ctypes.CDLL(so_path)
79
+ try:
80
+ func = getattr(lib, symbol)
81
+ except AttributeError as exc:
82
+ raise RuntimeError(
83
+ f"tree-sitter language symbol '{symbol}' not found in {so_path}"
84
+ ) from exc
85
+ func.restype = ctypes.c_void_p
86
+ language = Language(func())
87
+ parser = Parser()
88
+ if hasattr(parser, "set_language"):
89
+ parser.set_language(language)
90
+ else:
91
+ parser.language = language
92
+ _PARSER = parser
93
+ return _PARSER
94
+
95
+
96
+ def _node_text(node, source_bytes):
97
+ return source_bytes[node.start_byte : node.end_byte].decode(
98
+ "utf-8", errors="replace"
99
+ )
100
+
101
+
102
+ def _iter_tree(node):
103
+ stack = [node]
104
+ while stack:
105
+ current = stack.pop()
106
+ yield current
107
+ if current.children:
108
+ stack.extend(reversed(current.children))
109
+
110
+
111
+ def _find_child(node, type_set):
112
+ for child in node.children:
113
+ if child.type in type_set:
114
+ return child
115
+ return None
116
+
117
+
118
+ def _find_identifier(node, identifier_types):
119
+ for child in node.children:
120
+ if child.type in _ATTRIBUTE_NODE_TYPES:
121
+ continue
122
+ if child.type in identifier_types:
123
+ return child
124
+ return None
125
+
126
+
127
+ def _name_from_direct(node, source_bytes, identifier_types):
128
+ name_node = _find_identifier(node, identifier_types)
129
+ if name_node is None:
130
+ return None
131
+ return _node_text(name_node, source_bytes).strip()
132
+
133
+
134
+ def _name_from_child(node, source_bytes, child_types, identifier_types):
135
+ child = _find_child(node, child_types)
136
+ if child is None:
137
+ return None
138
+ return _name_from_direct(child, source_bytes, identifier_types)
139
+
140
+
141
+ def _node_key(node):
142
+ return (node.start_byte, node.end_byte, node.type)
143
+
144
+
145
+ def _node_name(node, source_bytes):
146
+ node_type = node.type
147
+ if node_type == "module_declaration":
148
+ return _name_from_child(
149
+ node, source_bytes, {"module_header"}, _SIMPLE_IDENTIFIER_NODE_TYPES
150
+ ) or _name_from_direct(node, source_bytes, _SIMPLE_IDENTIFIER_NODE_TYPES)
151
+ if node_type == "udp_declaration":
152
+ return _name_from_child(
153
+ node,
154
+ source_bytes,
155
+ {"udp_nonansi_declaration", "udp_ansi_declaration"},
156
+ _SIMPLE_IDENTIFIER_NODE_TYPES,
157
+ ) or _name_from_direct(node, source_bytes, _SIMPLE_IDENTIFIER_NODE_TYPES)
158
+ if node_type == "interface_declaration":
159
+ name = _name_from_direct(node, source_bytes, {"interface_identifier"})
160
+ if name:
161
+ return name
162
+ return _name_from_child(
163
+ node,
164
+ source_bytes,
165
+ {"interface_nonansi_header", "interface_ansi_header"},
166
+ {"interface_identifier"},
167
+ )
168
+ if node_type == "program_declaration":
169
+ name = _name_from_direct(node, source_bytes, {"program_identifier"})
170
+ if name:
171
+ return name
172
+ return _name_from_child(
173
+ node,
174
+ source_bytes,
175
+ {"program_nonansi_header", "program_ansi_header"},
176
+ {"program_identifier"},
177
+ )
178
+ if node_type == "package_declaration":
179
+ return _name_from_direct(node, source_bytes, {"package_identifier"})
180
+ if node_type in {"class_declaration", "interface_class_declaration"}:
181
+ return _name_from_direct(node, source_bytes, {"class_identifier"})
182
+ if node_type == "checker_declaration":
183
+ return _name_from_direct(node, source_bytes, {"checker_identifier"})
184
+ if node_type == "config_declaration":
185
+ return _name_from_direct(node, source_bytes, {"config_identifier"})
186
+ if node_type == "function_declaration":
187
+ return _name_from_child(
188
+ node, source_bytes, {"function_body_declaration"}, {"function_identifier"}
189
+ )
190
+ if node_type == "task_declaration":
191
+ return _name_from_child(
192
+ node, source_bytes, {"task_body_declaration"}, {"task_identifier"}
193
+ )
194
+ if node_type == "function_prototype":
195
+ return _name_from_direct(node, source_bytes, {"function_identifier"})
196
+ if node_type == "task_prototype":
197
+ return _name_from_direct(node, source_bytes, {"task_identifier"})
198
+ if node_type in {"class_constructor_declaration", "class_constructor_prototype"}:
199
+ return "new"
200
+ return None
201
+
202
+
203
+ def _find_enclosing_container(node, container_by_id):
204
+ parent = node.parent
205
+ while parent is not None:
206
+ node_key = _node_key(parent)
207
+ if node_key in container_by_id:
208
+ return container_by_id[node_key]
209
+ parent = parent.parent
210
+ return None
211
+
212
+
213
+ def checkout_commit(repo_path, commit_id):
214
+ """Checkout the specified commit in the given local git repository.
215
+ :param repo_path: Path to the local git repository
216
+ :param commit_id: Commit ID to checkout
217
+ :return: None
218
+ """
219
+ try:
220
+ # Change directory to the provided repository path and checkout the specified commit
221
+ print(f"Checking out commit {commit_id} in repository at {repo_path}...")
222
+ subprocess.run(["git", "-C", repo_path, "checkout", commit_id], check=True)
223
+ print("Commit checked out successfully.")
224
+ except subprocess.CalledProcessError as e:
225
+ print(f"An error occurred while running git command: {e}")
226
+ except Exception as e:
227
+ print(f"An unexpected error occurred: {e}")
228
+
229
+
230
+ def clone_repo(repo_name, repo_playground):
231
+ try:
232
+
233
+ print(
234
+ f"Cloning repository from https://github.com/{repo_name}.git to {repo_playground}/{repo_to_top_folder[repo_name]}..."
235
+ )
236
+ subprocess.run(
237
+ [
238
+ "git",
239
+ "clone",
240
+ f"https://github.com/{repo_name}.git",
241
+ f"{repo_playground}/{repo_to_top_folder[repo_name]}",
242
+ ],
243
+ check=True,
244
+ )
245
+ print("Repository cloned successfully.")
246
+ except subprocess.CalledProcessError as e:
247
+ print(f"An error occurred while running git command: {e}")
248
+ except Exception as e:
249
+ print(f"An unexpected error occurred: {e}")
250
+
251
+
252
+ def get_project_structure_from_scratch(
253
+ repo_name, commit_id, instance_id, repo_playground
254
+ ):
255
+
256
+ # Generate a temperary folder and add uuid to avoid collision
257
+ repo_playground = os.path.join(repo_playground, str(uuid.uuid4()))
258
+
259
+ # assert playground doesn't exist
260
+ assert not os.path.exists(repo_playground), f"{repo_playground} already exists"
261
+
262
+ # create playground
263
+ os.makedirs(repo_playground)
264
+
265
+ #clone_repo(repo_name, repo_playground)
266
+ #checkout_commit(f"{repo_playground}/{repo_to_top_folder[repo_name]}", commit_id)
267
+ #structure = create_structure(f"{repo_playground}/{repo_to_top_folder[repo_name]}")
268
+ structure = create_structure(f"{repo_name}")
269
+ # clean up
270
+ #subprocess.run(
271
+ # ["rm", "-rf", f"{repo_playground}/{repo_to_top_folder[repo_name]}"], check=True
272
+ #)
273
+ d = {
274
+ "repo": repo_name,
275
+ "base_commit": commit_id,
276
+ "structure": structure,
277
+ "instance_id": instance_id,
278
+ }
279
+ return d
280
+
281
+
282
+ def parse_verilog_file(file_path, file_content=None):
283
+ """Parse a Verilog/SystemVerilog file with tree-sitter."""
284
+ if file_content is None:
285
+ try:
286
+ with open(file_path, "r") as file:
287
+ file_content = file.read()
288
+ except Exception as e: # Catch all types of exceptions
289
+ print(f"Error in file {file_path}: {e}")
290
+ return [], [], ""
291
+
292
+ parser = _get_verilog_parser()
293
+ source_bytes = file_content.encode("utf-8", errors="replace")
294
+ tree = parser.parse(source_bytes)
295
+
296
+ class_info = []
297
+ function_names = []
298
+ container_by_id = {}
299
+ lines = file_content.splitlines()
300
+
301
+ for node in _iter_tree(tree.root_node):
302
+ if node.type not in _MODULE_NODE_TYPES:
303
+ continue
304
+
305
+ container_name = _node_name(node, source_bytes)
306
+ if not container_name:
307
+ continue
308
+ start_line = node.start_point[0] + 1
309
+ end_line = node.end_point[0] + 1
310
+
311
+ container_info = {
312
+ "name": container_name,
313
+ "start_line": start_line,
314
+ "end_line": end_line,
315
+ "text": lines[start_line - 1 : end_line],
316
+ "methods": [],
317
+ }
318
+ class_info.append(container_info)
319
+ container_by_id[_node_key(node)] = container_info
320
+
321
+ for node in _iter_tree(tree.root_node):
322
+ if node.type not in _FUNC_NODE_TYPES:
323
+ continue
324
+ func_name = _node_name(node, source_bytes)
325
+ if not func_name:
326
+ continue
327
+ start_line = node.start_point[0] + 1
328
+ end_line = node.end_point[0] + 1
329
+ func_info = {
330
+ "name": func_name,
331
+ "start_line": start_line,
332
+ "end_line": end_line,
333
+ "text": lines[start_line - 1 : end_line],
334
+ }
335
+ container_info = _find_enclosing_container(node, container_by_id)
336
+ if container_info is None:
337
+ function_names.append(func_info)
338
+ else:
339
+ container_info["methods"].append(func_info)
340
+
341
+ return class_info, function_names, lines
342
+
343
+
344
+ def parse_python_file(file_path, file_content=None):
345
+ """Compatibility shim: parses Verilog/SystemVerilog files."""
346
+ return parse_verilog_file(file_path, file_content)
347
+
348
+
349
+ def create_structure(directory_path):
350
+ """Create the structure of the repository directory by parsing Verilog files."""
351
+ structure = {}
352
+
353
+ for root, _, files in os.walk(directory_path):
354
+ repo_name = os.path.basename(directory_path)
355
+ relative_root = os.path.relpath(root, directory_path)
356
+ if relative_root == ".":
357
+ relative_root = repo_name
358
+ curr_struct = structure
359
+ for part in relative_root.split(os.sep):
360
+ if part not in curr_struct:
361
+ curr_struct[part] = {}
362
+ curr_struct = curr_struct[part]
363
+ for file_name in files:
364
+ _, ext = os.path.splitext(file_name)
365
+ if ext.lower() in _VERILOG_EXTENSIONS:
366
+ file_path = os.path.join(root, file_name)
367
+ class_info, function_names, file_lines = parse_verilog_file(file_path)
368
+ curr_struct[file_name] = {
369
+ "classes": class_info,
370
+ "functions": function_names,
371
+ "text": file_lines,
372
+ }
373
+ else:
374
+ curr_struct[file_name] = {}
375
+
376
+ return structure
Repos/HWE/agents/Agentless/requirements.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ anthropic
2
+ openai
3
+ pre-commit
4
+ datasets
5
+ tiktoken
6
+ libcst
7
+ llama-index
8
+ jsonlines
9
+ swebench @ git+https://github.com/princeton-nlp/SWE-bench
Repos/HWE/agents/Agentless/resources/comparison_graph.png ADDED

Git LFS Details

  • SHA256: 37b533748e6825cb35261f47c553adce581726581d3942510abca8f71986a18b
  • Pointer size: 130 Bytes
  • Size of remote file: 60.6 kB
Repos/HWE/agents/Agentless/run_agentless.py ADDED
@@ -0,0 +1,359 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ import argparse
3
+ import os
4
+ import selectors
5
+ import subprocess
6
+ import sys
7
+ import time
8
+
9
+
10
+ def _safe_model_dir_name(model_name: str) -> str:
11
+ return model_name.replace("/", "__")
12
+
13
+
14
+ def _build_env():
15
+ env = os.environ.copy()
16
+ env["OPENAI_API_BASE"] = "https://api.openai.com/v1"
17
+ env["OPENAI_API_KEY"] = "YOUR_OPENAI_API_KEY"
18
+ env["TREE_SITTER_VERILOG_SO"] = "/workspace/phoenix-bench/Agentless/my-languages.so"
19
+ env["PYTHONPATH"] = f'{env.get("PYTHONPATH", "")}:{os.getcwd()}'
20
+ env["PYTHONUNBUFFERED"] = "1"
21
+ return env
22
+
23
+
24
+ def run_cmd(cmd, env, cwd):
25
+ subprocess.run(cmd, env=env, cwd=cwd, check=True)
26
+
27
+
28
+ def _run_cmd_streaming(cmd, env, cwd, capture_limit=1024 * 1024):
29
+ proc = subprocess.Popen(
30
+ cmd,
31
+ env=env,
32
+ cwd=cwd,
33
+ stdout=subprocess.PIPE,
34
+ stderr=subprocess.PIPE,
35
+ bufsize=0,
36
+ )
37
+ sel = selectors.DefaultSelector()
38
+ sel.register(proc.stdout, selectors.EVENT_READ)
39
+ sel.register(proc.stderr, selectors.EVENT_READ)
40
+ captured = bytearray()
41
+
42
+ while True:
43
+ events = sel.select(timeout=1)
44
+ if events:
45
+ for key, _ in events:
46
+ data = os.read(key.fileobj.fileno(), 4096)
47
+ if not data:
48
+ sel.unregister(key.fileobj)
49
+ key.fileobj.close()
50
+ continue
51
+ if key.fileobj is proc.stdout:
52
+ sys.stdout.buffer.write(data)
53
+ sys.stdout.buffer.flush()
54
+ else:
55
+ sys.stderr.buffer.write(data)
56
+ sys.stderr.buffer.flush()
57
+ if capture_limit:
58
+ captured.extend(data)
59
+ if len(captured) > capture_limit:
60
+ captured = captured[-capture_limit:]
61
+ if proc.poll() is not None and not sel.get_map():
62
+ break
63
+
64
+ return proc.wait(), bytes(captured)
65
+
66
+
67
+ def run_cmd_with_retry_on_read_timeout(cmd, env, cwd, max_retries):
68
+ for attempt in range(1, max_retries + 1):
69
+ status, output = _run_cmd_streaming(cmd, env, cwd)
70
+ if status == 0:
71
+ return
72
+ if b"ReadTimeout" in output:
73
+ if attempt < max_retries:
74
+ print(
75
+ f"Step 3 hit a ReadTimeout (attempt {attempt}/{max_retries}), retrying..."
76
+ )
77
+ continue
78
+ raise SystemExit(status)
79
+
80
+
81
+ def run_cmd_with_inactivity_timeout(cmd, env, cwd, timeout_seconds):
82
+ proc = subprocess.Popen(
83
+ cmd,
84
+ env=env,
85
+ cwd=cwd,
86
+ stdout=subprocess.PIPE,
87
+ stderr=subprocess.PIPE,
88
+ bufsize=0,
89
+ )
90
+ sel = selectors.DefaultSelector()
91
+ sel.register(proc.stdout, selectors.EVENT_READ)
92
+ sel.register(proc.stderr, selectors.EVENT_READ)
93
+ last_output = time.monotonic()
94
+
95
+ while True:
96
+ events = sel.select(timeout=1)
97
+ if events:
98
+ for key, _ in events:
99
+ data = os.read(key.fileobj.fileno(), 4096)
100
+ if not data:
101
+ sel.unregister(key.fileobj)
102
+ key.fileobj.close()
103
+ continue
104
+ last_output = time.monotonic()
105
+ if key.fileobj is proc.stdout:
106
+ sys.stdout.buffer.write(data)
107
+ sys.stdout.buffer.flush()
108
+ else:
109
+ sys.stderr.buffer.write(data)
110
+ sys.stderr.buffer.flush()
111
+ else:
112
+ if time.monotonic() - last_output > timeout_seconds:
113
+ proc.terminate()
114
+ try:
115
+ proc.wait(timeout=5)
116
+ except subprocess.TimeoutExpired:
117
+ proc.kill()
118
+ return 124
119
+ if proc.poll() is not None and not sel.get_map():
120
+ break
121
+
122
+ return proc.wait()
123
+
124
+
125
+ def main():
126
+ parser = argparse.ArgumentParser()
127
+ parser.add_argument(
128
+ "--model",
129
+ type=str,
130
+ default=os.getenv("AGENTLESS_MODEL", "gpt-5.2"),
131
+ help="Model name for Agentless localization/repair steps.",
132
+ )
133
+ parser.add_argument(
134
+ "--backend",
135
+ type=str,
136
+ default="openai",
137
+ choices=["openai", "deepseek", "anthropic"],
138
+ help="Model backend for Agentless localization/repair steps.",
139
+ )
140
+ args = parser.parse_args()
141
+ model_dir = _safe_model_dir_name(args.model)
142
+
143
+ repo_root = "/workspace/phoenix-bench/Agentless"
144
+ os.chdir(repo_root)
145
+ env = _build_env()
146
+
147
+ dataset_path = "/workspace/phoenix-bench/Agentless/agentless_dataset.json"
148
+
149
+ steps = [
150
+ (
151
+ "1",
152
+ [
153
+ "python",
154
+ "agentless/fl/localize.py",
155
+ "--file_level",
156
+ "--output_folder",
157
+ "results/hwe-bench-lite/file_level",
158
+ "--num_threads",
159
+ "1",
160
+ "--skip_existing",
161
+ "--model",
162
+ args.model,
163
+ "--backend",
164
+ args.backend,
165
+ "--dataset_path",
166
+ dataset_path,
167
+ ],
168
+ False,
169
+ ),
170
+ (
171
+ "2",
172
+ [
173
+ "python",
174
+ "agentless/fl/localize.py",
175
+ "--file_level",
176
+ "--irrelevant",
177
+ "--output_folder",
178
+ "results/hwe-bench-lite/file_level_irrelevant",
179
+ "--num_threads",
180
+ "1",
181
+ "--skip_existing",
182
+ "--model",
183
+ args.model,
184
+ "--backend",
185
+ args.backend,
186
+ "--dataset_path",
187
+ dataset_path,
188
+ ],
189
+ False,
190
+ ),
191
+ (
192
+ "3",
193
+ [
194
+ "python",
195
+ "agentless/fl/retrieve.py",
196
+ "--index_type",
197
+ "simple",
198
+ "--filter_type",
199
+ "given_files",
200
+ "--filter_file",
201
+ "results/hwe-bench-lite/file_level_irrelevant/loc_outputs.jsonl",
202
+ "--output_folder",
203
+ "results/hwe-bench-lite/retrievel_embedding",
204
+ "--persist_dir",
205
+ "embedding/hwe-bench_simple",
206
+ "--num_threads",
207
+ "1",
208
+ "--dataset_path",
209
+ dataset_path,
210
+ ],
211
+ False,
212
+ ),
213
+ (
214
+ "4",
215
+ [
216
+ "python",
217
+ "agentless/fl/combine.py",
218
+ "--retrieval_loc_file",
219
+ "results/hwe-bench-lite/retrievel_embedding/retrieve_locs.jsonl",
220
+ "--model_loc_file",
221
+ "results/hwe-bench-lite/file_level/loc_outputs.jsonl",
222
+ "--top_n",
223
+ "3",
224
+ "--output_folder",
225
+ "results/hwe-bench-lite/file_level_combined",
226
+ ],
227
+ False,
228
+ ),
229
+ (
230
+ "5",
231
+ [
232
+ "python",
233
+ "agentless/fl/localize.py",
234
+ "--related_level",
235
+ "--output_folder",
236
+ "results/hwe-bench-lite/related_elements",
237
+ "--top_n",
238
+ "3",
239
+ "--compress_assign",
240
+ "--compress",
241
+ "--start_file",
242
+ "results/hwe-bench-lite/file_level_combined/combined_locs.jsonl",
243
+ "--num_threads",
244
+ "1",
245
+ "--skip_existing",
246
+ "--model",
247
+ args.model,
248
+ "--backend",
249
+ args.backend,
250
+ "--dataset_path",
251
+ dataset_path,
252
+ ],
253
+ False,
254
+ ),
255
+ (
256
+ "6",
257
+ [
258
+ "python",
259
+ "agentless/fl/localize.py",
260
+ "--fine_grain_line_level",
261
+ "--output_folder",
262
+ "results/hwe-bench-lite/edit_location_samples",
263
+ "--top_n",
264
+ "3",
265
+ "--compress",
266
+ "--temperature",
267
+ "0.8",
268
+ "--num_samples",
269
+ "4",
270
+ "--start_file",
271
+ "results/hwe-bench-lite/related_elements/loc_outputs.jsonl",
272
+ "--num_threads",
273
+ "1",
274
+ "--skip_existing",
275
+ "--model",
276
+ args.model,
277
+ "--backend",
278
+ args.backend,
279
+ "--dataset_path",
280
+ dataset_path,
281
+ ],
282
+ False,
283
+ ),
284
+ (
285
+ "7",
286
+ [
287
+ "python",
288
+ "agentless/fl/localize.py",
289
+ "--merge",
290
+ "--output_folder",
291
+ "results/hwe-bench-lite/edit_location_individual",
292
+ "--top_n",
293
+ "3",
294
+ "--num_samples",
295
+ "4",
296
+ "--start_file",
297
+ "results/hwe-bench-lite/edit_location_samples/loc_outputs.jsonl",
298
+ "--model",
299
+ args.model,
300
+ "--backend",
301
+ args.backend,
302
+ "--dataset_path",
303
+ dataset_path,
304
+ ],
305
+ False,
306
+ ),
307
+ (
308
+ "8",
309
+ [
310
+ "python",
311
+ "agentless/repair/repair.py",
312
+ "--loc_file",
313
+ "results/hwe-bench-lite/edit_location_individual/loc_merged_0-0_outputs.jsonl",
314
+ "--output_folder",
315
+ f"results/hwe-bench-lite/repair_sample_verilog/{model_dir}",
316
+ "--loc_interval",
317
+ "--top_n=3",
318
+ "--context_window=10",
319
+ "--max_samples",
320
+ "1",
321
+ "--cot",
322
+ "--diff_format",
323
+ "--gen_and_process",
324
+ "--num_threads",
325
+ "2",
326
+ "--model",
327
+ args.model,
328
+ "--backend",
329
+ args.backend,
330
+ "--dataset_path",
331
+ dataset_path,
332
+ ],
333
+ True,
334
+ ),
335
+ ]
336
+
337
+ for label, cmd, use_inactivity_timeout in steps:
338
+ print(label)
339
+ if label != "8":
340
+ continue
341
+ if label == "3":
342
+ run_cmd_with_retry_on_read_timeout(cmd, env, repo_root, max_retries=10)
343
+ elif use_inactivity_timeout:
344
+ while True:
345
+ status = run_cmd_with_inactivity_timeout(
346
+ cmd, env, repo_root, timeout_seconds=600
347
+ )
348
+ if status == 124:
349
+ print("Step 8 timed out after 600s of inactivity, retrying...")
350
+ continue
351
+ if status != 0:
352
+ raise SystemExit(status)
353
+ break
354
+ else:
355
+ run_cmd(cmd, env, repo_root)
356
+
357
+
358
+ if __name__ == "__main__":
359
+ main()
Repos/HWE/agents/Agentless/run_agentless.sh ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export OPENAI_API_BASE=https://api.openai.com/v1
2
+ export OPENAI_API_KEY=YOUR_OPENAI_API_KEY
3
+ export TREE_SITTER_VERILOG_SO=/workspace/phoenix-bench/Agentless/my-languages.so
4
+ export PYTHONPATH=$PYTHONPATH:$(pwd)
5
+ AGENTLESS_MODEL="${AGENTLESS_MODEL:-gpt-5.2}"
6
+ AGENTLESS_MODEL_DIR="${AGENTLESS_MODEL//\//__}"
7
+ AGENTLESS_BACKEND="${AGENTLESS_BACKEND:-}"
8
+
9
+ if [ -z "$AGENTLESS_BACKEND" ]; then
10
+ if [[ "$AGENTLESS_MODEL" == *deepseek* ]]; then
11
+ AGENTLESS_BACKEND="deepseek"
12
+ else
13
+ AGENTLESS_BACKEND="openai"
14
+ fi
15
+ fi
16
+
17
+ echo "1"
18
+ python agentless/fl/localize.py --file_level \
19
+ --output_folder results/hwe-bench-lite/file_level \
20
+ --num_threads 10 \
21
+ --skip_existing \
22
+ --model "$AGENTLESS_MODEL" \
23
+ --backend "$AGENTLESS_BACKEND" \
24
+ --dataset_path /workspace/phoenix-bench/Agentless/agentless_dataset.json
25
+
26
+ echo "2"
27
+ python agentless/fl/localize.py --file_level \
28
+ --irrelevant \
29
+ --output_folder results/hwe-bench-lite/file_level_irrelevant \
30
+ --num_threads 10 \
31
+ --skip_existing \
32
+ --model "$AGENTLESS_MODEL" \
33
+ --backend "$AGENTLESS_BACKEND" \
34
+ --dataset_path /workspace/phoenix-bench/Agentless/agentless_dataset.json
35
+
36
+ echo "3"
37
+ python agentless/fl/retrieve.py --index_type simple \
38
+ --filter_type given_files \
39
+ --filter_file results/hwe-bench-lite/file_level_irrelevant/loc_outputs.jsonl \
40
+ --output_folder results/hwe-bench-lite/retrievel_embedding \
41
+ --persist_dir embedding/hwe-bench_simple \
42
+ --num_threads 10 \
43
+ --dataset_path /workspace/phoenix-bench/Agentless/agentless_dataset.json
44
+
45
+ echo "4"
46
+ python agentless/fl/combine.py --retrieval_loc_file results/hwe-bench-lite/retrievel_embedding/retrieve_locs.jsonl \
47
+ --model_loc_file results/hwe-bench-lite/file_level/loc_outputs.jsonl \
48
+ --top_n 3 \
49
+ --output_folder results/hwe-bench-lite/file_level_combined
50
+
51
+ echo "5"
52
+ python agentless/fl/localize.py --related_level \
53
+ --output_folder results/hwe-bench-lite/related_elements \
54
+ --top_n 3 \
55
+ --compress_assign \
56
+ --compress \
57
+ --start_file results/hwe-bench-lite/file_level_combined/combined_locs.jsonl \
58
+ --num_threads 10 \
59
+ --skip_existing \
60
+ --model "$AGENTLESS_MODEL" \
61
+ --backend "$AGENTLESS_BACKEND" \
62
+ --dataset_path /workspace/phoenix-bench/Agentless/agentless_dataset.json
63
+
64
+ echo "6"
65
+ python agentless/fl/localize.py --fine_grain_line_level \
66
+ --output_folder results/hwe-bench-lite/edit_location_samples \
67
+ --top_n 3 \
68
+ --compress \
69
+ --temperature 0.8 \
70
+ --num_samples 4 \
71
+ --start_file results/hwe-bench-lite/related_elements/loc_outputs.jsonl \
72
+ --num_threads 10 \
73
+ --skip_existing \
74
+ --model "$AGENTLESS_MODEL" \
75
+ --backend "$AGENTLESS_BACKEND" \
76
+ --dataset_path /workspace/phoenix-bench/Agentless/agentless_dataset.json
77
+
78
+ echo "7"
79
+ python agentless/fl/localize.py --merge \
80
+ --output_folder results/hwe-bench-lite/edit_location_individual \
81
+ --top_n 3 \
82
+ --num_samples 4 \
83
+ --start_file results/hwe-bench-lite/edit_location_samples/loc_outputs.jsonl \
84
+ --model "$AGENTLESS_MODEL" \
85
+ --backend "$AGENTLESS_BACKEND" \
86
+ --dataset_path /workspace/phoenix-bench/Agentless/agentless_dataset.json
87
+
88
+ echo "8"
89
+ while true; do
90
+ timeout 300s python agentless/repair/repair.py --loc_file results/hwe-bench-lite/edit_location_individual/loc_merged_0-0_outputs.jsonl \
91
+ --output_folder "results/hwe-bench-lite/repair_sample_verilog/${AGENTLESS_MODEL_DIR}" \
92
+ --loc_interval \
93
+ --top_n=3 \
94
+ --context_window=10 \
95
+ --max_samples 1 \
96
+ --cot \
97
+ --diff_format \
98
+ --gen_and_process \
99
+ --num_threads 2 \
100
+ --model "$AGENTLESS_MODEL" \
101
+ --backend "$AGENTLESS_BACKEND" \
102
+ --dataset_path /workspace/phoenix-bench/Agentless/agentless_dataset.json
103
+ status=$?
104
+ if [ $status -eq 124 ]; then
105
+ echo "Step 8 timed out after 300s, retrying..."
106
+ continue
107
+ fi
108
+ if [ $status -ne 0 ]; then
109
+ exit $status
110
+ fi
111
+ break
112
+ done
Repos/HWE/agents/Agentless/tally_token_use.py ADDED
@@ -0,0 +1,352 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import sys
8
+ from collections import defaultdict
9
+ from dataclasses import asdict, dataclass
10
+ from pathlib import Path
11
+ from typing import Any, Iterable
12
+
13
+
14
+ DEFAULT_BASE_DIR = Path(__file__).resolve().parent / "results"
15
+
16
+
17
+ @dataclass
18
+ class TokenUsage:
19
+ records: int = 0
20
+ usage_objects: int = 0
21
+ prompt_tokens: int = 0
22
+ completion_tokens: int = 0
23
+ embedding_tokens: int = 0
24
+ cache_creation_tokens: int = 0
25
+ cache_read_tokens: int = 0
26
+
27
+ @property
28
+ def total_text_tokens(self) -> int:
29
+ return self.prompt_tokens + self.completion_tokens
30
+
31
+ @property
32
+ def total_tokens(self) -> int:
33
+ return (
34
+ self.prompt_tokens
35
+ + self.completion_tokens
36
+ + self.embedding_tokens
37
+ + self.cache_creation_tokens
38
+ + self.cache_read_tokens
39
+ )
40
+
41
+ def add_usage(self, usage: dict[str, Any]) -> None:
42
+ self.usage_objects += 1
43
+ self.prompt_tokens += first_int(
44
+ usage, "prompt_tokens", "input_tokens"
45
+ )
46
+ self.completion_tokens += first_int(
47
+ usage, "completion_tokens", "output_tokens"
48
+ )
49
+ self.embedding_tokens += first_int(usage, "embedding_tokens")
50
+ self.cache_creation_tokens += first_int(
51
+ usage, "cache_creation_token", "cache_creation_input_tokens"
52
+ )
53
+ self.cache_read_tokens += first_int(
54
+ usage, "cache_read_input_tokens", "cache_read_tokens"
55
+ )
56
+
57
+ def add_row(self, row: "TokenUsage") -> None:
58
+ self.records += row.records
59
+ self.usage_objects += row.usage_objects
60
+ self.prompt_tokens += row.prompt_tokens
61
+ self.completion_tokens += row.completion_tokens
62
+ self.embedding_tokens += row.embedding_tokens
63
+ self.cache_creation_tokens += row.cache_creation_tokens
64
+ self.cache_read_tokens += row.cache_read_tokens
65
+
66
+
67
+ @dataclass
68
+ class ModelSummary:
69
+ runs: int = 0
70
+ tokens_sent: int = 0
71
+ tokens_received: int = 0
72
+ total_tokens: int = 0
73
+ api_calls: int = 0
74
+
75
+ def add_usage(self, usage: TokenUsage) -> None:
76
+ self.runs += usage.records
77
+ self.tokens_sent += usage.prompt_tokens
78
+ self.tokens_received += usage.completion_tokens
79
+ self.total_tokens += usage.total_text_tokens
80
+ self.api_calls += usage.usage_objects
81
+
82
+
83
+ def parse_args() -> argparse.Namespace:
84
+ parser = argparse.ArgumentParser(
85
+ description=(
86
+ "Summarize token usage per model in Agentless JSONL outputs. By "
87
+ "default this scans args.json files under the repo's results/ "
88
+ "directory and tallies their declared output JSONL files."
89
+ )
90
+ )
91
+ parser.add_argument(
92
+ "--base-dir",
93
+ type=Path,
94
+ default=DEFAULT_BASE_DIR,
95
+ help="A JSONL file or directory containing Agentless result JSONL files.",
96
+ )
97
+ parser.add_argument(
98
+ "--format",
99
+ choices=("table", "json"),
100
+ default="table",
101
+ help="Output format.",
102
+ )
103
+ parser.add_argument(
104
+ "--include-zero-usage",
105
+ action="store_true",
106
+ help="Include models whose declared output files do not contain usage objects.",
107
+ )
108
+ return parser.parse_args()
109
+
110
+
111
+ def first_int(mapping: dict[str, Any], *keys: str) -> int:
112
+ for key in keys:
113
+ value = mapping.get(key)
114
+ if value is None:
115
+ continue
116
+ try:
117
+ return int(value)
118
+ except (TypeError, ValueError):
119
+ continue
120
+ return 0
121
+
122
+
123
+ def iter_usage_objects(value: Any) -> Iterable[dict[str, Any]]:
124
+ if isinstance(value, dict):
125
+ usage = value.get("usage")
126
+ if isinstance(usage, dict):
127
+ yield usage
128
+ for child in value.values():
129
+ yield from iter_usage_objects(child)
130
+ elif isinstance(value, list):
131
+ for child in value:
132
+ yield from iter_usage_objects(child)
133
+
134
+
135
+ def iter_jsonl_files(path: Path) -> list[Path]:
136
+ if path.is_file():
137
+ if path.suffix != ".jsonl":
138
+ raise ValueError(f"{path} is not a .jsonl file")
139
+ return [path]
140
+ if not path.is_dir():
141
+ raise ValueError(f"{path} is not a file or directory")
142
+ return sorted(path.glob("**/*.jsonl"))
143
+
144
+
145
+ def load_json(path: Path) -> Any:
146
+ with path.open(encoding="utf-8") as fh:
147
+ return json.load(fh)
148
+
149
+
150
+ def format_model_name(args_data: dict[str, Any], fallback: str) -> str:
151
+ model = args_data.get("model")
152
+ backend = args_data.get("backend")
153
+ if isinstance(model, str) and model:
154
+ if isinstance(backend, str) and backend and "/" not in model:
155
+ return f"{backend}/{model}"
156
+ return model
157
+ return fallback
158
+
159
+
160
+ def resolve_declared_output(args_path: Path, args_data: dict[str, Any]) -> Path | None:
161
+ raw_output_file = args_data.get("output_file")
162
+ if not isinstance(raw_output_file, str) or not raw_output_file:
163
+ return None
164
+
165
+ output_name = Path(raw_output_file).name
166
+ local_output = args_path.parent / output_name
167
+ if local_output.exists():
168
+ return local_output
169
+
170
+ raw_path = Path(raw_output_file)
171
+ if raw_path.is_absolute() and raw_path.exists():
172
+ return raw_path
173
+
174
+ repo_relative = Path(__file__).resolve().parent / raw_path
175
+ if repo_relative.exists():
176
+ return repo_relative
177
+
178
+ return None
179
+
180
+
181
+ def infer_args_for_jsonl(path: Path) -> tuple[str, list[str]]:
182
+ warnings: list[str] = []
183
+ for parent in [path.parent, *path.parents]:
184
+ args_path = parent / "args.json"
185
+ if not args_path.exists():
186
+ continue
187
+ try:
188
+ args_data = load_json(args_path)
189
+ except (OSError, json.JSONDecodeError) as exc:
190
+ warnings.append(f"Ignoring unreadable args file {args_path}: {exc}")
191
+ continue
192
+ if isinstance(args_data, dict):
193
+ return format_model_name(args_data, path.parent.name), warnings
194
+ return path.parent.name, warnings
195
+
196
+
197
+ def collect_file_usage(path: Path) -> tuple[TokenUsage, list[str]]:
198
+ usage = TokenUsage()
199
+ warnings: list[str] = []
200
+
201
+ try:
202
+ with path.open(encoding="utf-8") as fh:
203
+ for line_number, line in enumerate(fh, start=1):
204
+ line = line.strip()
205
+ if not line:
206
+ continue
207
+ usage.records += 1
208
+ try:
209
+ row = json.loads(line)
210
+ except json.JSONDecodeError as exc:
211
+ warnings.append(f"Skipping malformed JSONL row {path}:{line_number}: {exc}")
212
+ continue
213
+
214
+ for usage_object in iter_usage_objects(row):
215
+ usage.add_usage(usage_object)
216
+ except OSError as exc:
217
+ warnings.append(f"Skipping unreadable output file {path}: {exc}")
218
+
219
+ return usage, warnings
220
+
221
+
222
+ def collect_summary(
223
+ base_dir: Path, include_zero_usage: bool
224
+ ) -> tuple[dict[str, ModelSummary], list[str]]:
225
+ summary: dict[str, ModelSummary] = defaultdict(ModelSummary)
226
+ warnings: list[str] = []
227
+ seen_outputs: set[Path] = set()
228
+
229
+ if base_dir.is_file():
230
+ for path in iter_jsonl_files(base_dir):
231
+ model_name, model_warnings = infer_args_for_jsonl(path)
232
+ warnings.extend(model_warnings)
233
+ file_usage, file_warnings = collect_file_usage(path)
234
+ warnings.extend(file_warnings)
235
+ if file_usage.total_text_tokens or include_zero_usage:
236
+ summary[model_name].add_usage(file_usage)
237
+ return dict(summary), warnings
238
+
239
+ if not base_dir.is_dir():
240
+ raise ValueError(f"{base_dir} is not a file or directory")
241
+
242
+ for args_path in sorted(base_dir.glob("**/args.json")):
243
+ try:
244
+ args_data = load_json(args_path)
245
+ except (OSError, json.JSONDecodeError) as exc:
246
+ warnings.append(f"Ignoring unreadable args file {args_path}: {exc}")
247
+ continue
248
+ if not isinstance(args_data, dict):
249
+ warnings.append(f"Ignoring malformed args file {args_path}: top-level JSON is not an object")
250
+ continue
251
+
252
+ path = resolve_declared_output(args_path, args_data)
253
+ if path is None:
254
+ continue
255
+ path = path.resolve()
256
+ if path in seen_outputs:
257
+ continue
258
+ seen_outputs.add(path)
259
+
260
+ model_name = format_model_name(args_data, args_path.parent.name)
261
+ file_usage, file_warnings = collect_file_usage(path)
262
+ warnings.extend(file_warnings)
263
+ if file_usage.total_text_tokens or include_zero_usage:
264
+ summary[model_name].add_usage(file_usage)
265
+
266
+ return dict(summary), warnings
267
+
268
+
269
+ def format_int(value: int) -> str:
270
+ return str(value)
271
+
272
+
273
+ def render_table(summary: dict[str, ModelSummary]) -> str:
274
+ headers = [
275
+ "Model",
276
+ "Runs",
277
+ "Tokens Sent",
278
+ "Tokens Received",
279
+ "Total Tokens",
280
+ "API Calls",
281
+ ]
282
+ table_rows: list[list[str]] = []
283
+
284
+ for model_name, stats in sorted(
285
+ summary.items(),
286
+ key=lambda item: (-item[1].total_tokens, item[0]),
287
+ ):
288
+ table_rows.append(
289
+ [
290
+ model_name,
291
+ format_int(stats.runs),
292
+ format_int(stats.tokens_sent),
293
+ format_int(stats.tokens_received),
294
+ format_int(stats.total_tokens),
295
+ format_int(stats.api_calls),
296
+ ]
297
+ )
298
+
299
+ widths = [len(header) for header in headers]
300
+ for row in table_rows:
301
+ for index, value in enumerate(row):
302
+ widths[index] = max(widths[index], len(value))
303
+
304
+ def format_row(row: list[str]) -> str:
305
+ return " ".join(value.ljust(widths[index]) for index, value in enumerate(row))
306
+
307
+ lines = [format_row(headers), format_row(["-" * width for width in widths])]
308
+ if table_rows:
309
+ lines.extend(format_row(row) for row in table_rows)
310
+ else:
311
+ lines.append("No token usage records found.")
312
+
313
+ return "\n".join(lines)
314
+
315
+
316
+ def render_json(summary: dict[str, ModelSummary], base_dir: Path) -> str:
317
+ return json.dumps(
318
+ {
319
+ "base_dir": str(base_dir),
320
+ "models": {
321
+ model_name: asdict(stats)
322
+ for model_name, stats in sorted(summary.items())
323
+ },
324
+ },
325
+ indent=2,
326
+ sort_keys=True,
327
+ )
328
+
329
+
330
+ def main() -> int:
331
+ args = parse_args()
332
+ base_dir = args.base_dir.resolve()
333
+
334
+ try:
335
+ summary, warnings = collect_summary(base_dir, args.include_zero_usage)
336
+ except ValueError as exc:
337
+ print(f"Error: {exc}", file=sys.stderr)
338
+ return 2
339
+
340
+ if args.format == "json":
341
+ print(render_json(summary, base_dir))
342
+ else:
343
+ print(render_table(summary))
344
+
345
+ for warning in warnings:
346
+ print(f"Warning: {warning}", file=sys.stderr)
347
+
348
+ return 0
349
+
350
+
351
+ if __name__ == "__main__":
352
+ raise SystemExit(main())
Repos/HWE/agents/Agentless/test_agentless/apfaudio_eurorack-pmod_pr36/.gitattributes ADDED
@@ -0,0 +1 @@
 
 
1
+ hardware/fab/* linguist-vendored
Repos/HWE/agents/Agentless/test_agentless/apfaudio_eurorack-pmod_pr36/.gitignore ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # For PCBs designed using KiCad: https://www.kicad.org/
2
+ # Format documentation: https://kicad.org/help/file-formats/
3
+
4
+ # Temporary files
5
+ *.000
6
+ *.bak
7
+ *.bck
8
+ *.kicad_pcb-bak
9
+ *.kicad_sch-bak
10
+ *-backups
11
+ *.kicad_prl
12
+ *.sch-bak
13
+ *~
14
+ _autosave-*
15
+ *.tmp
16
+ *-save.pro
17
+ *-save.kicad_pcb
18
+ fp-info-cache
19
+
20
+ # Netlist files (exported from Eeschema)
21
+ *.net
22
+
23
+ # Autorouter files (exported from Pcbnew)
24
+ *.dsn
25
+ *.ses
26
+
27
+ # Exported BOM files
28
+ *.xml
Repos/HWE/agents/Agentless/test_agentless/apfaudio_eurorack-pmod_pr36/.gitmodules ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ [submodule "hardware/libs/AudioJacks"]
2
+ path = hardware/libs/AudioJacks
3
+ url = https://github.com/clacktronics/AudioJacks
4
+ [submodule "gateware/external/no2misc"]
5
+ path = gateware/external/no2misc
6
+ url = https://github.com/no2fpga/no2misc
Repos/HWE/agents/Agentless/test_agentless/apfaudio_eurorack-pmod_pr36/LICENSE ADDED
@@ -0,0 +1,289 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ CERN Open Hardware Licence Version 2 - Strongly Reciprocal
2
+
3
+
4
+ Preamble
5
+
6
+ CERN has developed this licence to promote collaboration among
7
+ hardware designers and to provide a legal tool which supports the
8
+ freedom to use, study, modify, share and distribute hardware designs
9
+ and products based on those designs. Version 2 of the CERN Open
10
+ Hardware Licence comes in three variants: CERN-OHL-P (permissive); and
11
+ two reciprocal licences: CERN-OHL-W (weakly reciprocal) and this
12
+ licence, CERN-OHL-S (strongly reciprocal).
13
+
14
+ The CERN-OHL-S is copyright CERN 2020. Anyone is welcome to use it, in
15
+ unmodified form only.
16
+
17
+ Use of this Licence does not imply any endorsement by CERN of any
18
+ Licensor or their designs nor does it imply any involvement by CERN in
19
+ their development.
20
+
21
+
22
+ 1 Definitions
23
+
24
+ 1.1 'Licence' means this CERN-OHL-S.
25
+
26
+ 1.2 'Compatible Licence' means
27
+
28
+ a) any earlier version of the CERN Open Hardware licence, or
29
+
30
+ b) any version of the CERN-OHL-S, or
31
+
32
+ c) any licence which permits You to treat the Source to which
33
+ it applies as licensed under CERN-OHL-S provided that on
34
+ Conveyance of any such Source, or any associated Product You
35
+ treat the Source in question as being licensed under
36
+ CERN-OHL-S.
37
+
38
+ 1.3 'Source' means information such as design materials or digital
39
+ code which can be applied to Make or test a Product or to
40
+ prepare a Product for use, Conveyance or sale, regardless of its
41
+ medium or how it is expressed. It may include Notices.
42
+
43
+ 1.4 'Covered Source' means Source that is explicitly made available
44
+ under this Licence.
45
+
46
+ 1.5 'Product' means any device, component, work or physical object,
47
+ whether in finished or intermediate form, arising from the use,
48
+ application or processing of Covered Source.
49
+
50
+ 1.6 'Make' means to create or configure something, whether by
51
+ manufacture, assembly, compiling, loading or applying Covered
52
+ Source or another Product or otherwise.
53
+
54
+ 1.7 'Available Component' means any part, sub-assembly, library or
55
+ code which:
56
+
57
+ a) is licensed to You as Complete Source under a Compatible
58
+ Licence; or
59
+
60
+ b) is available, at the time a Product or the Source containing
61
+ it is first Conveyed, to You and any other prospective
62
+ licensees
63
+
64
+ i) as a physical part with sufficient rights and
65
+ information (including any configuration and
66
+ programming files and information about its
67
+ characteristics and interfaces) to enable it either to
68
+ be Made itself, or to be sourced and used to Make the
69
+ Product; or
70
+ ii) as part of the normal distribution of a tool used to
71
+ design or Make the Product.
72
+
73
+ 1.8 'Complete Source' means the set of all Source necessary to Make
74
+ a Product, in the preferred form for making modifications,
75
+ including necessary installation and interfacing information
76
+ both for the Product, and for any included Available Components.
77
+ If the format is proprietary, it must also be made available in
78
+ a format (if the proprietary tool can create it) which is
79
+ viewable with a tool available to potential licensees and
80
+ licensed under a licence approved by the Free Software
81
+ Foundation or the Open Source Initiative. Complete Source need
82
+ not include the Source of any Available Component, provided that
83
+ You include in the Complete Source sufficient information to
84
+ enable a recipient to Make or source and use the Available
85
+ Component to Make the Product.
86
+
87
+ 1.9 'Source Location' means a location where a Licensor has placed
88
+ Covered Source, and which that Licensor reasonably believes will
89
+ remain easily accessible for at least three years for anyone to
90
+ obtain a digital copy.
91
+
92
+ 1.10 'Notice' means copyright, acknowledgement and trademark notices,
93
+ Source Location references, modification notices (subsection
94
+ 3.3(b)) and all notices that refer to this Licence and to the
95
+ disclaimer of warranties that are included in the Covered
96
+ Source.
97
+
98
+ 1.11 'Licensee' or 'You' means any person exercising rights under
99
+ this Licence.
100
+
101
+ 1.12 'Licensor' means a natural or legal person who creates or
102
+ modifies Covered Source. A person may be a Licensee and a
103
+ Licensor at the same time.
104
+
105
+ 1.13 'Convey' means to communicate to the public or distribute.
106
+
107
+
108
+ 2 Applicability
109
+
110
+ 2.1 This Licence governs the use, copying, modification, Conveying
111
+ of Covered Source and Products, and the Making of Products. By
112
+ exercising any right granted under this Licence, You irrevocably
113
+ accept these terms and conditions.
114
+
115
+ 2.2 This Licence is granted by the Licensor directly to You, and
116
+ shall apply worldwide and without limitation in time.
117
+
118
+ 2.3 You shall not attempt to restrict by contract or otherwise the
119
+ rights granted under this Licence to other Licensees.
120
+
121
+ 2.4 This Licence is not intended to restrict fair use, fair dealing,
122
+ or any other similar right.
123
+
124
+
125
+ 3 Copying, Modifying and Conveying Covered Source
126
+
127
+ 3.1 You may copy and Convey verbatim copies of Covered Source, in
128
+ any medium, provided You retain all Notices.
129
+
130
+ 3.2 You may modify Covered Source, other than Notices, provided that
131
+ You irrevocably undertake to make that modified Covered Source
132
+ available from a Source Location should You Convey a Product in
133
+ circumstances where the recipient does not otherwise receive a
134
+ copy of the modified Covered Source. In each case subsection 3.3
135
+ shall apply.
136
+
137
+ You may only delete Notices if they are no longer applicable to
138
+ the corresponding Covered Source as modified by You and You may
139
+ add additional Notices applicable to Your modifications.
140
+ Including Covered Source in a larger work is modifying the
141
+ Covered Source, and the larger work becomes modified Covered
142
+ Source.
143
+
144
+ 3.3 You may Convey modified Covered Source (with the effect that You
145
+ shall also become a Licensor) provided that You:
146
+
147
+ a) retain Notices as required in subsection 3.2;
148
+
149
+ b) add a Notice to the modified Covered Source stating that You
150
+ have modified it, with the date and brief description of how
151
+ You have modified it;
152
+
153
+ c) add a Source Location Notice for the modified Covered Source
154
+ if You Convey in circumstances where the recipient does not
155
+ otherwise receive a copy of the modified Covered Source; and
156
+
157
+ d) license the modified Covered Source under the terms and
158
+ conditions of this Licence (or, as set out in subsection
159
+ 8.3, a later version, if permitted by the licence of the
160
+ original Covered Source). Such modified Covered Source must
161
+ be licensed as a whole, but excluding Available Components
162
+ contained in it, which remain licensed under their own
163
+ applicable licences.
164
+
165
+
166
+ 4 Making and Conveying Products
167
+
168
+ You may Make Products, and/or Convey them, provided that You either
169
+ provide each recipient with a copy of the Complete Source or ensure
170
+ that each recipient is notified of the Source Location of the Complete
171
+ Source. That Complete Source is Covered Source, and You must
172
+ accordingly satisfy Your obligations set out in subsection 3.3. If
173
+ specified in a Notice, the Product must visibly and securely display
174
+ the Source Location on it or its packaging or documentation in the
175
+ manner specified in that Notice.
176
+
177
+
178
+ 5 Research and Development
179
+
180
+ You may Convey Covered Source, modified Covered Source or Products to
181
+ a legal entity carrying out development, testing or quality assurance
182
+ work on Your behalf provided that the work is performed on terms which
183
+ prevent the entity from both using the Source or Products for its own
184
+ internal purposes and Conveying the Source or Products or any
185
+ modifications to them to any person other than You. Any modifications
186
+ made by the entity shall be deemed to be made by You pursuant to
187
+ subsection 3.2.
188
+
189
+
190
+ 6 DISCLAIMER AND LIABILITY
191
+
192
+ 6.1 DISCLAIMER OF WARRANTY -- The Covered Source and any Products
193
+ are provided 'as is' and any express or implied warranties,
194
+ including, but not limited to, implied warranties of
195
+ merchantability, of satisfactory quality, non-infringement of
196
+ third party rights, and fitness for a particular purpose or use
197
+ are disclaimed in respect of any Source or Product to the
198
+ maximum extent permitted by law. The Licensor makes no
199
+ representation that any Source or Product does not or will not
200
+ infringe any patent, copyright, trade secret or other
201
+ proprietary right. The entire risk as to the use, quality, and
202
+ performance of any Source or Product shall be with You and not
203
+ the Licensor. This disclaimer of warranty is an essential part
204
+ of this Licence and a condition for the grant of any rights
205
+ granted under this Licence.
206
+
207
+ 6.2 EXCLUSION AND LIMITATION OF LIABILITY -- The Licensor shall, to
208
+ the maximum extent permitted by law, have no liability for
209
+ direct, indirect, special, incidental, consequential, exemplary,
210
+ punitive or other damages of any character including, without
211
+ limitation, procurement of substitute goods or services, loss of
212
+ use, data or profits, or business interruption, however caused
213
+ and on any theory of contract, warranty, tort (including
214
+ negligence), product liability or otherwise, arising in any way
215
+ in relation to the Covered Source, modified Covered Source
216
+ and/or the Making or Conveyance of a Product, even if advised of
217
+ the possibility of such damages, and You shall hold the
218
+ Licensor(s) free and harmless from any liability, costs,
219
+ damages, fees and expenses, including claims by third parties,
220
+ in relation to such use.
221
+
222
+
223
+ 7 Patents
224
+
225
+ 7.1 Subject to the terms and conditions of this Licence, each
226
+ Licensor hereby grants to You a perpetual, worldwide,
227
+ non-exclusive, no-charge, royalty-free, irrevocable (except as
228
+ stated in subsections 7.2 and 8.4) patent licence to Make, have
229
+ Made, use, offer to sell, sell, import, and otherwise transfer
230
+ the Covered Source and Products, where such licence applies only
231
+ to those patent claims licensable by such Licensor that are
232
+ necessarily infringed by exercising rights under the Covered
233
+ Source as Conveyed by that Licensor.
234
+
235
+ 7.2 If You institute patent litigation against any entity (including
236
+ a cross-claim or counterclaim in a lawsuit) alleging that the
237
+ Covered Source or a Product constitutes direct or contributory
238
+ patent infringement, or You seek any declaration that a patent
239
+ licensed to You under this Licence is invalid or unenforceable
240
+ then any rights granted to You under this Licence shall
241
+ terminate as of the date such process is initiated.
242
+
243
+
244
+ 8 General
245
+
246
+ 8.1 If any provisions of this Licence are or subsequently become
247
+ invalid or unenforceable for any reason, the remaining
248
+ provisions shall remain effective.
249
+
250
+ 8.2 You shall not use any of the name (including acronyms and
251
+ abbreviations), image, or logo by which the Licensor or CERN is
252
+ known, except where needed to comply with section 3, or where
253
+ the use is otherwise allowed by law. Any such permitted use
254
+ shall be factual and shall not be made so as to suggest any kind
255
+ of endorsement or implication of involvement by the Licensor or
256
+ its personnel.
257
+
258
+ 8.3 CERN may publish updated versions and variants of this Licence
259
+ which it considers to be in the spirit of this version, but may
260
+ differ in detail to address new problems or concerns. New
261
+ versions will be published with a unique version number and a
262
+ variant identifier specifying the variant. If the Licensor has
263
+ specified that a given variant applies to the Covered Source
264
+ without specifying a version, You may treat that Covered Source
265
+ as being released under any version of the CERN-OHL with that
266
+ variant. If no variant is specified, the Covered Source shall be
267
+ treated as being released under CERN-OHL-S. The Licensor may
268
+ also specify that the Covered Source is subject to a specific
269
+ version of the CERN-OHL or any later version in which case You
270
+ may apply this or any later version of CERN-OHL with the same
271
+ variant identifier published by CERN.
272
+
273
+ 8.4 This Licence shall terminate with immediate effect if You fail
274
+ to comply with any of its terms and conditions.
275
+
276
+ 8.5 However, if You cease all breaches of this Licence, then Your
277
+ Licence from any Licensor is reinstated unless such Licensor has
278
+ terminated this Licence by giving You, while You remain in
279
+ breach, a notice specifying the breach and requiring You to cure
280
+ it within 30 days, and You have failed to come into compliance
281
+ in all material respects by the end of the 30 day period. Should
282
+ You repeat the breach after receipt of a cure notice and
283
+ subsequent reinstatement, this Licence will terminate
284
+ immediately and permanently. Section 6 shall continue to apply
285
+ after any termination.
286
+
287
+ 8.6 This Licence shall not be enforceable except by a Licensor
288
+ acting as such, and third party beneficiary rights are
289
+ specifically excluded.
Repos/HWE/agents/Agentless/test_agentless/apfaudio_eurorack-pmod_pr36/README.md ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Eurorack PMOD
2
+
3
+ **Assembled boards now available!** [get one **here :)**](https://lectronz.com/stores/apfelaudio)
4
+
5
+ **Eurorack PMOD** makes it easy for you to combine the world of FPGAs and [hardware electronic music synthesis](https://en.wikipedia.org/wiki/Eurorack). It is an expansion board for FPGA development boards that allows them to interface with a Eurorack hardware synthesizer. This board exposes 8 (4 in + 4 out) DC-coupled audio channels, 192KHz / 32bit sampling supported, at a -8V to +8V swing, amongst many more features. R3.1 hardware looks like this:
6
+
7
+ ![assembled eurorack-pmod module R3.0 (panel)](docs/img/panel.jpg)
8
+ ![assembled eurorack-pmod module R3.0 (top)](docs/img/pmod_top.jpg)
9
+
10
+
11
+ ![ci workflow](https://github.com/schnommus/eurorack-pmod/actions/workflows/main.yml/badge.svg)
12
+
13
+
14
+ For a high-level overview on R2.2 hardware, **see [my FOSDEM '23 talk](https://youtu.be/Wbd-OfCWvKU)** on this project. Production hardware is named R3+ and has a few improvements (LEDs fully programmable, jack detection, calibration EEPROM).
15
+
16
+ [Want one?](#manufacturing). More photos can be found [below](#photos).
17
+
18
+ ### This project is:
19
+ - The design for a Eurorack-compatible PCB and front-panel, including a [PMOD](https://en.wikipedia.org/wiki/Pmod_Interface) connector (compatible with most FPGA dev boards). PCB designed in [KiCAD](https://www.kicad.org/). Design is [certified open hardware](https://certification.oshwa.org/de000135.html).
20
+ - Various [example cores](gateware/cores) (and calibration / driver cores for the audio CODEC) initially targeting an [iCEBreaker FPGA](https://1bitsquared.com/products/icebreaker) (iCE40 part) but many more boards are supported (see below). Examples include calibration, sampling, effects, synthesis sources and so on. The design files can be synthesized to a bitstream using Yosys' [oss-cad-suite](https://github.com/YosysHQ/oss-cad-suite-build).
21
+ - A [VCV Rack plugin](https://github.com/schnommus/verilog-vcvrack) so you can simulate your Verilog designs in a completely virtual modular system, no hardware required.
22
+
23
+ ## Included examples
24
+ This repository contains a bunch of example DSP cores which are continuously being updated:
25
+ - Bitcrusher
26
+ - Filter (high pass / low pass / band pass)
27
+ - Clock divider
28
+ - .wav sampler
29
+ - Pitch shifter
30
+ - Sequential routing switch
31
+ - Echo/delay effect
32
+ - VCA (voltage controlled amplifier)
33
+ - VCO (voltage controlled oscillator)
34
+
35
+ These examples can all run out of the box on the development boards listed below.
36
+
37
+ ## Choosing an FPGA development board
38
+ An FPGA development board itself is NOT included! Essentially anything iCE40 or ECP5 based that has a PMOD connector will support the open-source tools and the examples in this project. Just make sure you have enough LUTS, >3K is enough to do interesting things.
39
+
40
+ The following development boards have been tested with `eurorack-pmod` and are supported by the examples in the github repository
41
+ - iCEbreaker (iCE40 based)
42
+ - ECPIX-5 (ECP5 based)
43
+ - Colorlight i5 (ECP5 based)
44
+ - Colorlight i9 (ECP5 based)
45
+ - pico-ice from TinyVision (iCE40 based)
46
+
47
+ ## Hardware details
48
+
49
+ ![labelled eurorack-pmod 3.0](docs/img/labelled.jpg)
50
+
51
+ - 3HP module compatible with modular synthesizer systems.
52
+ - Module depth is 47mm with both ribbon cables attached
53
+ - This fits nicely in e.g. a 4MS POD 48X (pictured below).
54
+ - PMOD connector compatible with most FPGA development boards.
55
+ - 8 (4 in + 4 out) DC-coupled audio channels, 192KHz / 32bit sampling supported.
56
+ - PWM-controlled, user-programmable red/green LEDs on each output channel.
57
+ - Jack insertion detection on input & output jacks.
58
+ - Calibration EEPROM for unique ID and storing calibration data.
59
+ - I/O is about +/- 8V capable, wider is possible with a resistor change.
60
+
61
+ ## PMOD Pinout
62
+
63
+ The PMOD pinout is on the silkscreen on the back side of the board. Details are below. Note that Pin 1 is the SQUARE pad.
64
+
65
+ 1) SDI (AK4619VN SDIN1)
66
+ 2) SCL (I2C SCL for AK4619VN CODEC, EEPROM, LED + JACK IO expanders)
67
+ 3) SDO (AK4619VN SDOUT1)
68
+ 4) SDA (I2C SDA)
69
+ 5) LRCK (CODEC clock line)
70
+ 6) PDN (CODEC power down, also connected to LED output enable and JACK reset line -- HIGH means everything is on)
71
+ 7) BICK (CODEC clock line)
72
+ 8) MCLK (CODEC clock line)
73
+ 9) GND
74
+ 10) GND
75
+ 11) 3V3 IN
76
+ 12) 3V3 IN
77
+
78
+ ## Gateware details
79
+ - Examples based on iCE40 and ECP5 based FPGAs supported by open-source tools.
80
+ - User-defined DSP logic is decoupled from rest of system (see [`gateware/cores`](gateware/cores) directory)
81
+
82
+ ## Getting Started
83
+
84
+ For now, I have tested builds on Linux and Windows (under MSYS2). Both are tested in CI.
85
+
86
+ 0. Install the [OSS FPGA CAD flow](https://github.com/yosyshq/oss-cad-suite-build).
87
+ - You may be able to get yosys / verilator from other package managers but I recommend using the [releases from YosysHQ](https://github.com/yosyshq/oss-cad-suite-build) so you're using the same binaries that CI is using.
88
+ - On Linux, once the YosysHQ suite is installed and in PATH, you should be able to just use `make` in the gateware directory.
89
+ - On Windows, CI is using MSYS2 with MINGW64 shell. Install MSYS2, MINGW64, extract the oss-cad-suite from YosysHQ and add it to PATH. Then you should be able to use `make` in the gateware directory.
90
+ - Note: The gateware is automatically built and tested in CI, so for either platform it may be helpful to look at [`.github/workflows/main.yml`](.github/workflows/main.yml).
91
+
92
+ 1. Build or obtain `eurorack-pmod` hardware and connect it to your FPGA development board using a ribbon cable or similar. (Double check that the pin mappings are correct, some ribbon cables will swap them on you! Default pinmaps are for the ribbon cables I shipped with hardware, you need to flip the pinmaps for a direct connection PMOD -> FPGA)
93
+ 2. Try some of the examples. From the `gateware` directory, type `make` to see valid commands. By default if you do not select a CORE it will compile a bitstream with the 'mirror' core, which just sends inputs to outputs.
94
+ 2. Calibrate your hardware using the process described in [`gateware/cal/cal.py`](gateware/cal/cal.py). Use this to create your own `gateware/cal/cal_mem.hex` to compensate for any DC biases in the ADCs/DACs. (this step is only necessary if you need sub-50mV accuracy on your inputs/outputs, which is the case if you are tuning oscillators, not so much if you are creating rhythm pulses.
95
+
96
+ # Project structure
97
+ The project is split into 2 directories, [`hardware`](hardware) for the PCB/panel and [`gateware`](gateware) for the FPGA source. Some interesting directories:
98
+ - [`gateware/cores`](gateware/cores): example user core implementations (i.e sequential switch, bitcrusher, filter, vco, vca, sampler etc).
99
+ - [`gateware/top.sv`](gateware/top.sv): top-level gateware with defines for selecting features.
100
+ - [`gateware/cal/cal.py`](gateware/cal/cal.py): tool used to calibrate the hardware after assembly, generating calibration memory.
101
+ - [`gateware/drivers`](gateware/drivers): driver for CODEC and I2C devices used on this board.
102
+ - [`hardware/eurorack-pmod-r3`](hardware/eurorack-pmod-r3): KiCAD design files for PCB and front panel.
103
+ - [`hardware/fab`](hardware/fab): gerber files and BOM for manufacturing the hardware.
104
+
105
+ # Manufacturing
106
+
107
+ **Assembled boards now available!** [get one **here :)**](https://lectronz.com/stores/apfelaudio)
108
+
109
+ Update: R3.1 (first production release) is fully functional with 1 rework, see github issues for up-to-date information.
110
+
111
+ Note: I gave some R3.0 (preproduction) units out at Hackaday Berlin '23. These are tested but NOT calibrated. They had 2 hacks applied. Some inductors are shorted with 0 ohm resistors as the wrong inductor was populated (means the board is a bit noiser than it should be - but still definitely useable). Also the reset line of the jack detect IO expander was routed incorrectly, so I manually shorted 2 pins of that chip. Functionally these boards are the same as R3.1, which fixes these issues.
112
+
113
+
114
+ ## Known limitations
115
+ - Moved to github issues
116
+
117
+ # Photos
118
+
119
+ ## Assembled `eurorack-pmod` (front)
120
+ ![assembled eurorack-pmod module (front)](docs/img/leds_front.jpg)
121
+
122
+ ## `eurorack-pmod` connected to iCEBreaker
123
+ ![assembled eurorack-pmod module (in system)](docs/img/pmod_insystem.jpg)
124
+
125
+ # License
126
+
127
+ [![OSHW logo](docs/img/oshw.svg)](https://certification.oshwa.org/de000135.html)
128
+
129
+ Hardware and gateware are released under the CERN Open-Hardware License V2 `CERN-OHL-S`, mirrored in the LICENSE text in this repository.
130
+
131
+ If you wish to license parts of this design in a commercial product without a reciprocal open-source license, or you have a ground-breaking idea for a module we could work on together, feel free to contact me directly. See sebholzapfel.com.
132
+
133
+ *Copyright (C) 2022,2023 Sebastian Holzapfel*
134
+
135
+ The above LICENSE and copyright notice does NOT apply to imported artifacts in this repository (i.e datasheets, third-party footprints).
Repos/HWE/agents/Agentless/test_agentless/apfaudio_eurorack-pmod_pr36/docs/img/labelled.jpg ADDED

Git LFS Details

  • SHA256: 5aa295c16d37cb12efaf8a8ade179c521e5c90b8091ff89026682c564408c640
  • Pointer size: 131 Bytes
  • Size of remote file: 292 kB
Repos/HWE/agents/Agentless/test_agentless/apfaudio_eurorack-pmod_pr36/docs/img/leds_front.jpg ADDED

Git LFS Details

  • SHA256: d07846f5c41306827e196f974fd260073b2af442e9dd35091c29db0b5a333cff
  • Pointer size: 131 Bytes
  • Size of remote file: 162 kB