SWE-agent takes a GitHub issue and tries to automatically fix it, using your LM of choice. It can also be employed for offensive cybersecurity or competitive coding challenges. [NeurIPS 2024]
Refactor run.py main function into class with hook structure (#253)
Kilian Lieret877de061b06c
diff --git a/run.py b/run.pyindex 0a9e873f..905ef5c9 100644--- a/run.py+++ b/run.py@@ -4,11 +4,12 @@ import osimport reimport subprocessimport traceback-from typing import Any, Dict, Optional+from typing import Any, Dict, List, Optionalimport rich.consoleimport rich.markdownimport rich.panelimport rich.markdown+try:from rich_argparse import RichHelpFormatterexcept ImportError:@@ -92,6 +93,7 @@ class ScriptArguments(FlattenedAccess, FrozenSerializable):"""Generate a unique name for this run based on the arguments."""model_name = self.agent.model.model_name.replace(":", "-")data_stem = get_data_path_name(self.environment.data_path)+ assert self.agent.config_file is not None # mypyconfig_stem = Path(self.agent.config_file).stemtemp = self.agent.model.temperature@@ -107,237 +109,328 @@ class ScriptArguments(FlattenedAccess, FrozenSerializable):)-def main(args: ScriptArguments):- logger.info(f"π Arguments: {args.dumps_yaml()}")- agent = Agent("primary", args.agent)-- env = SWEEnv(args.environment)-- traj_dir = Path("trajectories") / Path(getuser()) / args.run_name- traj_dir.mkdir(parents=True, exist_ok=True)+class _ContinueLoop(Exception):+ """Used for internal control flow"""+ ...- save_arguments(traj_dir, args)- for index in range(len(env.data)):- try:- # Reset environment- instance_id = env.data[index]["instance_id"]- assert isinstance(instance_id, str) # mypy- if should_skip(args, traj_dir, instance_id):- continue- logger.info("βΆοΈ Beginning task " + str(index))+class MainHook:+ """Hook structure for the web server or other addons to interface with"""+ def on_init(self, *, args: ScriptArguments, agent: Agent, env: SWEEnv, traj_dir: Path):+ """Called when hook is initialized"""+ ...- observation, info = env.reset(index)- if info is None:- continue+ def on_start(self):+ """Called at the beginning of `Main.main`"""+ ...- # Get info, patch information- issue = getattr(env, "query", None)- files = []- assert env.record is not None # mypy- if "patch" in env.record:- files = "\n".join(- [f"- {x.path}" for x in PatchSet(env.record["patch"]).modified_files]- )- # Get test files, F2P tests information- test_files = []- if "test_patch" in env.record:- test_patch_obj = PatchSet(env.record["test_patch"])- test_files = "\n".join(- [f"- {x.path}" for x in test_patch_obj.modified_files + test_patch_obj.added_files]- )- tests = ""- if "FAIL_TO_PASS" in env.record:- tests = "\n".join([f"- {x}" for x in env.record["FAIL_TO_PASS"]])-- setup_args = {- "issue": issue,- "files": files,- "test_files": test_files,- "tests": tests- }- info, trajectory = agent.run(- setup_args=setup_args,- env=env,- observation=observation,- traj_dir=traj_dir,- return_type="info_trajectory",- )- save_predictions(traj_dir, instance_id, info)- patch_path = save_patch(traj_dir, instance_id, info)- if args.actions.open_pr and should_open_pr(args, info, token=env._github_token):- env.open_pr(trajectory=trajectory)- if args.actions.apply_patch_locally and patch_path is not None and env.record["repo_type"] == "local":- apply_patch(Path(args.environment.repo_path), patch_file=patch_path)-- except KeyboardInterrupt:- logger.info("Exiting InterCode environment...")- env.close()- break- except Exception as e:- traceback.print_exc()- logger.warning(f"β Failed on {env.record['instance_id']}: {e}")- if args.raise_exceptions:- raise e- env.reset_container()- continue---def should_open_pr(args: ScriptArguments, info: Dict[str, Any], *, token: str="") -> bool:- """Does opening a PR make sense?"""- if not info.get("submission"):- logger.info("Not opening PR because no submission was made.")- return False- if info["exit_status"] != "submitted":- logger.info("Not opening PR because exit status was %s and not submitted.", info["exit_status"])- return False- try:- issue = get_gh_issue_data(args.environment.data_path, token=token)- except InvalidGithubURL:- logger.info("Currently only GitHub is supported to open PRs to. Skipping PR creation.")- return False- if issue.state != "open":- logger.info(f"Issue is not open (state={issue.state}. Skipping PR creation.")- return False- if issue.assignee:- logger.info("Issue is already assigned. Skipping PR creation. Be nice :)")- return False- if issue.locked:- logger.info("Issue is locked. Skipping PR creation.")- return False- org, repo, issue_number = parse_gh_issue_url(args.environment.data_path)- associated_commits = get_associated_commit_urls(org, repo, issue_number, token=token)- if associated_commits:- commit_url_strs = ", ".join(associated_commits)- if args.actions.skip_if_commits_reference_issue:- logger.info(f"Issue already has associated commits (see {commit_url_strs}). Skipping PR creation.")- return False- else:- logger.warning(- "Proceeding with PR creation even though there are already commits "- f"({commit_url_strs}) associated with the issue. Please only do this for your own repositories "- "or after verifying that the existing commits do not fix the issue."- )- return True+ def on_end(self):+ """Called at the end of `Main.main`"""+ ...++ def on_instance_start(self, *, index: int, instance: Dict[str, Any]):+ """Called at the beginning of each instance loop in `Main.run`"""+ ...++ def on_instance_skipped(self, ):+ """Called when an instance is skipped in `Main.run`"""+ ...++ def on_instance_completed(self, *, info, trajectory):+ """Called when an instance is completed in `Main.run`"""+ ...-def save_arguments(traj_dir: Path, args: ScriptArguments) -> None:- """Save the arguments to a yaml file to the run's trajectory directory."""- log_path = traj_dir / "args.yaml"+class SaveApplyPatchHook(MainHook):+ """This hook saves patches to a separate directory and optionally applies them to a local repository."""- if log_path.exists():+ def on_init(self, *, args: ScriptArguments, agent: Agent, env: SWEEnv, traj_dir: Path):+ self._traj_dir = traj_dir+ self._apply_patch_locally = args.actions.apply_patch_locally+ self._instance = None++ def on_instance_start(self, *, index: int, instance: Dict[str, Any]):+ self._instance = instance++ def on_instance_completed(self, *, info, trajectory):+ assert self._instance is not None # mypy+ instance_id = self._instance["instance_id"]+ patch_path = self._save_patch(instance_id, info)+ if patch_path:+ if not self._apply_patch_locally:+ return+ assert self._instance # mypy+ if not self._instance["repo_type"] == "local":+ return+ local_dir = Path(self._instance["repo"])+ self._apply_patch(patch_path, local_dir)++ @staticmethod+ def _print_patch_message(patch_output_file: Path):+ console = rich.console.Console()+ msg = [+ "SWE-agent has produced a patch that it believes will solve the issue you submitted!",+ "Use the code snippet below to inspect or apply it!"+ ]+ panel = rich.panel.Panel.fit(+ "\n".join(msg),+ title="π Submission successful π",+ )+ console.print(panel)+ content = [+ "```bash",+ f"# The patch has been saved to your local filesystem at:",+ f"PATCH_FILE_PATH='{patch_output_file.resolve()}'",+ "# Inspect it:",+ "cat \"${PATCH_FILE_PATH}\"",+ "# Apply it to a local repository:",+ f"cd <your local repo root>",+ "git apply \"${PATCH_FILE_PATH}\"",+ "```",+ ]+ console.print(rich.markdown.Markdown("\n".join(content)))++ def _save_patch(self, instance_id: str, info) -> Optional[Path]:+ """Create patch files that can be applied with `git am`.++ Returns:+ The path to the patch file, if it was saved. Otherwise, returns None.+ """+ patch_output_dir = self._traj_dir / "patches"+ patch_output_dir.mkdir(exist_ok=True, parents=True)+ patch_output_file = patch_output_dir / f"{instance_id}.patch"+ if not info.get("submission"):+ logger.info("No patch to save.")+ return+ model_patch = info["submission"]+ patch_output_file.write_text(model_patch)+ self._print_patch_message(patch_output_file)+ return patch_output_file++ def _apply_patch(self, patch_file: Path, local_dir: Path) -> None:+ """Apply a patch to a local directory."""++ assert local_dir.is_dir()+ assert patch_file.exists()+ # The resolve() is important, because we're gonna run the cmd+ # somewhere else+ cmd = ["git", "apply", str(patch_file.resolve())]+ try:+ subprocess.run(cmd, cwd=local_dir, check=True)+ except subprocess.CalledProcessError as e:+ logger.error(f"Failed to apply patch {patch_file} to {local_dir}: {e}")+ return+ logger.info(f"Applied patch {patch_file} to {local_dir}")+++class OpenPRHook(MainHook):+ """This hook opens a PR if the issue is solved and the user has enabled the option."""++ def on_init(self, *, args: ScriptArguments, agent: Agent, env: SWEEnv, traj_dir: Path):+ self._env = env+ self._token: str = env._github_token+ self._data_path = args.environment.data_path+ self._open_pr = args.actions.open_pr+ self._skip_if_commits_reference_issue = args.actions.skip_if_commits_reference_issue++ def on_instance_completed(self, *, info, trajectory):+ if self._open_pr and self.should_open_pr(info):+ self._env.open_pr(trajectory=trajectory)++ def should_open_pr(self, info: Dict[str, Any]) -> bool:+ """Does opening a PR make sense?"""+ if not info.get("submission"):+ logger.info("Not opening PR because no submission was made.")+ return False+ if info["exit_status"] != "submitted":+ logger.info("Not opening PR because exit status was %s and not submitted.", info["exit_status"])+ return Falsetry:- other_args = args.load_yaml(log_path)- if (args.dumps_yaml() != other_args.dumps_yaml()): # check yaml equality instead of object equality- logger.warning("**************************************************")- logger.warning("Found existing args.yaml with different arguments!")- logger.warning("**************************************************")- except Exception as e:- logger.warning(f"Failed to load existing args.yaml: {e}")-- with log_path.open("w") as f:- args.dump_yaml(f)---def should_skip(args: ScriptArguments, traj_dir: Path, instance_id: str) -> bool:- """Check if we should skip this instance based on the instance filter and skip_existing flag."""- # Skip instances that don't match the instance filter- if re.match(args.instance_filter, instance_id) is None:- logger.info(f"Instance filter not matched. Skipping instance {instance_id}")+ issue = get_gh_issue_data(self._data_path, token=self._token)+ except InvalidGithubURL:+ logger.info("Currently only GitHub is supported to open PRs to. Skipping PR creation.")+ return False+ if issue.state != "open":+ logger.info(f"Issue is not open (state={issue.state}. Skipping PR creation.")+ return False+ if issue.assignee:+ logger.info("Issue is already assigned. Skipping PR creation. Be nice :)")+ return False+ if issue.locked:+ logger.info("Issue is locked. Skipping PR creation.")+ return False+ org, repo, issue_number = parse_gh_issue_url(self._data_path)+ associated_commits = get_associated_commit_urls(org, repo, issue_number, token=self._token)+ if associated_commits:+ commit_url_strs = ", ".join(associated_commits)+ if self._skip_if_commits_reference_issue:+ logger.info(f"Issue already has associated commits (see {commit_url_strs}). Skipping PR creation.")+ return False+ else:+ logger.warning(+ "Proceeding with PR creation even though there are already commits "+ f"({commit_url_strs}) associated with the issue. Please only do this for your own repositories "+ "or after verifying that the existing commits do not fix the issue."+ )return True- # If flag is set to False, don't skip- if not args.skip_existing:- return False-- # Check if there's an existing trajectory for this instance- log_path = traj_dir / (instance_id + ".traj")- if log_path.exists():- with log_path.open("r") as f:- data = json.load(f)- # If the trajectory has no exit status, it's incomplete and we will redo it- exit_status = data["info"].get("exit_status", None)- if exit_status == "early_exit" or exit_status is None:- logger.info(f"Found existing trajectory with no exit status: {log_path}")- logger.info("Removing incomplete trajectory...")- os.remove(log_path)- else:- logger.info(f"βοΈ Skipping existing trajectory: {log_path}")- return True- return False--def save_predictions(traj_dir: Path, instance_id: str, info):- output_file = traj_dir / "all_preds.jsonl"- model_patch = info["submission"] if "submission" in info else None- datum = {- KEY_MODEL: Path(traj_dir).name,- KEY_INSTANCE_ID: instance_id,- KEY_PREDICTION: model_patch,- }- with open(output_file, "a+") as fp:- print(json.dumps(datum), file=fp, flush=True)- logger.info(f"Saved predictions to {output_file}")+class Main:+ def __init__(self, args: ScriptArguments):+ logger.info(f"π Arguments: {args.dumps_yaml()}")+ self.args = args+ self.agent = Agent("primary", args.agent)+ self.env = SWEEnv(args.environment)+ self.traj_dir = Path("trajectories") / Path(getuser()) / args.run_name+ self.traj_dir.mkdir(parents=True, exist_ok=True)+ self._save_arguments()+ default_hooks = [+ SaveApplyPatchHook(),+ OpenPRHook(),+ ]+ self.hooks: List[MainHook] = []+ for hook in default_hooks:+ self.add_hook(hook)++ def add_hook(self, hook: MainHook):+ hook.on_init(args=self.args, agent=self.agent, env=self.env, traj_dir=self.traj_dir)+ self.hooks.append(hook)++ def run(self, index):+ # Reset environment+ instance_id = self.env.data[index]["instance_id"]+ for hook in self.hooks:+ hook.on_instance_start(index=index, instance=self.env.data[index])+ assert isinstance(instance_id, str) # mypy+ if self.should_skip(instance_id):+ for hook in self.hooks:+ hook.on_instance_skipped()+ raise _ContinueLoop+ logger.info("βΆοΈ Beginning task " + str(index))++ observation, info = self.env.reset(index)+ if info is None:+ raise _ContinueLoop++ # Get info, patch information+ issue = getattr(self.env, "query", None)+ files = []+ assert self.env.record is not None # mypy+ if "patch" in self.env.record:+ files = "\n".join(+ [f"- {x.path}" for x in PatchSet(self.env.record["patch"]).modified_files]+ )+ # Get test files, F2P tests information+ test_files = []+ if "test_patch" in self.env.record:+ test_patch_obj = PatchSet(self.env.record["test_patch"])+ test_files = "\n".join(+ [f"- {x.path}" for x in test_patch_obj.modified_files + test_patch_obj.added_files]+ )+ tests = ""+ if "FAIL_endTO_PASS" in self.env.record:+ tests = "\n".join([f"- {x}" for x in self.env.record["FAIL_TO_PASS"]])++ setup_args = {+ "issue": issue,+ "files": files,+ "test_files": test_files,+ "tests": tests+ }+ info, trajectory = self.agent.run(+ setup_args=setup_args,+ env=self.env,+ observation=observation,+ traj_dir=self.traj_dir,+ return_type="info_trajectory",+ )+ self._save_predictions(instance_id, info)+ for hook in self.hooks:+ hook.on_instance_completed(info=info, trajectory=trajectory)++ def main(self):+ for hook in self.hooks:+ hook.on_start()+ for index in range(len(self.env.data)):+ try:+ self.run(index)+ except _ContinueLoop:+ continue+ except KeyboardInterrupt:+ logger.info("Exiting InterCode environment...")+ self.env.close()+ break+ except Exception as e:+ traceback.print_exc()+ if self.args.raise_exceptions:+ raise e+ if self.env.record:+ logger.warning(f"β Failed on {self.env.record['instance_id']}: {e}")+ else:+ logger.warning(f"β Failed on unknown instance")+ self.env.reset_container()+ continue+ for hook in self.hooks:+ hook.on_end()++ def _save_arguments(self) -> None:+ """Save the arguments to a yaml file to the run's trajectory directory."""+ log_path = self.traj_dir / "args.yaml"++ if log_path.exists():+ try:+ other_args = self.args.load_yaml(log_path)+ if (self.args.dumps_yaml() != other_args.dumps_yaml()): # check yaml equality instead of object equality+ logger.warning("**************************************************")+ logger.warning("Found existing args.yaml with different arguments!")+ logger.warning("**************************************************")+ except Exception as e:+ logger.warning(f"Failed to load existing args.yaml: {e}")++ with log_path.open("w") as f:+ self.args.dump_yaml(f)+++ def should_skip(self, instance_id: str) -> bool:+ """Check if we should skip this instance based on the instance filter and skip_existing flag."""+ # Skip instances that don't match the instance filter+ if re.match(self.args.instance_filter, instance_id) is None:+ logger.info(f"Instance filter not matched. Skipping instance {instance_id}")+ return True+ # If flag is set to False, don't skip+ if not self.args.skip_existing:+ return False+ # Check if there's an existing trajectory for this instance+ log_path = self.traj_dir / (instance_id + ".traj")+ if log_path.exists():+ with log_path.open("r") as f:+ data = json.load(f)+ # If the trajectory has no exit status, it's incomplete and we will redo it+ exit_status = data["info"].get("exit_status", None)+ if exit_status == "early_exit" or exit_status is None:+ logger.info(f"Found existing trajectory with no exit status: {log_path}")+ logger.info("Removing incomplete trajectory...")+ os.remove(log_path)+ else:+ logger.info(f"βοΈ Skipping existing trajectory: {log_path}")+ return True+ return False-def save_patch(traj_dir: Path, instance_id: str, info) -> Optional[Path]:- """Create patch files that can be applied with `git am`.-- Returns:- The path to the patch file, if it was saved. Otherwise, returns None.- """- patch_output_dir = traj_dir / "patches"- patch_output_dir.mkdir(exist_ok=True, parents=True)- patch_output_file = patch_output_dir / f"{instance_id}.patch"- if not info.get("submission"):- logger.info("No patch to save.")- return- model_patch = info["submission"]- patch_output_file.write_text(model_patch)- _print_patch_message(patch_output_file)- return patch_output_file---def apply_patch(local_dir: Path, patch_file: Path) -> None:- """Apply a patch to a local directory."""- assert local_dir.is_dir()- assert patch_file.exists()- # The resolve() is important, because we're gonna run the cmd- # somewhere else- cmd = ["git", "apply", str(patch_file.resolve())]- try:- subprocess.run(cmd, cwd=local_dir, check=True)- except subprocess.CalledProcessError as e:- logger.error(f"Failed to apply patch {patch_file} to {local_dir}: {e}")- return- logger.info(f"Applied patch {patch_file} to {local_dir}")--def _print_patch_message(patch_output_file: Path):- console = rich.console.Console()- msg = [- "SWE-agent has produced a patch that it believes will solve the issue you submitted!",- "Use the code snippet below to inspect or apply it!"- ]- panel = rich.panel.Panel.fit(- "\n".join(msg),- title="π Submission successful π",- )- console.print(panel)- content = [- "```bash",- f"# The patch has been saved to your local filesystem at:",- f"PATCH_FILE_PATH='{patch_output_file.resolve()}'",- "# Inspect it:",- "cat \"${PATCH_FILE_PATH}\"",- "# Apply it to a local repository:",- f"cd <your local repo root>",- "git apply \"${PATCH_FILE_PATH}\"",- "```",- ]- console.print(rich.markdown.Markdown("\n".join(content)))+ def _save_predictions(self, instance_id: str, info):+ output_file = self.traj_dir / "all_preds.jsonl"+ model_patch = info["submission"] if "submission" in info else None+ datum = {+ KEY_MODEL: Path(self.traj_dir).name,+ KEY_INSTANCE_ID: instance_id,+ KEY_PREDICTION: model_patch,+ }+ with open(output_file, "a+") as fp:+ print(json.dumps(datum), file=fp, flush=True)+ logger.info(f"Saved predictions to {output_file}")def get_args(args=None) -> ScriptArguments:@@ -364,7 +457,7 @@ def get_args(args=None) -> ScriptArguments:temperature=0.0,top_p=0.95,),- config_file="config/default.yaml",+ config_file=Path("config/default.yaml"),),actions=ActionsArguments(open_pr=False, skip_if_commits_reference_issue=True),)@@ -383,6 +476,10 @@ def get_args(args=None) -> ScriptArguments:return parse(ScriptArguments, default=defaults, add_config_path_arg=False, args=args, formatter_class=RichHelpFormatter, description=Markdown(__doc__))++def main(args: ScriptArguments):+ Main(args).main()++if __name__ == "__main__":- args = get_args()- main(args)+ main(get_args())diff --git a/sweagent/agent/models.py b/sweagent/agent/models.pyindex 128c72f9..f6068048 100644--- a/sweagent/agent/models.py+++ b/sweagent/agent/models.py@@ -691,13 +691,34 @@ class ReplayModel(BaseModel):return action+class InstantEmptySubmitTestModel(BaseModel):+ MODELS = {"instant_empty_submit": {}}++ def __init__(self, args: ModelArguments, commands: list[Command]):+ """This model immediately submits an empty reproduce.py. Useful for testing purposes"""+ super().__init__(args, commands)+ self._action_idx = 0++ def query(self, history: list[dict[str, str]]) -> str:+ # Need to at least do _something_ to submit+ if self._action_idx == 0:+ self._action_idx = 1+ action = "DISCUSSION\nblah blah\n\n```\ncreate reproduce.py\n```\n"+ elif self._action_idx == 1:+ self._action_idx = 0+ action = "DISCUSSION\nblargh glargh\n\n```\nsubmit```\n"+ return action+++def get_model(args: ModelArguments, commands: Optional[list[Command]] = None):"""Returns correct model object given arguments and commands"""if commands is None:commands = []-+ if args.model_name == "instant_empty_submit":+ return InstantEmptySubmitTestModel(args, commands)if args.model_name == "human":return HumanModel(args, commands)if args.model_name == "human_thought":diff --git a/sweagent/environment/swe_env.py b/sweagent/environment/swe_env.pyindex 94e14aa4..4633528f 100644--- a/sweagent/environment/swe_env.py+++ b/sweagent/environment/swe_env.py@@ -105,12 +105,12 @@ class SWEEnv(gym.Env):except:logger.warning("Failed to get commit hash for this repo")- self._github_token = os.environ.get("GITHUB_TOKEN", None)+ self._github_token: str = os.environ.get("GITHUB_TOKEN", "")if not self._github_token and os.path.isfile(os.path.join(os.getcwd(), "keys.cfg")):cfg = config.Config(os.path.join(os.getcwd(), "keys.cfg"))- self._github_token = cfg.get("GITHUB_TOKEN", None)+ self._github_token: str = cfg.get("GITHUB_TOKEN", "") # type: ignore# Load Task Instancesself.data_path = self.args.data_pathdiff --git a/sweagent/environment/utils.py b/sweagent/environment/utils.pyindex c973dd93..a4be13ff 100644--- a/sweagent/environment/utils.py+++ b/sweagent/environment/utils.py@@ -22,7 +22,6 @@ from typing import Any, List, Optional, Set, Tuple, Dictfrom git import InvalidGitRepositoryError, Repo-LOGGER_NAME = "intercode"START_UP_DELAY = 5TIMEOUT_DURATION = 25@@ -684,4 +683,5 @@ def format_trajectory_markdown(trajectory: List[Dict[str, str]]):"","</details>",]- return "\n".join(prefix) + "\n\n---\n\n".join(steps) + "\n".join(suffix)\ No newline at end of file+ return "\n".join(prefix) + "\n\n---\n\n".join(steps) + "\n".join(suffix)+diff --git a/tests/conftest.py b/tests/conftest.pyindex 5345e892..12b2c064 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -33,9 +33,12 @@ def test_data_sources_path(test_data_path) -> Path:assert p.is_dir()return p+@fixture+def test_trajectory_path(test_trajectories_path) -> Path:+ traj = test_trajectories_path / "gpt4__klieret__swe-agent-test-repo__default_from_url__t-0.00__p-0.95__c-3.00__install-1" / "klieret__swe-agent-test-repo-i1.traj"+ assert traj.exists()+ return traj@fixture-def test_trajectory(test_trajectories_path):- traj_dir = test_trajectories_path / "gpt4__klieret__swe-agent-test-repo__default_from_url__t-0.00__p-0.95__c-3.00__install-1" / "klieret__swe-agent-test-repo-i1.traj"- assert traj_dir.exists()- return json.loads(traj_dir.read_text())\ No newline at end of file+def test_trajectory(test_trajectory_path):+ return json.loads(test_trajectory_path.read_text())diff --git a/tests/test_run.py b/tests/test_run.pyindex da3f1689..956ec6a9 100644--- a/tests/test_run.py+++ b/tests/test_run.py@@ -1,4 +1,13 @@+import json+from pathlib import Pathimport subprocess+from typing import Any, Dict+import pytest++from run import ActionsArguments, Main, MainHook, OpenPRHook, ScriptArguments+from sweagent.agent.agents import Agent, AgentArguments+from sweagent.agent.models import ModelArguments+from sweagent.environment.swe_env import EnvironmentArguments, SWEEnvdef test_run_cli_help():args = [@@ -9,5 +18,136 @@ def test_run_cli_help():subprocess.run(args, check=True)-def test_run_obsolete():- ...\ No newline at end of file++def open_pr_hook_init_for_sop():+ hook = OpenPRHook()+ hook._token = ""+ hook._env = None+ hook._data_path = "https://github.com/klieret/swe-agent-test-repo/issues/1"+ hook._open_pr = True+ hook._skip_if_commits_reference_issue = True+ return hook+++def info_dict():+ return {+ "submission": "asdf",+ "exit_status": "submitted",+ }+++def test_should_open_pr_fail_submission(open_pr_hook_init_for_sop, info_dict):+ hook = open_pr_hook_init_for_sop+ info_dict["submission"] = None+ assert not hook.should_open_pr(info_dict)+++def test_should_open_pr_fail_exit(open_pr_hook_init_for_sop, info_dict):+ hook = open_pr_hook_init_for_sop+ info_dict["exit_status"] = "fail"+ assert not hook.should_open_pr(info_dict)+++def test_should_open_pr_fail_invalid_url(open_pr_hook_init_for_sop, info_dict):+ hook = open_pr_hook_init_for_sop+ hook._data_path = "asdf"+ assert not hook.should_open_pr(info_dict)+++def test_should_open_pr_fail_closed(open_pr_hook_init_for_sop, info_dict):+ hook = open_pr_hook_init_for_sop+ hook._data_path = "https://github.com/klieret/swe-agent-test-repo/issues/16"+ assert not hook.should_open_pr(info_dict)+++def test_should_open_pr_fail_assigned(open_pr_hook_init_for_sop, info_dict):+ hook = open_pr_hook_init_for_sop+ hook._data_path = "https://github.com/klieret/swe-agent-test-repo/issues/17"+ assert not hook.should_open_pr(info_dict)+++def test_should_open_pr_fail_locked(open_pr_hook_init_for_sop, info_dict):+ hook = open_pr_hook_init_for_sop+ hook._data_path = "https://github.com/klieret/swe-agent-test-repo/issues/18"+ assert not hook.should_open_pr(info_dict)++def test_should_open_pr_fail_has_pr(open_pr_hook_init_for_sop, info_dict):+ hook = open_pr_hook_init_for_sop+ hook._data_path = "https://github.com/klieret/swe-agent-test-repo/issues/19"+ assert not hook.should_open_pr(info_dict)+++def test_should_open_pr_success_has_pr_override(open_pr_hook_init_for_sop, info_dict):+ hook = open_pr_hook_init_for_sop+ hook._data_path = "https://github.com/klieret/swe-agent-test-repo/issues/19"+ hook._skip_if_commits_reference_issue = False+ assert hook.should_open_pr(info_dict)+++class RaisesExceptionHook(MainHook):+ def on_instance_start(self, *, index: int, instance: Dict[str, Any]):+ raise ValueError("test exception")++def test_script_args():+ return ScriptArguments(+ suffix="",+ environment=EnvironmentArguments(+ image_name="sweagent/swe-agent:latest",+ data_path="https://github.com/klieret/swe-agent-test-repo/issues/1",+ split="dev",+ verbose=True,+ install_environment=True,+ ),+ skip_existing=True,+ agent=AgentArguments(+ model=ModelArguments(+ model_name="instant_empty_submit",+ total_cost_limit=0.0,+ per_instance_cost_limit=3.0,+ temperature=0.0,+ top_p=0.95,+ ),+ config_file=Path("config/default.yaml"),+ ),+ actions=ActionsArguments(open_pr=False, skip_if_commits_reference_issue=True),+ raise_exceptions=True,+ )+++def test_exception_raised(test_script_args):+ assert test_script_args.raise_exceptions+ main = Main(test_script_args)+ main.add_hook(RaisesExceptionHook())+ with pytest.raises(ValueError, match="test exception"):+ main.main()+++class CreateFakeLogFile(MainHook):+ """Testing the skip functionality"""+ def on_init(self, *, args: ScriptArguments, agent: Agent, env: SWEEnv, traj_dir: Path):+ self._traj_dir = traj_dir+ (traj_dir / "args.yaml").write_text("asdf")++ def on_instance_start(self, *, index: int, instance: Dict[str, Any]):+ instance_id = instance["instance_id"]+ dct = {+ "info": {"exit_status": "submitted"},+ }+ (self._traj_dir / f"{instance_id}.traj").write_text(json.dumps(dct))++++def test_existing_corrupted_args(test_script_args):+ main = Main(test_script_args)+ main.add_hook(CreateFakeLogFile())+ main.main++++def test_main_hook(test_script_args):+ main = Main(test_script_args)+ main.add_hook(MainHook())+ main.main