patch-pilot-ai 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,11 @@
1
+ """
2
+ Patch Pilot - Autonomous Test-Driven Code Healing & Bug Patching Agent powered by Google Gemini.
3
+ """
4
+
5
+ __version__ = "0.1.0"
6
+ __author__ = "Shubhransh Gupta"
7
+
8
+ from .agent import PatchPilotAgent
9
+ from .config import PatchConfig
10
+
11
+ __all__ = ["PatchPilotAgent", "PatchConfig", "__version__"]
patch_pilot/agent.py ADDED
@@ -0,0 +1,205 @@
1
+ """
2
+ Autonomous test-driven code healing and bug fixing orchestrator.
3
+ """
4
+
5
+ import os
6
+ import re
7
+ import json
8
+ import logging
9
+ from pathlib import Path
10
+ from typing import Optional, Dict, Any, List
11
+
12
+ from .config import PatchConfig
13
+ from .git_ops import GitRepo
14
+ from .runner import TestRunner, TestResult
15
+ from .llm import UnifiedLLM
16
+
17
+ logger = logging.getLogger(__name__)
18
+
19
+
20
+ class PatchPilotAgent:
21
+ """Agent that diagnoses bugs, modifies code, and self-heals iteratively until tests pass."""
22
+
23
+ def __init__(self, config: Optional[PatchConfig] = None):
24
+ self.config = config or PatchConfig()
25
+ self.config.validate()
26
+
27
+ self.repo_dir = self.config.target_repo_dir.resolve()
28
+ self.git = GitRepo(self.repo_dir)
29
+ self.runner = TestRunner(
30
+ repo_dir=self.repo_dir,
31
+ custom_cmd=self.config.test_command,
32
+ timeout=self.config.timeout_per_run
33
+ )
34
+ self.llm = UnifiedLLM(
35
+ provider=self.config.provider,
36
+ model=self.config.model,
37
+ api_key=self.config.api_key,
38
+ base_url=self.config.base_url,
39
+ timeout=self.config.timeout_per_run * 2,
40
+ )
41
+
42
+ def _call_llm(self, prompt: str, system_prompt: Optional[str] = None) -> str:
43
+ return self.llm.generate(prompt, system_instruction=system_prompt)
44
+
45
+ def _collect_repo_files(self) -> List[str]:
46
+ """Lists files in the repository excluding common ignore paths."""
47
+ ignored = {".git", ".venv", "venv", "node_modules", "__pycache__", "dist", "build"}
48
+ files = []
49
+ for root, dirs, filenames in os.walk(self.repo_dir):
50
+ dirs[:] = [d for d in dirs if d not in ignored]
51
+ for f in filenames:
52
+ rel = os.path.relpath(os.path.join(root, f), self.repo_dir)
53
+ if not rel.startswith("."):
54
+ files.append(rel)
55
+ return files[:150]
56
+
57
+ def solve_issue(self, issue_text: str, on_step=None) -> Dict[str, Any]:
58
+ """Orchestrates the entire bug diagnosis, patch application, test healing, and git commit."""
59
+ def log(msg: str):
60
+ if on_step:
61
+ on_step(msg)
62
+ else:
63
+ print(f"[*] {msg}")
64
+
65
+ log(f"Starting Patch Pilot in: {self.repo_dir}")
66
+ log(f"Issue description: '{issue_text[:80]}...'")
67
+
68
+ # 1. Repo inspection
69
+ files = self._collect_repo_files()
70
+ log(f"Scanned repository tree ({len(files)} files discovered).")
71
+
72
+ # 2. Detect test runner
73
+ test_cmd = self.runner.detect_test_command()
74
+ log(f"Target test command: `{test_cmd}`")
75
+
76
+ # 3. Create branch if git repo
77
+ branch_name = None
78
+ if self.git.is_git_repo() and self.config.create_branch:
79
+ clean_slug = re.sub(r"[^a-zA-Z0-9_-]", "-", issue_text.lower())[:30].strip("-")
80
+ branch_name = f"{self.config.branch_prefix}/{clean_slug}"
81
+ self.git.create_and_checkout_branch(branch_name)
82
+ log(f"Created working git branch: {branch_name}")
83
+
84
+ # 4. Ask Gemini to locate target file and read its contents
85
+ log("Diagnosing relevant files for the bug...")
86
+ locate_prompt = f"""
87
+ Given the repository file list:
88
+ {json.dumps(files, indent=2)}
89
+
90
+ And the reported issue:
91
+ "{issue_text}"
92
+
93
+ Which file is most likely causing this bug or needs to be modified?
94
+ Return ONLY a JSON list of 1 to 3 relative file paths. Example:
95
+ ["src/auth.py", "tests/test_auth.py"]
96
+ """
97
+ target_files_resp = self._call_llm(locate_prompt)
98
+ try:
99
+ match = re.search(r"\[.*\]", target_files_resp, re.DOTALL)
100
+ target_files = json.loads(match.group(0)) if match else [files[0]]
101
+ except Exception:
102
+ target_files = [files[0]] if files else []
103
+
104
+ log(f"Identified candidate files: {target_files}")
105
+
106
+ # Read contents of candidate files
107
+ context_files = {}
108
+ for tf in target_files:
109
+ fp = self.repo_dir / tf
110
+ if fp.is_file():
111
+ try:
112
+ with open(fp, "r", encoding="utf-8") as f:
113
+ context_files[tf] = f.read()
114
+ except Exception:
115
+ pass
116
+
117
+ # 5. Iterative Self-Healing Loop
118
+ attempt = 0
119
+ tests_passed = False
120
+ last_test_output = ""
121
+ patched_files = []
122
+
123
+ while attempt < self.config.max_healing_attempts and not tests_passed:
124
+ attempt += 1
125
+ log(f"Healing iteration {attempt}/{self.config.max_healing_attempts}...")
126
+
127
+ patch_prompt = f"""
128
+ Issue to resolve:
129
+ "{issue_text}"
130
+
131
+ Candidate file contents:
132
+ {json.dumps(context_files, indent=2)}
133
+
134
+ Previous test run result / traceback:
135
+ {last_test_output or 'Initial run - no previous traceback.'}
136
+
137
+ TASK:
138
+ Provide the complete replacement code for the file that needs fixing.
139
+ Respond with a JSON object where each key is the relative file path and each value is the complete, valid file content.
140
+ Example:
141
+ {{
142
+ "src/module.py": "...full code..."
143
+ }}
144
+ """
145
+ system_prompt = (
146
+ "You are an elite principal software engineer. "
147
+ "Fix bugs cleanly while maintaining backward compatibility and adhering to project style. "
148
+ "Return ONLY the requested JSON object."
149
+ )
150
+
151
+ raw_patch = self._call_llm(patch_prompt, system_prompt=system_prompt)
152
+ try:
153
+ match = re.search(r"\{.*\}", raw_patch, re.DOTALL)
154
+ patch_dict = json.loads(match.group(0)) if match else {}
155
+ except Exception as e:
156
+ log(f"Failed to parse patch JSON: {e}")
157
+ patch_dict = {}
158
+
159
+ if not patch_dict:
160
+ log("No files modified in this attempt.")
161
+ break
162
+
163
+ # Apply patch to disk
164
+ for rel_path, new_content in patch_dict.items():
165
+ target_path = self.repo_dir / rel_path
166
+ target_path.parent.mkdir(parents=True, exist_ok=True)
167
+ with open(target_path, "w", encoding="utf-8") as f:
168
+ f.write(new_content)
169
+ context_files[rel_path] = new_content
170
+ if rel_path not in patched_files:
171
+ patched_files.append(rel_path)
172
+ log(f"Applied patch to: {rel_path}")
173
+
174
+ # Run test suite
175
+ log(f"Executing tests (`{test_cmd}`)...")
176
+ test_res = self.runner.run_tests(test_cmd)
177
+
178
+ if test_res.passed:
179
+ log("✅ All tests passed successfully!")
180
+ tests_passed = True
181
+ break
182
+ else:
183
+ log(f"❌ Tests failed (exit code {test_res.exit_code}). Capturing stack trace for self-healing...")
184
+ last_test_output = test_res.output_summary
185
+
186
+ # 6. Commit if tests passed and git repo
187
+ commit_message = ""
188
+ if self.git.is_git_repo():
189
+ status = self.git.get_status()
190
+ if status:
191
+ commit_message = f"fix: resolve {issue_text[:50]}"
192
+ self.git.stage_all_and_commit(commit_message)
193
+ log(f"Committed changes with message: '{commit_message}'")
194
+
195
+ diff = self.git.get_diff() if self.git.is_git_repo() else ""
196
+
197
+ return {
198
+ "success": tests_passed,
199
+ "attempts": attempt,
200
+ "patched_files": patched_files,
201
+ "branch": branch_name,
202
+ "commit_message": commit_message,
203
+ "diff": diff,
204
+ "test_command": test_cmd,
205
+ }
patch_pilot/cli.py ADDED
@@ -0,0 +1,116 @@
1
+ """
2
+ Command-line interface for Patch Pilot.
3
+ """
4
+
5
+ import sys
6
+ import argparse
7
+ from pathlib import Path
8
+ from rich.console import Console
9
+ from rich.panel import Panel
10
+ from rich.table import Table
11
+
12
+ from .config import PatchConfig
13
+ from .agent import PatchPilotAgent
14
+
15
+ console = Console()
16
+
17
+ BANNER = """[bold green]
18
+ ___ _ __ ___ _ __ __
19
+ / _ \\___ _/ /_____/ / ____/ _ \\(_) /___ / /_
20
+ / ___/ _ `/ __/ __/ _ \\/___/ ___/ / / _ \\/ __/
21
+ /_/ \\_,_/\\__/\\__/_//_/ /_/ /_/_/\\___/\\__/
22
+ [/bold green]
23
+ [dim]🤖 Autonomous Code Healing & Bug Patching • Gemini | Claude | GPT | DeepSeek | Nemotron[/dim]
24
+ """
25
+
26
+
27
+ def main():
28
+ parser = argparse.ArgumentParser(
29
+ description="Patch Pilot — Autonomous Test-Driven Bug Patching Agent supporting Gemini, Claude, GPT, DeepSeek, and Ollama"
30
+ )
31
+ parser.add_argument("issue", nargs="?", help="Description of the bug or issue to resolve.")
32
+ parser.add_argument("--repo", "-r", type=str, default=".", help="Path to local git repo (default: current directory)")
33
+ parser.add_argument("--provider", "-p", type=str, default=None, help="LLM Provider: gemini, openai, anthropic, deepseek, nvidia, ollama, openrouter")
34
+ parser.add_argument("--model", "-m", type=str, default=None, help="Model identifier (e.g. claude-3-5-sonnet, gpt-4o, gemini-2.5-flash)")
35
+ parser.add_argument("--test-cmd", "-t", type=str, default=None, help="Custom test command (e.g. 'pytest tests/test_auth.py')")
36
+ parser.add_argument("--max-attempts", type=int, default=4, help="Max healing iterations (default: 4)")
37
+ parser.add_argument("--api-key", "-k", type=str, default=None, help="API Key override")
38
+ parser.add_argument("--base-url", type=str, default=None, help="Custom API Base URL (for Ollama, vLLM, etc.)")
39
+ parser.add_argument("--no-branch", action="store_true", help="Do not create a git branch")
40
+
41
+ args = parser.parse_args()
42
+
43
+ console.print(BANNER)
44
+
45
+ issue = args.issue
46
+ if not issue:
47
+ issue = console.input("[bold yellow]Describe the bug to fix: [/bold yellow]").strip()
48
+
49
+ if not issue:
50
+ console.print("[red]Error: Bug description cannot be empty.[/red]")
51
+ sys.exit(1)
52
+
53
+ repo_path = Path(args.repo).resolve()
54
+ if not repo_path.is_dir():
55
+ console.print(f"[red]Error: Directory '{repo_path}' does not exist.[/red]")
56
+ sys.exit(1)
57
+
58
+ config = PatchConfig(
59
+ provider=args.provider,
60
+ model=args.model,
61
+ api_key=args.api_key,
62
+ base_url=args.base_url,
63
+ max_healing_attempts=args.max_attempts,
64
+ test_command=args.test_cmd,
65
+ target_repo_dir=repo_path,
66
+ create_branch=not args.no_branch,
67
+ )
68
+
69
+ try:
70
+ config.validate()
71
+ except ValueError as e:
72
+ console.print(Panel(f"[bold red]Configuration Error:[/bold red]\n{str(e)}", border_style="red"))
73
+ sys.exit(1)
74
+
75
+ agent = PatchPilotAgent(config=config)
76
+
77
+ console.print(Panel(
78
+ f"[bold white]Repo:[/bold white] {repo_path}\n"
79
+ f"[bold white]Issue:[/bold white] {issue}\n"
80
+ f"[bold white]Provider:[/bold white] {agent.llm.provider.upper()} | [bold white]Model:[/bold white] {agent.llm.model}",
81
+ title="[bold green]Mission Activated[/bold green]",
82
+ border_style="green"
83
+ ))
84
+
85
+ with console.status("[bold green]Patch Pilot diagnosing and healing code...[/bold green]", spinner="dots") as status:
86
+ def on_step(msg: str):
87
+ status.update(f"[bold green]{msg}[/bold green]")
88
+ console.print(f" [dim]•[/dim] {msg}")
89
+
90
+ try:
91
+ result = agent.solve_issue(issue_text=issue, on_step=on_step)
92
+ except Exception as e:
93
+ console.print(f"\n[bold red]Execution error:[/bold red] {e}")
94
+ sys.exit(1)
95
+
96
+ # Display results
97
+ table = Table(title="Patch Pilot Execution Summary", border_style="green")
98
+ table.add_column("Property", style="cyan")
99
+ table.add_column("Value", style="white")
100
+
101
+ status_str = "[bold green]RESOLVED & VERIFIED[/bold green]" if result["success"] else "[bold red]FAILED[/bold red]"
102
+ table.add_row("Outcome", status_str)
103
+ table.add_row("Healing Attempts", str(result["attempts"]))
104
+ table.add_row("Patched Files", ", ".join(result["patched_files"]) or "None")
105
+ if result.get("branch"):
106
+ table.add_row("Git Branch", result["branch"])
107
+ if result.get("commit_message"):
108
+ table.add_row("Git Commit", result["commit_message"])
109
+ table.add_row("Test Suite", result["test_command"])
110
+
111
+ console.print("\n")
112
+ console.print(table)
113
+
114
+
115
+ if __name__ == "__main__":
116
+ main()
patch_pilot/config.py ADDED
@@ -0,0 +1,66 @@
1
+ """
2
+ Configuration for Patch Pilot agent supporting multiple LLM providers.
3
+ """
4
+
5
+ import os
6
+ from pathlib import Path
7
+ from dataclasses import dataclass, field
8
+ from typing import Optional, List
9
+
10
+
11
+ def load_env():
12
+ """Load nearby .env file if available."""
13
+ for p in [Path.cwd() / ".env", Path.cwd() / ".env.local", Path.home() / ".config" / "patch-pilot" / ".env"]:
14
+ if p.is_file():
15
+ try:
16
+ with open(p, "r", encoding="utf-8") as f:
17
+ for line in f:
18
+ line = line.strip()
19
+ if line and not line.startswith("#") and "=" in line:
20
+ k, v = line.split("=", 1)
21
+ k, v = k.strip(), v.strip().strip("'\"")
22
+ if k and k not in os.environ:
23
+ os.environ[k] = v
24
+ break
25
+ except Exception:
26
+ pass
27
+
28
+
29
+ load_env()
30
+
31
+
32
+ @dataclass
33
+ class PatchConfig:
34
+ provider: Optional[str] = None
35
+ model: Optional[str] = None
36
+ api_key: Optional[str] = None
37
+ base_url: Optional[str] = None
38
+ max_healing_attempts: int = 4
39
+ test_command: Optional[str] = None
40
+ timeout_per_run: int = 45
41
+ target_repo_dir: Path = field(default_factory=Path.cwd)
42
+ create_branch: bool = True
43
+ branch_prefix: str = "fix/patch-pilot"
44
+
45
+ def validate(self):
46
+ available_keys = [
47
+ self.api_key,
48
+ os.getenv("GEMINI_API_KEY"),
49
+ os.getenv("OPENAI_API_KEY"),
50
+ os.getenv("ANTHROPIC_API_KEY"),
51
+ os.getenv("OPENROUTER_API_KEY"),
52
+ os.getenv("DEEPSEEK_API_KEY"),
53
+ os.getenv("NVIDIA_API_KEY"),
54
+ self.base_url,
55
+ ]
56
+ if not any(available_keys):
57
+ raise ValueError(
58
+ "No API Key found.\n"
59
+ "Please set one of the following environment variables:\n"
60
+ " • export GEMINI_API_KEY='...'\n"
61
+ " • export OPENAI_API_KEY='...'\n"
62
+ " • export ANTHROPIC_API_KEY='...'\n"
63
+ " • export DEEPSEEK_API_KEY='...'\n"
64
+ " • export NVIDIA_API_KEY='...'\n"
65
+ "Or pass --api-key / --base-url."
66
+ )
patch_pilot/git_ops.py ADDED
@@ -0,0 +1,47 @@
1
+ """
2
+ Git operations wrapper for Patch Pilot.
3
+ """
4
+
5
+ import subprocess
6
+ from pathlib import Path
7
+ from typing import Optional, Tuple
8
+
9
+
10
+ class GitRepo:
11
+ """Helper for git repository manipulation."""
12
+
13
+ def __init__(self, repo_path: Path):
14
+ self.repo_path = repo_path
15
+
16
+ def _run(self, args: list) -> Tuple[int, str, str]:
17
+ res = subprocess.run(
18
+ ["git"] + args,
19
+ cwd=str(self.repo_path),
20
+ capture_output=True,
21
+ text=True,
22
+ )
23
+ return res.returncode, res.stdout, res.stderr
24
+
25
+ def is_git_repo(self) -> bool:
26
+ code, out, _ = self._run(["rev-parse", "--is-inside-work-tree"])
27
+ return code == 0 and "true" in out
28
+
29
+ def get_diff(self) -> str:
30
+ code, out, _ = self._run(["diff"])
31
+ return out
32
+
33
+ def create_and_checkout_branch(self, branch_name: str) -> bool:
34
+ code, _, _ = self._run(["checkout", "-b", branch_name])
35
+ if code != 0:
36
+ # Try switching to it if it already exists
37
+ code, _, _ = self._run(["checkout", branch_name])
38
+ return code == 0
39
+
40
+ def stage_all_and_commit(self, message: str) -> bool:
41
+ self._run(["add", "-A"])
42
+ code, out, err = self._run(["commit", "-m", message])
43
+ return code == 0
44
+
45
+ def get_status(self) -> str:
46
+ _, out, _ = self._run(["status", "--short"])
47
+ return out
patch_pilot/llm.py ADDED
@@ -0,0 +1,184 @@
1
+ """
2
+ Unified multi-provider LLM interface for Patch Pilot supporting Gemini, Claude, GPT, DeepSeek, Nemotron, and Ollama.
3
+ """
4
+
5
+ import os
6
+ import json
7
+ import logging
8
+ from typing import Optional, Dict, Any, List
9
+ import requests
10
+
11
+ logger = logging.getLogger(__name__)
12
+
13
+
14
+ class UnifiedLLM:
15
+ """
16
+ Universal LLM client that routes requests to:
17
+ - Google Gemini
18
+ - OpenAI (GPT-4o, o1, o3-mini)
19
+ - Anthropic (Claude 3.5 Sonnet, Claude 3.7 Sonnet)
20
+ - OpenAI-Compatible endpoints (OpenRouter, DeepSeek, NVIDIA Nemotron, Ollama, vLLM)
21
+ """
22
+
23
+ def __init__(
24
+ self,
25
+ provider: Optional[str] = None,
26
+ model: Optional[str] = None,
27
+ api_key: Optional[str] = None,
28
+ base_url: Optional[str] = None,
29
+ timeout: int = 60,
30
+ ):
31
+ self.api_key = api_key
32
+ self.base_url = base_url
33
+ self.timeout = timeout
34
+ self.provider, self.model = self._resolve_provider_and_model(provider, model)
35
+ self._resolve_api_key()
36
+
37
+ def _resolve_provider_and_model(self, provider: Optional[str], model: Optional[str]) -> tuple:
38
+ if provider:
39
+ p = provider.lower()
40
+ m = model or self._default_model_for_provider(p)
41
+ return p, m
42
+
43
+ m = (model or "").lower()
44
+ if "claude" in m:
45
+ return "anthropic", model
46
+ if any(x in m for x in ["gpt", "o1", "o3", "chatgpt"]):
47
+ return "openai", model
48
+ if "gemini" in m:
49
+ return "gemini", model
50
+ if "deepseek" in m:
51
+ return "deepseek", model
52
+ if "nemotron" in m or "nvidia" in m:
53
+ return "nvidia", model
54
+
55
+ # Check environment variable presence
56
+ if os.getenv("GEMINI_API_KEY"):
57
+ return "gemini", model or "gemini-2.5-flash"
58
+ if os.getenv("OPENAI_API_KEY"):
59
+ return "openai", model or "gpt-4o"
60
+ if os.getenv("ANTHROPIC_API_KEY"):
61
+ return "anthropic", model or "claude-3-5-sonnet-20241022"
62
+ if os.getenv("OPENROUTER_API_KEY"):
63
+ return "openrouter", model or "meta-llama/llama-3.3-70b-instruct"
64
+ if os.getenv("DEEPSEEK_API_KEY"):
65
+ return "deepseek", model or "deepseek-chat"
66
+
67
+ return "gemini", model or "gemini-2.5-flash"
68
+
69
+ def _default_model_for_provider(self, provider: str) -> str:
70
+ defaults = {
71
+ "gemini": "gemini-2.5-flash",
72
+ "openai": "gpt-4o",
73
+ "anthropic": "claude-3-5-sonnet-20241022",
74
+ "openrouter": "meta-llama/llama-3.3-70b-instruct",
75
+ "deepseek": "deepseek-chat",
76
+ "nvidia": "nvidia/nemotron-4-340b-instruct",
77
+ "ollama": "llama3.2",
78
+ }
79
+ return defaults.get(provider, "gemini-2.5-flash")
80
+
81
+ def _resolve_api_key(self):
82
+ if self.api_key:
83
+ return
84
+
85
+ key_map = {
86
+ "gemini": "GEMINI_API_KEY",
87
+ "openai": "OPENAI_API_KEY",
88
+ "anthropic": "ANTHROPIC_API_KEY",
89
+ "openrouter": "OPENROUTER_API_KEY",
90
+ "deepseek": "DEEPSEEK_API_KEY",
91
+ "nvidia": "NVIDIA_API_KEY",
92
+ }
93
+ env_var = key_map.get(self.provider)
94
+ if env_var:
95
+ self.api_key = os.getenv(env_var)
96
+
97
+ def generate(self, prompt: str, system_instruction: Optional[str] = None) -> str:
98
+ if self.provider == "gemini":
99
+ return self._call_gemini(prompt, system_instruction)
100
+ elif self.provider == "anthropic":
101
+ return self._call_anthropic(prompt, system_instruction)
102
+ elif self.provider in ("openai", "openrouter", "deepseek", "nvidia", "ollama") or self.base_url:
103
+ return self._call_openai_compatible(prompt, system_instruction)
104
+ else:
105
+ return self._call_gemini(prompt, system_instruction)
106
+
107
+ def _call_gemini(self, prompt: str, system_instruction: Optional[str]) -> str:
108
+ try:
109
+ from google import genai
110
+ from google.genai import types
111
+ client = genai.Client(api_key=self.api_key)
112
+ cfg = {}
113
+ if system_instruction:
114
+ cfg["system_instruction"] = system_instruction
115
+ res = client.models.generate_content(
116
+ model=self.model,
117
+ contents=prompt,
118
+ config=types.GenerateContentConfig(**cfg) if cfg else None
119
+ )
120
+ if res and res.text:
121
+ return res.text
122
+ except Exception:
123
+ pass
124
+
125
+ url = f"https://generativelanguage.googleapis.com/v1beta/models/{self.model}:generateContent?key={self.api_key}"
126
+ contents = []
127
+ if system_instruction:
128
+ contents.append({"role": "user", "parts": [{"text": f"SYSTEM: {system_instruction}"}]})
129
+ contents.append({"role": "user", "parts": [{"text": prompt}]})
130
+ resp = requests.post(url, json={"contents": contents}, timeout=self.timeout)
131
+ resp.raise_for_status()
132
+ data = resp.json()
133
+ return data["candidates"][0]["content"]["parts"][0]["text"]
134
+
135
+ def _call_anthropic(self, prompt: str, system_instruction: Optional[str]) -> str:
136
+ url = "https://api.anthropic.com/v1/messages"
137
+ headers = {
138
+ "x-api-key": self.api_key or "",
139
+ "anthropic-version": "2023-06-01",
140
+ "content-type": "application/json",
141
+ }
142
+ payload = {
143
+ "model": self.model,
144
+ "max_tokens": 4096,
145
+ "messages": [{"role": "user", "content": prompt}],
146
+ }
147
+ if system_instruction:
148
+ payload["system"] = system_instruction
149
+
150
+ resp = requests.post(url, json=payload, headers=headers, timeout=self.timeout)
151
+ resp.raise_for_status()
152
+ data = resp.json()
153
+ content = data.get("content", [])
154
+ if content and "text" in content[0]:
155
+ return content[0]["text"]
156
+ return ""
157
+
158
+ def _call_openai_compatible(self, prompt: str, system_instruction: Optional[str]) -> str:
159
+ endpoint_map = {
160
+ "openai": "https://api.openai.com/v1/chat/completions",
161
+ "openrouter": "https://openrouter.ai/api/v1/chat/completions",
162
+ "deepseek": "https://api.deepseek.com/v1/chat/completions",
163
+ "nvidia": "https://integrate.api.nvidia.com/v1/chat/completions",
164
+ "ollama": "http://localhost:11434/v1/chat/completions",
165
+ }
166
+ url = self.base_url or endpoint_map.get(self.provider, "https://api.openai.com/v1/chat/completions")
167
+ headers = {
168
+ "Authorization": f"Bearer {self.api_key or ''}",
169
+ "Content-Type": "application/json",
170
+ }
171
+ messages = []
172
+ if system_instruction:
173
+ messages.append({"role": "system", "content": system_instruction})
174
+ messages.append({"role": "user", "content": prompt})
175
+
176
+ payload = {
177
+ "model": self.model,
178
+ "messages": messages,
179
+ }
180
+
181
+ resp = requests.post(url, json=payload, headers=headers, timeout=self.timeout)
182
+ resp.raise_for_status()
183
+ data = resp.json()
184
+ return data["choices"][0]["message"]["content"]
patch_pilot/runner.py ADDED
@@ -0,0 +1,94 @@
1
+ """
2
+ Subprocess test runner and automatic framework detector.
3
+ """
4
+
5
+ import subprocess
6
+ from pathlib import Path
7
+ from typing import Tuple, Optional
8
+ from dataclasses import dataclass
9
+
10
+
11
+ @dataclass
12
+ class TestResult:
13
+ command: str
14
+ passed: bool
15
+ exit_code: int
16
+ stdout: str
17
+ stderr: str
18
+ output_summary: str
19
+
20
+
21
+ class TestRunner:
22
+ """Detects and runs project tests."""
23
+
24
+ def __init__(self, repo_dir: Path, custom_cmd: Optional[str] = None, timeout: int = 45):
25
+ self.repo_dir = repo_dir
26
+ self.custom_cmd = custom_cmd
27
+ self.timeout = timeout
28
+
29
+ def detect_test_command(self) -> str:
30
+ """Auto-detect test command based on repo markers."""
31
+ if self.custom_cmd:
32
+ return self.custom_cmd
33
+
34
+ # Python
35
+ if (self.repo_dir / "pytest.ini").is_file() or (self.repo_dir / "pyproject.toml").is_file() or (self.repo_dir / "tests").is_dir():
36
+ return "pytest"
37
+ if (self.repo_dir / "setup.py").is_file():
38
+ return "python -m unittest discover"
39
+
40
+ # Node / JS
41
+ if (self.repo_dir / "package.json").is_file():
42
+ return "npm test"
43
+
44
+ # Rust
45
+ if (self.repo_dir / "Cargo.toml").is_file():
46
+ return "cargo test"
47
+
48
+ # Go
49
+ if (self.repo_dir / "go.mod").is_file():
50
+ return "go test ./..."
51
+
52
+ return "pytest"
53
+
54
+ def run_tests(self, command: Optional[str] = None) -> TestResult:
55
+ """Executes test suite and captures output."""
56
+ cmd_str = command or self.detect_test_command()
57
+ try:
58
+ res = subprocess.run(
59
+ cmd_str,
60
+ cwd=str(self.repo_dir),
61
+ shell=True,
62
+ capture_output=True,
63
+ text=True,
64
+ timeout=self.timeout
65
+ )
66
+ passed = (res.returncode == 0)
67
+ combined_output = (res.stdout + "\n" + res.stderr).strip()
68
+ summary = "\n".join(combined_output.splitlines()[-25:]) if combined_output else "No output"
69
+ return TestResult(
70
+ command=cmd_str,
71
+ passed=passed,
72
+ exit_code=res.returncode,
73
+ stdout=res.stdout,
74
+ stderr=res.stderr,
75
+ output_summary=summary,
76
+ )
77
+ except subprocess.TimeoutExpired:
78
+ return TestResult(
79
+ command=cmd_str,
80
+ passed=False,
81
+ exit_code=-1,
82
+ stdout="",
83
+ stderr="Execution timed out",
84
+ output_summary=f"Test timed out after {self.timeout}s",
85
+ )
86
+ except Exception as e:
87
+ return TestResult(
88
+ command=cmd_str,
89
+ passed=False,
90
+ exit_code=-1,
91
+ stdout="",
92
+ stderr=str(e),
93
+ output_summary=f"Failed to run test command: {e}",
94
+ )
@@ -0,0 +1,150 @@
1
+ Metadata-Version: 2.4
2
+ Name: patch-pilot-ai
3
+ Version: 0.1.0
4
+ Summary: Autonomous code healing and bug patching agent powered by Google Gemini.
5
+ Author: Shubhransh Gupta
6
+ License: MIT
7
+ Keywords: swe-agent,bug-fixer,gemini,ai-agent,autonomous-agent,self-healing,automated-testing,git,python,code-generation
8
+ Classifier: Development Status :: 4 - Beta
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.10
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Topic :: Software Development :: Bug Tracking
16
+ Classifier: Topic :: Software Development :: Quality Assurance
17
+ Requires-Python: >=3.10
18
+ Description-Content-Type: text/markdown
19
+ Requires-Dist: google-genai>=3.0.0
20
+ Requires-Dist: rich>=13.0.0
21
+ Requires-Dist: requests>=2.28.0
22
+ Requires-Dist: pydantic>=2.0.0
23
+ Provides-Extra: dev
24
+ Requires-Dist: pytest>=7.0.0; extra == "dev"
25
+
26
+ # 🤖 Patch Pilot
27
+
28
+ [![Documentation](https://img.shields.io/badge/Documentation-Apple%20HIG%20Style-blue?style=for-the-badge&logo=vercel)](https://agent-docs-coral.vercel.app#patch-pilot)
29
+ [![GitHub Stars](https://img.shields.io/github/stars/shubhransh-gupta/patch-pilot?style=for-the-badge&color=30d158)](https://github.com/shubhransh-gupta/patch-pilot/stargazers)
30
+ [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg?style=for-the-badge)](https://opensource.org/licenses/MIT)
31
+
32
+ > **📖 Live Documentation & Interactive FAQs:** [https://agent-docs-coral.vercel.app#patch-pilot](https://agent-docs-coral.vercel.app#patch-pilot)
33
+
34
+ <p align="center">
35
+ <img src="assets/demo.svg" alt="Patch Pilot Live Terminal Demo" width="100%" />
36
+ </p>
37
+
38
+ An autonomous test-driven code healing and bug patching agent with **universal model support**.
39
+
40
+ Patch Pilot inspects your local repository, analyzes bug descriptions, pinpoints root-cause files, iteratively applies patches, executes your test suite, and feeds back error stack traces until tests pass and changes are committed cleanly to Git.
41
+
42
+ ## 🌐 Universal Model Support (Bring Your Own Key)
43
+
44
+ Patch Pilot works with all major AI providers or entirely local setups:
45
+
46
+ | Provider | Supported Models | Environment Variable |
47
+ | :--- | :--- | :--- |
48
+ | **Anthropic Claude** | `claude-3-5-sonnet-20241022`, `claude-3-7-sonnet` | `export ANTHROPIC_API_KEY="..."` |
49
+ | **OpenAI** | `gpt-4o`, `gpt-4o-mini`, `o1`, `o3-mini` | `export OPENAI_API_KEY="..."` |
50
+ | **Google Gemini** | `gemini-2.5-flash`, `gemini-2.5-pro`, `gemini-1.5-pro` | `export GEMINI_API_KEY="..."` |
51
+ | **DeepSeek** | `deepseek-chat`, `deepseek-reasoner` | `export DEEPSEEK_API_KEY="..."` |
52
+ | **NVIDIA Nemotron** | `nvidia/nemotron-4-340b-instruct` | `export NVIDIA_API_KEY="..."` |
53
+ | **OpenRouter** | 200+ models across all frontier labs | `export OPENROUTER_API_KEY="..."` |
54
+ | **Local / Self-Hosted** | Ollama (`qwen2.5-coder`, `llama3.2`, `deepseek-r1`), vLLM | `--base-url http://localhost:11434/v1` |
55
+
56
+ ## 🌟 Key Capabilities
57
+
58
+ - **Multi-Model Intelligence**: Fix code using Claude 3.5 Sonnet, GPT-4o, Gemini 2.5, DeepSeek-Coder, or local Ollama.
59
+ - **Automatic Test Runner Detection**: Supports `pytest`, `unittest`, `npm test`, `cargo test`, and `go test` with zero configuration.
60
+ - **Iterative Self-Healing Loop**: If a patch fails the test suite, Patch Pilot captures the exact error tracebacks and re-prompts the model to refine the fix.
61
+ - **Git Branch & Commit Automation**: Automatically isolates changes in a dedicated Git feature branch and writes conventional commit messages upon test verification.
62
+
63
+ ## 🚀 Quick Start
64
+
65
+ ### 1. Installation
66
+
67
+ ```bash
68
+ git clone https://github.com/shubhransh-gupta/patch-pilot.git
69
+ cd patch-pilot
70
+ pip install -e .
71
+ ```
72
+
73
+ ### ⚡ Use as a GitHub Action in Your CI/CD
74
+
75
+ You can drop Patch Pilot directly into any repository's CI pipeline to automatically self-heal failing builds:
76
+
77
+ ```yaml
78
+ - name: Run Patch Pilot Self-Healing
79
+ uses: shubhransh-gupta/patch-pilot@v1
80
+ with:
81
+ api-key: ${{ secrets.GEMINI_API_KEY }}
82
+ provider: 'gemini'
83
+ issue: 'Fix failing unit tests in CI build'
84
+ ```
85
+
86
+ ### 2. Set Your Preferred API Key
87
+
88
+ Choose any provider:
89
+ ```bash
90
+ # Option A: Anthropic Claude (Great for complex reasoning)
91
+ export ANTHROPIC_API_KEY="sk-ant-..."
92
+
93
+ # Option B: OpenAI
94
+ export OPENAI_API_KEY="sk-proj-..."
95
+
96
+ # Option C: Google Gemini
97
+ export GEMINI_API_KEY="AIzaSy..."
98
+
99
+ # Option D: DeepSeek
100
+ export DEEPSEEK_API_KEY="sk-..."
101
+ ```
102
+
103
+ ### 3. Run Patch Pilot Inside Any Repo
104
+
105
+ ```bash
106
+ cd my-project/
107
+
108
+ # Auto-detects provider from your exported environment variable
109
+ patch-pilot "Fix KeyError when parsing optional config headers in client.py"
110
+
111
+ # Or explicitly choose provider and model
112
+ patch-pilot "Fix race condition in token refresher" --provider anthropic --model claude-3-5-sonnet-20241022
113
+
114
+ # Or run with local Ollama
115
+ patch-pilot "Fix off-by-one error in pagination" --base-url http://localhost:11434/v1 --model qwen2.5-coder
116
+ ```
117
+
118
+ ## ⚙️ Options
119
+
120
+ ```bash
121
+ patch-pilot [ISSUE] [OPTIONS]
122
+
123
+ Options:
124
+ --provider, -p TEXT LLM provider: gemini, openai, anthropic, deepseek, nvidia, ollama, openrouter
125
+ --model, -m TEXT Specific model identifier
126
+ --base-url TEXT Custom API base URL (for Ollama, vLLM, etc.)
127
+ --repo, -r PATH Path to local repository (default: .)
128
+ --test-cmd, -t TEXT Custom test command (e.g. 'pytest tests/test_auth.py')
129
+ --max-attempts INT Max self-healing iterations (default: 4)
130
+ --api-key, -k TEXT Explicit API key override
131
+ --no-branch Skip automatic git branch creation
132
+ ```
133
+
134
+ ## 📦 Project Structure
135
+
136
+ ```
137
+ patch-pilot/
138
+ ├── patch_pilot/
139
+ │ ├── agent.py # Core self-healing loop and diagnosis orchestrator
140
+ │ ├── llm.py # Universal multi-provider LLM interface (Claude/GPT/Gemini/Ollama)
141
+ │ ├── runner.py # Subprocess test executor and framework detector
142
+ │ ├── git_ops.py # Git branch and commit wrapper
143
+ │ ├── config.py # Configuration and model settings
144
+ │ └── cli.py # Rich terminal interface
145
+ └── pyproject.toml # Packaging and entry points
146
+ ```
147
+
148
+ ## 📄 License
149
+
150
+ MIT License. Copyright (c) 2026 Shubhransh Gupta.
@@ -0,0 +1,12 @@
1
+ patch_pilot/__init__.py,sha256=RTOsaTqBytiCp1GymHUltdmspYPv7akDHGbShuZh93U,289
2
+ patch_pilot/agent.py,sha256=67pfBlM-tYOYpyhFVzRbFeH2ICAgz0s3p0Z7qeXdP0U,7511
3
+ patch_pilot/cli.py,sha256=SKn4xgUOne-9AXLwSxr2zNkDgCttmzlxlJsKZ9PwOfs,4584
4
+ patch_pilot/config.py,sha256=eJAu-77zR3dFmridJ34To8Hqb0_cd13-HCKkXrUH_dM,2233
5
+ patch_pilot/git_ops.py,sha256=FafKPVf-NcyPqDUzbuzr5X127HBSPCylVNAbZ6gc8HI,1371
6
+ patch_pilot/llm.py,sha256=908EKCnGpTuv5qoshPEbzXAQgZttNx_JYDxN1IMenVY,7058
7
+ patch_pilot/runner.py,sha256=2fHJkVqasfeUljCiXTq_VnG5v-zUegeBzQBRQnHkbug,2893
8
+ patch_pilot_ai-0.1.0.dist-info/METADATA,sha256=f_8-AkyZjZ_PWQ9JFq2Z-lohDjx7ptIyMZLTbSlduek,6267
9
+ patch_pilot_ai-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
10
+ patch_pilot_ai-0.1.0.dist-info/entry_points.txt,sha256=IN9SZNZXmaF4ZT22GJmu2v775yhdkV1tp_Yx2WJZV1o,53
11
+ patch_pilot_ai-0.1.0.dist-info/top_level.txt,sha256=HJHtJChTGQ6S9psHFetojqlbv4Hs1E1SorY5Ew20X5Q,12
12
+ patch_pilot_ai-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ patch-pilot = patch_pilot.cli:main
@@ -0,0 +1 @@
1
+ patch_pilot