pr-forge-ai 0.3.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.
pr_forge/__init__.py ADDED
@@ -0,0 +1,7 @@
1
+ """
2
+ PR Forge — Token-efficient PR-to-Production autonomous development agent
3
+ with Xcode 27 iOS skills and Zero-Bloat Swift optimization.
4
+ """
5
+
6
+ __version__ = "0.3.0"
7
+ __all__ = ["__version__"]
pr_forge/agent.py ADDED
@@ -0,0 +1,356 @@
1
+ """
2
+ Autonomous PR-to-Production agent with progressive skills, Figma pruning,
3
+ Zero-Bloat Swift optimization, and iterative verify-and-reiterate loop.
4
+ """
5
+
6
+ from dataclasses import dataclass, field
7
+ import json
8
+ import os
9
+ from pathlib import Path
10
+ import re
11
+ from typing import Any, Callable, Dict, List, Optional
12
+
13
+ from .config import ForgeConfig
14
+ from .context_optimizer import (
15
+ IterationLedger,
16
+ build_symbol_map,
17
+ collect_repo_files,
18
+ read_targeted_files,
19
+ )
20
+ from .figma import resolve_figma_context
21
+ from .git_ops import GitRepo, post_pr_comment
22
+ from .llm import UnifiedLLM
23
+ from .pr_parser import PRContext, parse_pr_markdown
24
+ from .runner import BuildTestRunner
25
+ from .skill_loader import load_progressive_skills
26
+
27
+
28
+ @dataclass
29
+ class ForgeResult:
30
+ success: bool
31
+ iterations: int
32
+ modified_files: List[str]
33
+ requirements_done: int
34
+ requirements_total: int
35
+ build_command: str
36
+ build_passed: bool
37
+ token_usage: Dict[str, int]
38
+ skills_loaded: List[str]
39
+ skill_tokens_saved: int
40
+ report_markdown: str
41
+ branch: Optional[str] = None
42
+ extra: Dict[str, Any] = field(default_factory=dict)
43
+
44
+
45
+ def _extract_json_object(text: str) -> Dict[str, Any]:
46
+ """Extract the first valid JSON object from an LLM response (fenced or raw)."""
47
+ fenced = re.search(r"```(?:json)?\s*(\{.*?\})\s*```", text, re.DOTALL)
48
+ candidates = [fenced.group(1)] if fenced else []
49
+ raw_match = re.search(r"\{.*\}", text, re.DOTALL)
50
+ if raw_match:
51
+ candidates.append(raw_match.group(0))
52
+ for cand in candidates:
53
+ try:
54
+ parsed = json.loads(cand)
55
+ if isinstance(parsed, dict):
56
+ return parsed
57
+ except json.JSONDecodeError:
58
+ continue
59
+ return {}
60
+
61
+
62
+ class PRForgeAgent:
63
+ """Implements PR specs end-to-end in a token-efficient verify-and-reiterate loop."""
64
+
65
+ def __init__(
66
+ self,
67
+ config: Optional[ForgeConfig] = None,
68
+ llm: Optional[UnifiedLLM] = None,
69
+ runner: Optional[BuildTestRunner] = None,
70
+ ):
71
+ self.config = config or ForgeConfig()
72
+ if llm is None:
73
+ self.config.validate()
74
+ self.repo_dir = self.config.target_repo_dir.resolve()
75
+ self.git = GitRepo(self.repo_dir)
76
+ self.runner = runner or BuildTestRunner(
77
+ repo_dir=self.repo_dir,
78
+ custom_cmd=self.config.test_command,
79
+ timeout=self.config.timeout_per_run,
80
+ )
81
+ self.llm = llm or UnifiedLLM(
82
+ provider=self.config.provider,
83
+ model=self.config.model,
84
+ api_key=self.config.api_key,
85
+ base_url=self.config.base_url,
86
+ timeout=self.config.timeout_per_run,
87
+ )
88
+
89
+ def _safe_write_files(self, file_map: Dict[str, str]) -> List[str]:
90
+ written: List[str] = []
91
+ root = self.repo_dir.resolve()
92
+ for rel_path, content in file_map.items():
93
+ if not isinstance(rel_path, str) or not isinstance(content, str):
94
+ continue
95
+ target = (root / rel_path).resolve()
96
+ try:
97
+ target.relative_to(root)
98
+ except ValueError:
99
+ continue
100
+ target.parent.mkdir(parents=True, exist_ok=True)
101
+ target.write_text(content, encoding="utf-8")
102
+ written.append(rel_path)
103
+ return written
104
+
105
+ def _select_target_files(
106
+ self,
107
+ pr_ctx: PRContext,
108
+ symbol_map: str,
109
+ system_prompt: str,
110
+ ) -> List[str]:
111
+ prompt = (
112
+ "Select existing files to inspect (and/or note up to 5 paths) before implementing this PR.\n"
113
+ "Return ONLY a JSON array of relative file paths (max 8).\n\n"
114
+ f"PR Title: {pr_ctx.title}\n"
115
+ f"PRD:\n{pr_ctx.prd[:2500]}\n\n"
116
+ f"Changed files hint: {json.dumps(pr_ctx.changed_files_hint)}\n\n"
117
+ f"Repository Symbol Map:\n{symbol_map}"
118
+ )
119
+ resp = self.llm.generate(prompt, system_instruction=system_prompt)
120
+ match = re.search(r"\[.*?\]", resp, re.DOTALL)
121
+ if match:
122
+ try:
123
+ paths = json.loads(match.group(0))
124
+ if isinstance(paths, list):
125
+ return [str(p) for p in paths[:8]]
126
+ except json.JSONDecodeError:
127
+ pass
128
+ return pr_ctx.changed_files_hint[:6]
129
+
130
+ def _audit_iteration(
131
+ self,
132
+ pr_ctx: PRContext,
133
+ diff_text: str,
134
+ build_passed: bool,
135
+ build_output: str,
136
+ system_prompt: str,
137
+ ) -> Dict[str, Any]:
138
+ req_lines = "\n".join(f"- {r.id}: {r.text}" for r in pr_ctx.requirements)
139
+ prompt = (
140
+ "Audit the current implementation against EVERY PRD requirement, template rule, Figma spec, "
141
+ "active skills, and Zero-Bloat conciseness (replace bloated imperative loops with higher-order "
142
+ "functions / high-level Apple APIs where applicable).\n\n"
143
+ "Return ONLY JSON:\n"
144
+ "{\n"
145
+ ' "complete": true | false,\n'
146
+ ' "requirements": {"REQ-1": true, "REQ-2": false},\n'
147
+ ' "gaps": "concise list of missing features, build fixes, or code simplifications needed"\n'
148
+ "}\n\n"
149
+ f"Requirements:\n{req_lines}\n\n"
150
+ f"Build/Test Passed: {build_passed}\n"
151
+ f"Build/Test Output Tail:\n{build_output[-1500:]}\n\n"
152
+ f"Current Git Diff / Changes:\n{diff_text[:4000]}"
153
+ )
154
+ resp = self.llm.generate(prompt, system_instruction=system_prompt)
155
+ return _extract_json_object(resp)
156
+
157
+ def _build_report(
158
+ self,
159
+ pr_ctx: PRContext,
160
+ ledger: IterationLedger,
161
+ build_cmd: str,
162
+ build_passed: bool,
163
+ skills_loaded: List[str],
164
+ skills_saved: int,
165
+ ) -> str:
166
+ done_n, total_n = pr_ctx.completion_ratio()
167
+ status_badge = "Complete & Verified" if (build_passed and pr_ctx.all_requirements_complete()) else "Needs Attention"
168
+ req_md = "\n".join(
169
+ f"- [{'x' if r.done else ' '}] **{r.id}**: {r.text}"
170
+ for r in pr_ctx.requirements
171
+ )
172
+ files_md = ", ".join(f"`{f}`" for f in sorted(ledger.touched_files)) or "None"
173
+ return (
174
+ f"## PR Forge Summary — {status_badge}\n\n"
175
+ f"- **Iterations**: {ledger.iteration}/{self.config.max_iterations}\n"
176
+ f"- **Requirements**: {done_n}/{total_n} complete\n"
177
+ f"- **Verification (`{build_cmd}`)**: {'PASS' if build_passed else 'FAIL'}\n"
178
+ f"- **Modified Files**: {files_md}\n"
179
+ f"- **Active Skills**: {', '.join(f'`{s}`' for s in skills_loaded)}\n"
180
+ f"- **Tokens Used**: {self.llm.usage.total_tokens} "
181
+ f"(prompt={self.llm.usage.prompt_tokens}, completion={self.llm.usage.completion_tokens}, "
182
+ f"~{skills_saved} skill tokens saved via progressive loading)\n\n"
183
+ f"### PRD Checklist\n{req_md}\n"
184
+ )
185
+
186
+ def run(
187
+ self,
188
+ pr_context: PRContext,
189
+ on_step: Optional[Callable[[str], None]] = None,
190
+ ) -> ForgeResult:
191
+ """Execute the full PR-to-code verify-and-reiterate loop."""
192
+ def log(msg: str) -> None:
193
+ if on_step:
194
+ on_step(msg)
195
+
196
+ repo_files = collect_repo_files(self.repo_dir)
197
+ symbol_map = build_symbol_map(self.repo_dir, repo_files)
198
+ figma_summary = resolve_figma_context(pr_context.figma_specs, self.config.figma_token)
199
+ loaded_skills = load_progressive_skills(
200
+ requested_skills=pr_context.skills,
201
+ prd_text=f"{pr_context.title}\n{pr_context.prd}\n{pr_context.template}",
202
+ repo_files=repo_files,
203
+ repo_dir=self.repo_dir,
204
+ enforce_concise_swift=self.config.enforce_concise_swift,
205
+ )
206
+ log(f"Loaded progressive skills ({', '.join(loaded_skills.selected_names)}); saved ~{loaded_skills.tokens_saved_estimate} tokens.")
207
+
208
+ branch_name: Optional[str] = None
209
+ if self.git.is_git_repo() and self.config.create_branch:
210
+ slug = re.sub(r"[^a-zA-Z0-9_-]", "-", (pr_context.title or "feature").lower())[:28].strip("-") or "feature"
211
+ branch_name = f"{self.config.branch_prefix}-{pr_context.pr_number or slug}"
212
+ self.git.create_and_checkout_branch(branch_name)
213
+ log(f"Checked out branch `{branch_name}`.")
214
+
215
+ system_prompt = (
216
+ "You are PR Forge, an autonomous senior software & iOS/Xcode 27 architect.\n"
217
+ "Follow all active skills strictly. Write minimal, zero-bloat Swift/code: "
218
+ "prefer standard library higher-order functions and high-level native Apple APIs over verbose boilerplate.\n"
219
+ "Keep outputs minimal and token-efficient.\n\n"
220
+ f"{loaded_skills.combined_prompt}"
221
+ )
222
+
223
+ candidate_paths = self._select_target_files(pr_context, symbol_map, system_prompt)
224
+ log(f"Targeted {len(candidate_paths)} files from symbol map.")
225
+
226
+ build_cmd = self.runner.detect_command()
227
+ ledger = IterationLedger()
228
+ build_passed = False
229
+
230
+ while ledger.iteration < self.config.max_iterations:
231
+ ledger.iteration += 1
232
+ log(f"Iteration {ledger.iteration}/{self.config.max_iterations}: implementing & verifying...")
233
+
234
+ files_to_read = list(dict.fromkeys(candidate_paths + sorted(ledger.touched_files)))
235
+ file_contents = read_targeted_files(self.repo_dir, files_to_read)
236
+
237
+ impl_prompt = (
238
+ "Implement or refine the solution for this PR. Only output files you create or modify.\n"
239
+ "Return ONLY valid JSON matching:\n"
240
+ "{\n"
241
+ ' "summary": "short 1-line summary",\n'
242
+ ' "files": {"relative/path.ext": "complete file content"}\n'
243
+ "}\n\n"
244
+ f"PR Title: {pr_context.title}\n"
245
+ f"Template / Architecture:\n{pr_context.template or '(none)'}\n\n"
246
+ f"PRD:\n{pr_context.prd}\n\n"
247
+ f"Figma Spec:\n{figma_summary or '(none)'}\n\n"
248
+ f"Rolling State:\n{ledger.render(pr_context.requirements)}\n\n"
249
+ f"Repository Symbol Map:\n{symbol_map}\n\n"
250
+ f"Targeted File Contents:\n{json.dumps(file_contents, indent=2)}"
251
+ )
252
+ raw_impl = self.llm.generate(impl_prompt, system_instruction=system_prompt)
253
+ parsed_impl = _extract_json_object(raw_impl)
254
+ file_updates = parsed_impl.get("files") or {}
255
+ if isinstance(file_updates, dict) and file_updates:
256
+ written = self._safe_write_files(file_updates)
257
+ ledger.touched_files.update(written)
258
+ log(f"Updated {len(written)} file(s): {', '.join(written)}")
259
+ else:
260
+ log("No file edits parsed in this step; running verification & audit.")
261
+
262
+ # Refresh repo files/symbol map if new files were added
263
+ repo_files = collect_repo_files(self.repo_dir)
264
+ symbol_map = build_symbol_map(self.repo_dir, repo_files)
265
+
266
+ test_res = self.runner.run(build_cmd)
267
+ build_passed = test_res.passed
268
+ ledger.last_build_status = "PASS" if build_passed else f"FAIL (exit {test_res.exit_code})"
269
+ ledger.last_error_tail = "" if build_passed else test_res.output_summary
270
+ log(f"Build/Test `{build_cmd}` -> {ledger.last_build_status}")
271
+
272
+ diff_text = self.git.get_diff() if self.git.is_git_repo() else "\n".join(sorted(ledger.touched_files))
273
+ if not diff_text and ledger.touched_files:
274
+ snap = read_targeted_files(self.repo_dir, sorted(ledger.touched_files), max_chars_per_file=2000)
275
+ diff_text = json.dumps(snap)
276
+
277
+ audit = self._audit_iteration(
278
+ pr_ctx=pr_context,
279
+ diff_text=diff_text,
280
+ build_passed=build_passed,
281
+ build_output=test_res.output_summary,
282
+ system_prompt=system_prompt,
283
+ )
284
+
285
+ req_status = audit.get("requirements") or {}
286
+ if isinstance(req_status, dict):
287
+ for req in pr_context.requirements:
288
+ if req.id in req_status:
289
+ req.done = bool(req_status[req.id])
290
+
291
+ audit_complete = bool(audit.get("complete", False))
292
+ ledger.last_audit_notes = str(audit.get("gaps") or "")
293
+
294
+ done_n, total_n = pr_context.completion_ratio()
295
+ log(f"Self-audit: {done_n}/{total_n} requirements complete; audit_complete={audit_complete}")
296
+
297
+ if build_passed and (pr_context.all_requirements_complete() or (audit_complete and total_n == 0)):
298
+ # Ensure single-requirement fallback marks done if audit_complete is True
299
+ for req in pr_context.requirements:
300
+ req.done = True
301
+ break
302
+
303
+ success = build_passed and pr_context.all_requirements_complete()
304
+ report = self._build_report(
305
+ pr_ctx=pr_context,
306
+ ledger=ledger,
307
+ build_cmd=build_cmd,
308
+ build_passed=build_passed,
309
+ skills_loaded=loaded_skills.selected_names,
310
+ skills_saved=loaded_skills.tokens_saved_estimate,
311
+ )
312
+
313
+ if success and self.config.auto_commit and self.git.is_git_repo():
314
+ self.git.stage_all_and_commit(f"feat(pr-forge): implement {pr_context.title or 'PR specification'}")
315
+
316
+ if self.config.post_pr_comment and pr_context.repo_slug and pr_context.pr_number:
317
+ post_pr_comment(pr_context.repo_slug, pr_context.pr_number, report, self.config.github_token)
318
+
319
+ step_summary = os.getenv("GITHUB_STEP_SUMMARY")
320
+ if step_summary:
321
+ try:
322
+ with open(step_summary, "a", encoding="utf-8") as fh:
323
+ fh.write(report + "\n")
324
+ except OSError:
325
+ pass
326
+
327
+ done_n, total_n = pr_context.completion_ratio()
328
+ return ForgeResult(
329
+ success=success,
330
+ iterations=ledger.iteration,
331
+ modified_files=sorted(ledger.touched_files),
332
+ requirements_done=done_n,
333
+ requirements_total=total_n,
334
+ build_command=build_cmd,
335
+ build_passed=build_passed,
336
+ token_usage={
337
+ "prompt_tokens": self.llm.usage.prompt_tokens,
338
+ "completion_tokens": self.llm.usage.completion_tokens,
339
+ "total_tokens": self.llm.usage.total_tokens,
340
+ "calls": self.llm.usage.calls,
341
+ },
342
+ skills_loaded=loaded_skills.selected_names,
343
+ skill_tokens_saved=loaded_skills.tokens_saved_estimate,
344
+ report_markdown=report,
345
+ branch=branch_name,
346
+ )
347
+
348
+ @classmethod
349
+ def from_markdown(
350
+ cls,
351
+ markdown_text: str,
352
+ title: str = "",
353
+ config: Optional[ForgeConfig] = None,
354
+ ) -> ForgeResult:
355
+ ctx = parse_pr_markdown(body=markdown_text, title=title)
356
+ return cls(config=config).run(ctx)
pr_forge/cli.py ADDED
@@ -0,0 +1,225 @@
1
+ """
2
+ Command-line interface for PR Forge.
3
+ """
4
+
5
+ import argparse
6
+ import os
7
+ from pathlib import Path
8
+ import shutil
9
+ import sys
10
+ from rich.console import Console
11
+ from rich.panel import Panel
12
+ from rich.table import Table
13
+
14
+ from . import __version__
15
+ from .agent import PRForgeAgent
16
+ from .config import ForgeConfig
17
+ from .pr_parser import fetch_github_pr, parse_pr_markdown
18
+ from .skill_loader import XCODE_ADDITIONAL_DOCS_DIR, list_builtin_skills
19
+
20
+
21
+ console = Console()
22
+
23
+ PR_TEMPLATE_CONTENT = """## Template
24
+ <!-- Optional: target architecture, starter pattern, or folder conventions -->
25
+ - SwiftUI / UIKit / @Observable state (zero-bloat, no redundant wrappers)
26
+
27
+ ## PRD
28
+ <!-- Describe what to build and list verifiable acceptance criteria -->
29
+ - [ ] Requirement 1
30
+ - [ ] Requirement 2
31
+
32
+ ## Figma
33
+ <!-- Paste Figma URL (https://www.figma.com/design/...) or inline design tokens -->
34
+
35
+ ## Additional Skills
36
+ <!-- Built-in: ios-xcode27, swiftui-27, uikit-modern, apple-frameworks, swift-concise, or custom .md paths -->
37
+ - ios-xcode27
38
+ - swift-concise
39
+ """
40
+
41
+ WORKFLOW_TEMPLATE_CONTENT = """name: PR Forge Autonomous Implementation
42
+
43
+ on:
44
+ pull_request:
45
+ types: [opened, synchronize, labeled]
46
+ issue_comment:
47
+ types: [created]
48
+
49
+ jobs:
50
+ forge:
51
+ if: |
52
+ (github.event_name == 'issue_comment' && github.event.issue.pull_request && contains(github.event.comment.body, '/forge')) ||
53
+ (github.event_name == 'pull_request' && contains(github.event.pull_request.labels.*.name, 'pr-forge'))
54
+ runs-on: macos-latest
55
+ permissions:
56
+ contents: write
57
+ pull-requests: write
58
+
59
+ steps:
60
+ - uses: actions/checkout@v4
61
+ with:
62
+ fetch-depth: 0
63
+
64
+ - name: Run PR Forge
65
+ uses: shubhransh-gupta/pr-forge@v1
66
+ with:
67
+ api-key: ${{ secrets.GEMINI_API_KEY }}
68
+ figma-token: ${{ secrets.FIGMA_TOKEN }}
69
+ github-token: ${{ secrets.GITHUB_TOKEN }}
70
+ provider: gemini
71
+ max-iterations: '6'
72
+ auto-commit: 'true'
73
+ post-comment: 'true'
74
+ """
75
+
76
+
77
+ def _build_config(args: argparse.Namespace, repo_path: Path) -> ForgeConfig:
78
+ return ForgeConfig(
79
+ provider=args.provider,
80
+ model=args.model,
81
+ api_key=args.api_key,
82
+ base_url=args.base_url,
83
+ figma_token=args.figma_token,
84
+ github_token=args.github_token,
85
+ max_iterations=args.max_iterations,
86
+ test_command=args.test_cmd,
87
+ target_repo_dir=repo_path,
88
+ create_branch=args.create_branch,
89
+ auto_commit=args.auto_commit,
90
+ post_pr_comment=args.post_comment,
91
+ enforce_concise_swift=not args.no_concise_swift,
92
+ )
93
+
94
+
95
+ def _render_result(result) -> None:
96
+ table = Table(title="PR Forge Execution Summary", border_style="cyan")
97
+ table.add_column("Metric", style="cyan")
98
+ table.add_column("Value", style="white")
99
+ table.add_row("Outcome", "[bold green]COMPLETE & VERIFIED[/bold green]" if result.success else "[bold red]INCOMPLETE[/bold red]")
100
+ table.add_row("Iterations", str(result.iterations))
101
+ table.add_row("PRD Checklist", f"{result.requirements_done}/{result.requirements_total}")
102
+ table.add_row("Verification", f"{'PASS' if result.build_passed else 'FAIL'} (`{result.build_command}`)")
103
+ table.add_row("Modified Files", ", ".join(result.modified_files) or "None")
104
+ table.add_row("Active Skills", ", ".join(result.skills_loaded))
105
+ table.add_row(
106
+ "Token Usage",
107
+ f"{result.token_usage['total_tokens']} total (~{result.skill_tokens_saved} skill tokens saved)",
108
+ )
109
+ console.print(table)
110
+
111
+
112
+ def _render_doctor() -> None:
113
+ tbl = Table(title=f"PR Forge v{__version__} Environment Doctor", border_style="cyan")
114
+ tbl.add_column("Check", style="cyan")
115
+ tbl.add_column("Status", style="white")
116
+ llm_keys = [k for k in ("GEMINI_API_KEY", "ANTHROPIC_API_KEY", "OPENAI_API_KEY", "OPENROUTER_API_KEY", "DEEPSEEK_API_KEY") if os.getenv(k)]
117
+ tbl.add_row("LLM API Key", ", ".join(llm_keys) if llm_keys else "[yellow]Not set[/yellow]")
118
+ tbl.add_row("FIGMA_TOKEN", "Set" if os.getenv("FIGMA_TOKEN") else "[dim]Optional (not set)[/dim]")
119
+ tbl.add_row("GitHub CLI (`gh`)", shutil.which("gh") or "[yellow]Not found[/yellow]")
120
+ tbl.add_row("Swift / Xcodebuild", f"swift={bool(shutil.which('swift'))}, xcodebuild={bool(shutil.which('xcodebuild'))}")
121
+ tbl.add_row("Xcode 27 Docs", "Detected" if XCODE_ADDITIONAL_DOCS_DIR.is_dir() else "[dim]Using bundled distilled skills[/dim]")
122
+ console.print(tbl)
123
+
124
+
125
+ def _add_common_agent_flags(parser: argparse.ArgumentParser) -> None:
126
+ parser.add_argument("--repo", "-r", default=".", help="Target repository directory (default: .)")
127
+ parser.add_argument("--provider", "-p", default=None, help="gemini, anthropic, openai, deepseek, openrouter, ollama")
128
+ parser.add_argument("--model", "-m", default=None, help="Model override")
129
+ parser.add_argument("--api-key", "-k", default=None, help="LLM API key override")
130
+ parser.add_argument("--base-url", default=None, help="Custom OpenAI-compatible base URL")
131
+ parser.add_argument("--figma-token", default=None, help="Figma personal access token")
132
+ parser.add_argument("--github-token", default=None, help="GitHub token for PR fetch/comment")
133
+ parser.add_argument("--test-cmd", "-t", default=None, help="Custom build/test command")
134
+ parser.add_argument("--max-iterations", type=int, default=6, help="Max verify-and-reiterate loops (default: 6)")
135
+ parser.add_argument("--create-branch", action="store_true", help="Create a working git branch")
136
+ parser.add_argument("--auto-commit", action="store_true", help="Commit verified changes automatically")
137
+ parser.add_argument("--post-comment", action="store_true", help="Post summary comment back to GitHub PR")
138
+ parser.add_argument("--no-concise-swift", action="store_true", help="Disable automatic Zero-Bloat Swift rule injection")
139
+
140
+
141
+ def main() -> None:
142
+ parser = argparse.ArgumentParser(
143
+ prog="pr-forge",
144
+ description="PR Forge — Token-efficient PR-to-Production agent with Xcode 27 iOS & Zero-Bloat Swift skills.",
145
+ )
146
+ parser.add_argument("--version", action="version", version=f"pr-forge {__version__}")
147
+ sub = parser.add_subparsers(dest="command")
148
+
149
+ run_p = sub.add_parser("run", help="Implement a PR specification from a markdown file or inline PRD")
150
+ run_p.add_argument("--pr-file", "-f", default=None, help="Path to PR markdown file containing Template/PRD/Figma/Skills")
151
+ run_p.add_argument("--prd", default=None, help="Inline PRD / prompt text")
152
+ run_p.add_argument("--title", default="PR Implementation", help="PR title")
153
+ _add_common_agent_flags(run_p)
154
+
155
+ pr_p = sub.add_parser("pr", help="Fetch and implement a live GitHub Pull Request")
156
+ pr_p.add_argument("pr_number", type=int, help="GitHub PR number")
157
+ pr_p.add_argument("--gh-repo", required=True, help="GitHub repository slug (owner/repo)")
158
+ _add_common_agent_flags(pr_p)
159
+
160
+ sub.add_parser("skills", help="List bundled Xcode 27 iOS, Zero-Bloat Swift, and PR efficiency skills")
161
+ sub.add_parser("doctor", help="Check LLM keys, GitHub CLI, Figma token, and Xcode 27 availability")
162
+
163
+ init_p = sub.add_parser("init-pr-template", help="Install PR template & GitHub Action workflow into a repo")
164
+ init_p.add_argument("--repo", "-r", default=".", help="Target repository directory")
165
+
166
+ args = parser.parse_args()
167
+
168
+ if args.command == "doctor":
169
+ _render_doctor()
170
+ return
171
+
172
+ if args.command == "skills":
173
+ tbl = Table(title="Bundled PR Forge Skills", border_style="cyan")
174
+ tbl.add_column("Skill", style="bold cyan")
175
+ tbl.add_column("Focus", style="white")
176
+ for name, desc in list_builtin_skills():
177
+ tbl.add_row(name, desc)
178
+ console.print(tbl)
179
+ return
180
+
181
+ if args.command == "init-pr-template":
182
+ repo_path = Path(args.repo).resolve()
183
+ tpl_path = repo_path / ".github" / "PULL_REQUEST_TEMPLATE.md"
184
+ wf_path = repo_path / ".github" / "workflows" / "pr-forge.yml"
185
+ tpl_path.parent.mkdir(parents=True, exist_ok=True)
186
+ wf_path.parent.mkdir(parents=True, exist_ok=True)
187
+ tpl_path.write_text(PR_TEMPLATE_CONTENT, encoding="utf-8")
188
+ wf_path.write_text(WORKFLOW_TEMPLATE_CONTENT, encoding="utf-8")
189
+ console.print(f"[green]Installed[/green] {tpl_path} and {wf_path}")
190
+ return
191
+
192
+ if args.command not in ("run", "pr"):
193
+ parser.print_help()
194
+ return
195
+
196
+ repo_path = Path(args.repo).resolve()
197
+ config = _build_config(args, repo_path)
198
+ try:
199
+ config.validate()
200
+ except ValueError as exc:
201
+ console.print(Panel(f"[bold red]Configuration Error[/bold red]\n{exc}", border_style="red"))
202
+ sys.exit(1)
203
+
204
+ if args.command == "pr":
205
+ pr_ctx = fetch_github_pr(args.gh_repo, args.pr_number, config.github_token)
206
+ else:
207
+ if args.pr_file:
208
+ body = Path(args.pr_file).read_text(encoding="utf-8")
209
+ elif args.prd:
210
+ body = f"## PRD\n{args.prd}"
211
+ else:
212
+ console.print("[red]Provide --pr-file or --prd.[/red]")
213
+ sys.exit(1)
214
+ pr_ctx = parse_pr_markdown(body=body, title=args.title)
215
+
216
+ agent = PRForgeAgent(config=config)
217
+ with console.status("[bold cyan]PR Forge working...[/bold cyan]", spinner="dots"):
218
+ result = agent.run(pr_ctx, on_step=lambda m: console.print(f" [dim]•[/dim] {m}"))
219
+
220
+ _render_result(result)
221
+ sys.exit(0 if result.success else 1)
222
+
223
+
224
+ if __name__ == "__main__":
225
+ main()
pr_forge/config.py ADDED
@@ -0,0 +1,80 @@
1
+ """
2
+ Configuration for PR Forge supporting multi-provider LLMs, GitHub PRs, Figma, and Xcode 27 skills.
3
+ """
4
+
5
+ import os
6
+ from dataclasses import dataclass, field
7
+ from pathlib import Path
8
+ from typing import Optional
9
+
10
+
11
+ def load_env() -> None:
12
+ """Load nearby .env / .env.local if present without overriding existing env vars."""
13
+ candidates = [
14
+ Path.cwd() / ".env",
15
+ Path.cwd() / ".env.local",
16
+ Path.home() / ".config" / "pr-forge" / ".env",
17
+ ]
18
+ for path in candidates:
19
+ if not path.is_file():
20
+ continue
21
+ try:
22
+ for raw in path.read_text(encoding="utf-8").splitlines():
23
+ line = raw.strip()
24
+ if line and not line.startswith("#") and "=" in line:
25
+ key, val = line.split("=", 1)
26
+ key, val = key.strip(), val.strip().strip("'\"")
27
+ if key and key not in os.environ:
28
+ os.environ[key] = val
29
+ break
30
+ except OSError:
31
+ pass
32
+
33
+
34
+ load_env()
35
+
36
+
37
+ @dataclass
38
+ class ForgeConfig:
39
+ """Runtime settings for a PR Forge run."""
40
+
41
+ provider: Optional[str] = None
42
+ model: Optional[str] = None
43
+ api_key: Optional[str] = None
44
+ base_url: Optional[str] = None
45
+ figma_token: Optional[str] = None
46
+ github_token: Optional[str] = None
47
+ max_iterations: int = 6
48
+ test_command: Optional[str] = None
49
+ timeout_per_run: int = 90
50
+ target_repo_dir: Path = field(default_factory=Path.cwd)
51
+ create_branch: bool = False
52
+ branch_prefix: str = "forge/pr"
53
+ auto_commit: bool = False
54
+ post_pr_comment: bool = False
55
+ token_budget: int = 24000
56
+ enforce_concise_swift: bool = True
57
+
58
+ def __post_init__(self) -> None:
59
+ if not self.figma_token:
60
+ self.figma_token = os.getenv("FIGMA_TOKEN")
61
+ if not self.github_token:
62
+ self.github_token = os.getenv("GITHUB_TOKEN")
63
+
64
+ def validate(self) -> None:
65
+ """Ensure at least one LLM credential or custom base_url is configured."""
66
+ available = [
67
+ self.api_key,
68
+ os.getenv("GEMINI_API_KEY"),
69
+ os.getenv("OPENAI_API_KEY"),
70
+ os.getenv("ANTHROPIC_API_KEY"),
71
+ os.getenv("OPENROUTER_API_KEY"),
72
+ os.getenv("DEEPSEEK_API_KEY"),
73
+ os.getenv("NVIDIA_API_KEY"),
74
+ self.base_url,
75
+ ]
76
+ if not any(available):
77
+ raise ValueError(
78
+ "No LLM API key found. Set GEMINI_API_KEY, OPENAI_API_KEY, ANTHROPIC_API_KEY, "
79
+ "DEEPSEEK_API_KEY, OPENROUTER_API_KEY, or pass --api-key / --base-url."
80
+ )