Muhammad Faraz Malik commited on
Commit
0e26181
Β·
1 Parent(s): 4928c2c

Add fixed repository .zip download and one-click GitHub Pull Request creation

Browse files
src/tools/file_tools.py CHANGED
@@ -365,6 +365,16 @@ class Workspace:
365
  def full_diff(self) -> str:
366
  return "".join(self.diff(r) for r in self.changed_files())
367
 
 
 
 
 
 
 
 
 
 
 
368
 
369
  def validate_repro_path(rel: str) -> str:
370
  """Repro tests must be ``test_*.py`` / ``*_test.py`` files; returns the normalized path."""
 
365
  def full_diff(self) -> str:
366
  return "".join(self.diff(r) for r in self.changed_files())
367
 
368
+ def export_zip_bytes(self) -> bytes:
369
+ """Package the entire fixed working copy (``work/``) into an in-memory ``.zip`` archive."""
370
+ buf = io.BytesIO()
371
+ with zipfile.ZipFile(buf, "w", compression=zipfile.ZIP_DEFLATED) as zf:
372
+ for rel in _walk_files(self.work):
373
+ full = self.work / rel
374
+ if full.is_file():
375
+ zf.write(full, arcname=rel.as_posix())
376
+ return buf.getvalue()
377
+
378
 
379
  def validate_repro_path(rel: str) -> str:
380
  """Repro tests must be ``test_*.py`` / ``*_test.py`` files; returns the normalized path."""
src/tools/git_tools.py CHANGED
@@ -1,24 +1,29 @@
1
- """Git helpers invoked ONLY after human approval (`commit_and_pr` node).
2
 
3
- Copies approved changes back into the target repository (or creates a branch + commit
4
- if it is a git repository and `apply_to_repo=True`). When running against a temporary
5
- clone or non-git folder, it generates a deterministic commit SHA and patch bundle
6
- without touching external remotes unless explicitly asked.
7
  """
8
 
9
  from __future__ import annotations
10
 
 
11
  import hashlib
 
12
  import shutil
13
  import subprocess
 
14
  from dataclasses import dataclass
15
  from pathlib import Path, PurePosixPath
16
 
 
 
17
  from tools.file_tools import Workspace
18
 
19
 
20
  class GitError(Exception):
21
- """Git operation failed."""
22
 
23
 
24
  @dataclass(frozen=True)
@@ -29,6 +34,17 @@ class CommitResult:
29
  applied_to_repo: bool = False
30
 
31
 
 
 
 
 
 
 
 
 
 
 
 
32
  def is_git_repo(path: Path) -> bool:
33
  try:
34
  res = subprocess.run( # noqa: S603
@@ -88,3 +104,114 @@ def apply_workspace_to_repo(
88
  _git(repo_path, "commit", "-m", commit_message)
89
  sha = _git(repo_path, "rev-parse", "--short", "HEAD")
90
  return CommitResult(branch=branch_name, commit_sha=sha, applied_to_repo=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Git & GitHub PR helpers invoked ONLY after human approval (`commit_and_pr` node or UI).
2
 
3
+ Supports:
4
+ 1. Copying approved changes back into a local repository and creating a branch + commit.
5
+ 2. Pushing a fix branch (`agent/fix-...`) and opening a real Pull Request on GitHub via the
6
+ GitHub REST API using a user-supplied Personal Access Token (`github_token`).
7
  """
8
 
9
  from __future__ import annotations
10
 
11
+ import base64
12
  import hashlib
13
+ import re
14
  import shutil
15
  import subprocess
16
+ import uuid
17
  from dataclasses import dataclass
18
  from pathlib import Path, PurePosixPath
19
 
20
+ import httpx
21
+
22
  from tools.file_tools import Workspace
23
 
24
 
25
  class GitError(Exception):
26
+ """Git or GitHub API operation failed."""
27
 
28
 
29
  @dataclass(frozen=True)
 
34
  applied_to_repo: bool = False
35
 
36
 
37
+ def parse_github_owner_repo(repo_url: str) -> tuple[str, str] | None:
38
+ """Extract `(owner, repo)` from a GitHub HTTPS or SSH URL."""
39
+ m = re.search(
40
+ r"github\.com[:/](?P<owner>[A-Za-z0-9_.-]+)/(?P<repo>[A-Za-z0-9_.-]+?)(?:\.git|/.*)?$",
41
+ repo_url.strip(),
42
+ )
43
+ if not m:
44
+ return None
45
+ return m.group("owner"), m.group("repo")
46
+
47
+
48
  def is_git_repo(path: Path) -> bool:
49
  try:
50
  res = subprocess.run( # noqa: S603
 
104
  _git(repo_path, "commit", "-m", commit_message)
105
  sha = _git(repo_path, "rev-parse", "--short", "HEAD")
106
  return CommitResult(branch=branch_name, commit_sha=sha, applied_to_repo=True)
107
+
108
+
109
+ def create_github_pull_request(
110
+ ws: Workspace,
111
+ *,
112
+ repo_url: str,
113
+ github_token: str,
114
+ issue_title: str,
115
+ issue_body: str,
116
+ rationale: str,
117
+ branch_prefix: str = "agent/fix",
118
+ ) -> CommitResult:
119
+ """Create a branch, commit changed files, and open a Pull Request via the GitHub REST API.
120
+
121
+ Uses GitHub's Git Data / Contents REST endpoints over HTTPS so it works in cloud
122
+ containers without needing SSH keys or local git credentials.
123
+ """
124
+ parsed = parse_github_owner_repo(repo_url)
125
+ if not parsed:
126
+ raise GitError(f"Cannot parse GitHub owner/repo from URL: {repo_url!r}")
127
+ owner, repo = parsed
128
+ token = github_token.strip()
129
+ if not token:
130
+ raise GitError("A GitHub Personal Access Token (with `repo` or `contents:write` + `pull_requests:write` scope) is required.")
131
+
132
+ changed = ws.changed_files()
133
+ if not changed:
134
+ raise GitError("No modified files in workspace to commit.")
135
+
136
+ headers = {
137
+ "Authorization": f"Bearer {token}",
138
+ "Accept": "application/vnd.github+json",
139
+ "X-GitHub-Api-Version": "2022-11-28",
140
+ }
141
+ base_api = f"https://api.github.com/repos/{owner}/{repo}"
142
+
143
+ with httpx.Client(headers=headers, timeout=30.0) as client:
144
+ # 1. Get default branch name & its HEAD SHA
145
+ repo_resp = client.get(base_api)
146
+ if repo_resp.status_code != 200:
147
+ raise GitError(f"GitHub API error fetching {owner}/{repo}: {repo_resp.text[:200]}")
148
+ default_branch = repo_resp.json().get("default_branch", "main")
149
+
150
+ ref_resp = client.get(f"{base_api}/git/ref/heads/{default_branch}")
151
+ if ref_resp.status_code != 200:
152
+ raise GitError(f"Could not read branch {default_branch!r}: {ref_resp.text[:200]}")
153
+ base_sha = ref_resp.json()["object"]["sha"]
154
+
155
+ # 2. Create a new branch ref
156
+ branch_name = f"{branch_prefix}-{uuid.uuid4().hex[:6]}"
157
+ create_ref = client.post(
158
+ f"{base_api}/git/refs",
159
+ json={"ref": f"refs/heads/{branch_name}", "sha": base_sha},
160
+ )
161
+ if create_ref.status_code not in (200, 201):
162
+ raise GitError(
163
+ f"Could not create branch {branch_name!r} (check token write permissions): "
164
+ f"{create_ref.text[:200]}"
165
+ )
166
+
167
+ # 3. Commit each modified/new file onto the new branch via Contents API
168
+ last_commit_sha = base_sha[:7]
169
+ for rel in changed:
170
+ full = ws.work / Path(*PurePosixPath(rel).parts)
171
+ content_b64 = base64.b64encode(full.read_bytes()).decode("ascii")
172
+
173
+ existing_sha: str | None = None
174
+ existing = client.get(f"{base_api}/contents/{rel}", params={"ref": branch_name})
175
+ if existing.status_code == 200 and isinstance(existing.json(), dict):
176
+ existing_sha = existing.json().get("sha")
177
+
178
+ put_payload: dict[str, str] = {
179
+ "message": f"Fix: {issue_title} ({rel})",
180
+ "content": content_b64,
181
+ "branch": branch_name,
182
+ }
183
+ if existing_sha:
184
+ put_payload["sha"] = existing_sha
185
+
186
+ put_resp = client.put(f"{base_api}/contents/{rel}", json=put_payload)
187
+ if put_resp.status_code not in (200, 201):
188
+ raise GitError(f"Failed to commit {rel!r}: {put_resp.text[:200]}")
189
+ last_commit_sha = put_resp.json().get("commit", {}).get("sha", last_commit_sha)[:7]
190
+
191
+ # 4. Open the Pull Request
192
+ pr_body = (
193
+ f"## Automated Bug Fix\n\n"
194
+ f"**Issue:** {issue_title}\n\n"
195
+ f"{issue_body}\n\n"
196
+ f"### Root-Cause & Fix Rationale\n{rationale}\n\n"
197
+ f"### Files Changed\n" + "\n".join(f"- `{c}`" for c in changed)
198
+ )
199
+ pr_resp = client.post(
200
+ f"{base_api}/pulls",
201
+ json={
202
+ "title": f"Fix: {issue_title}",
203
+ "head": branch_name,
204
+ "base": default_branch,
205
+ "body": pr_body,
206
+ },
207
+ )
208
+ if pr_resp.status_code not in (200, 201):
209
+ raise GitError(f"Branch {branch_name!r} pushed, but PR creation failed: {pr_resp.text[:200]}")
210
+
211
+ pr_url = pr_resp.json().get("html_url")
212
+ return CommitResult(
213
+ branch=branch_name,
214
+ commit_sha=last_commit_sha,
215
+ pr_url=pr_url,
216
+ applied_to_repo=True,
217
+ )
src/ui/streamlit_app.py CHANGED
@@ -40,6 +40,7 @@ from tools.file_tools import (
40
  clone_repo_to_temp,
41
  create_repo_from_uploads,
42
  )
 
43
  from ui.mock_graph import (
44
  DEMO_ISSUE_BODY,
45
  DEMO_ISSUE_TITLE,
@@ -152,10 +153,14 @@ def start_run(
152
  elif repo_source == "GitHub URL (shallow clone)":
153
  with st.spinner(f"Cloning {repo_input.strip()}..."):
154
  target_path = clone_repo_to_temp(repo_input)
 
155
  else:
 
156
  target_path = Path(repo_input.strip()).expanduser().resolve()
157
  if not target_path.is_dir():
158
  raise WorkspaceError(f"Local folder does not exist: {target_path}")
 
 
159
  except Exception as exc:
160
  st.session_state.last_error = str(exc)
161
  return
@@ -239,6 +244,24 @@ def _render_report_download(values: dict[str, Any], key_suffix: str) -> None:
239
  st.caption(f"Could not generate PDF report: {exc}")
240
 
241
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
242
  def render_approval(payload: dict[str, Any], values: dict[str, Any]) -> None:
243
  st.subheader("⏸️ Waiting for your approval")
244
  st.caption(
@@ -252,7 +275,11 @@ def render_approval(payload: dict[str, Any], values: dict[str, Any]) -> None:
252
  with st.expander("Reproduction test"):
253
  st.code(payload["repro_test"], language="python")
254
 
255
- _render_report_download(values, key_suffix=f"approval-{payload['iteration']}")
 
 
 
 
256
 
257
  feedback = st.text_area(
258
  "Feedback for the agent (required to request changes)",
@@ -286,7 +313,8 @@ def render_outcome(values: dict[str, Any]) -> None:
286
  note = "Demo commit" if is_demo else "Approved commit"
287
  st.success(
288
  f"{note} `{values['commit_sha']}` on `{values['branch']}` "
289
- "(changes kept in the isolated workspace; download the patch or PDF report below)."
 
290
  )
291
  attempts: list[FixAttempt] = values["attempts"]
292
  patch = "\n".join(p.unified_diff for p in attempts[-1].patches)
@@ -295,7 +323,7 @@ def render_outcome(values: dict[str, Any]) -> None:
295
  patch = Workspace.open(values["workspace_root"]).full_diff() or patch
296
  except Exception: # noqa: BLE001
297
  pass
298
- col1, col2 = st.columns(2)
299
  with col1:
300
  st.download_button(
301
  "⬇️ Download patch (.patch)",
@@ -304,7 +332,50 @@ def render_outcome(values: dict[str, Any]) -> None:
304
  use_container_width=True,
305
  )
306
  with col2:
 
 
307
  _render_report_download(values, key_suffix="committed")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
308
  elif status == "escalated":
309
  st.error(f"Escalated: {values.get('error')}")
310
  _render_report_download(values, key_suffix="escalated")
 
40
  clone_repo_to_temp,
41
  create_repo_from_uploads,
42
  )
43
+ from tools.git_tools import GitError, create_github_pull_request, parse_github_owner_repo
44
  from ui.mock_graph import (
45
  DEMO_ISSUE_BODY,
46
  DEMO_ISSUE_TITLE,
 
153
  elif repo_source == "GitHub URL (shallow clone)":
154
  with st.spinner(f"Cloning {repo_input.strip()}..."):
155
  target_path = clone_repo_to_temp(repo_input)
156
+ st.session_state.repo_github_url = repo_input.strip()
157
  else:
158
+ st.session_state.repo_github_url = ""
159
  target_path = Path(repo_input.strip()).expanduser().resolve()
160
  if not target_path.is_dir():
161
  raise WorkspaceError(f"Local folder does not exist: {target_path}")
162
+ if repo_source != "GitHub URL (shallow clone)":
163
+ st.session_state.repo_github_url = ""
164
  except Exception as exc:
165
  st.session_state.last_error = str(exc)
166
  return
 
244
  st.caption(f"Could not generate PDF report: {exc}")
245
 
246
 
247
+ def _render_zip_download(values: dict[str, Any], key_suffix: str) -> None:
248
+ ws_root = values.get("workspace_root")
249
+ if not ws_root:
250
+ return
251
+ try:
252
+ zip_bytes = Workspace.open(ws_root).export_zip_bytes()
253
+ st.download_button(
254
+ "πŸ“¦ Download Fixed Repo (.zip)",
255
+ data=zip_bytes,
256
+ file_name="fixed-repository.zip",
257
+ mime="application/zip",
258
+ key=f"zip-{key_suffix}",
259
+ use_container_width=True,
260
+ )
261
+ except Exception as exc: # noqa: BLE001
262
+ st.caption(f"Could not export repository zip: {exc}")
263
+
264
+
265
  def render_approval(payload: dict[str, Any], values: dict[str, Any]) -> None:
266
  st.subheader("⏸️ Waiting for your approval")
267
  st.caption(
 
275
  with st.expander("Reproduction test"):
276
  st.code(payload["repro_test"], language="python")
277
 
278
+ dl1, dl2 = st.columns(2)
279
+ with dl1:
280
+ _render_report_download(values, key_suffix=f"approval-{payload['iteration']}")
281
+ with dl2:
282
+ _render_zip_download(values, key_suffix=f"approval-{payload['iteration']}")
283
 
284
  feedback = st.text_area(
285
  "Feedback for the agent (required to request changes)",
 
313
  note = "Demo commit" if is_demo else "Approved commit"
314
  st.success(
315
  f"{note} `{values['commit_sha']}` on `{values['branch']}` "
316
+ "(download the fixed repository `.zip`, unified `.patch`, or PDF report below, "
317
+ "or push a Pull Request directly to GitHub)."
318
  )
319
  attempts: list[FixAttempt] = values["attempts"]
320
  patch = "\n".join(p.unified_diff for p in attempts[-1].patches)
 
323
  patch = Workspace.open(values["workspace_root"]).full_diff() or patch
324
  except Exception: # noqa: BLE001
325
  pass
326
+ col1, col2, col3 = st.columns(3)
327
  with col1:
328
  st.download_button(
329
  "⬇️ Download patch (.patch)",
 
332
  use_container_width=True,
333
  )
334
  with col2:
335
+ _render_zip_download(values, key_suffix="committed")
336
+ with col3:
337
  _render_report_download(values, key_suffix="committed")
338
+
339
+ # One-click GitHub Pull Request creation (for live runs)
340
+ if not is_demo and values.get("workspace_root"):
341
+ with st.expander("πŸš€ Push Branch & Open GitHub Pull Request", expanded=bool(st.session_state.get("repo_github_url"))):
342
+ default_gh_url = st.session_state.get("repo_github_url") or (values.get("issue").url if values.get("issue") else "") or ""
343
+ gh_url = st.text_input(
344
+ "Target GitHub Repository URL",
345
+ value=default_gh_url,
346
+ placeholder="https://github.com/owner/repo",
347
+ key="pr-repo-url",
348
+ )
349
+ gh_token = st.text_input(
350
+ "GitHub Personal Access Token (`repo` scope β€” session-only, never stored)",
351
+ value=os.environ.get("GITHUB_TOKEN", ""),
352
+ type="password",
353
+ placeholder="ghp_... or github_pat_...",
354
+ key="pr-gh-token",
355
+ )
356
+ if st.button("πŸš€ Create Branch & Open Pull Request on GitHub", type="primary"):
357
+ if not parse_github_owner_repo(gh_url):
358
+ st.error("Please enter a valid GitHub repository URL (`https://github.com/owner/repo`).")
359
+ elif not gh_token.strip():
360
+ st.error("Please enter a GitHub Personal Access Token with write access to the repository.")
361
+ else:
362
+ try:
363
+ with st.spinner("Creating branch, committing files, and opening Pull Request..."):
364
+ ws = Workspace.open(values["workspace_root"])
365
+ issue_obj = values["issue"]
366
+ pr_res = create_github_pull_request(
367
+ ws,
368
+ repo_url=gh_url,
369
+ github_token=gh_token,
370
+ issue_title=issue_obj.title,
371
+ issue_body=issue_obj.body,
372
+ rationale=attempts[-1].rationale,
373
+ )
374
+ st.success(f"πŸŽ‰ Pull Request opened on `{pr_res.branch}`: {pr_res.pr_url}")
375
+ if pr_res.pr_url:
376
+ st.link_button("πŸ”— View Pull Request on GitHub", pr_res.pr_url)
377
+ except GitError as exc:
378
+ st.error(f"GitHub PR error: {exc}")
379
  elif status == "escalated":
380
  st.error(f"Escalated: {values.get('error')}")
381
  _render_report_download(values, key_suffix="escalated")
tests/unit/test_routing.py CHANGED
@@ -176,10 +176,24 @@ def test_workspace_jails_paths_and_applies_edits():
176
 
177
  ws.reset()
178
  assert ws.diff("calc.py") == ""
 
 
 
179
  finally:
180
  ws.cleanup()
181
 
182
 
 
 
 
 
 
 
 
 
 
 
 
183
  def test_create_repo_from_uploads_handles_zip_and_rejects_zip_slip():
184
  import io
185
  import shutil
 
176
 
177
  ws.reset()
178
  assert ws.diff("calc.py") == ""
179
+
180
+ zip_bytes = ws.export_zip_bytes()
181
+ assert len(zip_bytes) > 100
182
  finally:
183
  ws.cleanup()
184
 
185
 
186
+ def test_parse_github_owner_repo():
187
+ from tools.git_tools import parse_github_owner_repo
188
+
189
+ assert parse_github_owner_repo("https://github.com/farazmalik180/SwiftSupport-Commerce.git") == (
190
+ "farazmalik180",
191
+ "SwiftSupport-Commerce",
192
+ )
193
+ assert parse_github_owner_repo("https://github.com/owner/repo") == ("owner", "repo")
194
+ assert parse_github_owner_repo("not-a-url") is None
195
+
196
+
197
  def test_create_repo_from_uploads_handles_zip_and_rejects_zip_slip():
198
  import io
199
  import shutil