pr-forge-ai 0.3.0__tar.gz

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.
Files changed (32) hide show
  1. pr_forge_ai-0.3.0/PKG-INFO +173 -0
  2. pr_forge_ai-0.3.0/README.md +149 -0
  3. pr_forge_ai-0.3.0/pr_forge/__init__.py +7 -0
  4. pr_forge_ai-0.3.0/pr_forge/agent.py +356 -0
  5. pr_forge_ai-0.3.0/pr_forge/cli.py +225 -0
  6. pr_forge_ai-0.3.0/pr_forge/config.py +80 -0
  7. pr_forge_ai-0.3.0/pr_forge/context_optimizer.py +132 -0
  8. pr_forge_ai-0.3.0/pr_forge/figma.py +152 -0
  9. pr_forge_ai-0.3.0/pr_forge/git_ops.py +83 -0
  10. pr_forge_ai-0.3.0/pr_forge/llm.py +221 -0
  11. pr_forge_ai-0.3.0/pr_forge/pr_parser.py +268 -0
  12. pr_forge_ai-0.3.0/pr_forge/runner.py +111 -0
  13. pr_forge_ai-0.3.0/pr_forge/skill_loader.py +216 -0
  14. pr_forge_ai-0.3.0/pr_forge/skills/apple-frameworks.md +14 -0
  15. pr_forge_ai-0.3.0/pr_forge/skills/pr-token-efficiency.md +6 -0
  16. pr_forge_ai-0.3.0/pr_forge/skills/swift-concise.md +19 -0
  17. pr_forge_ai-0.3.0/pr_forge/skills/swiftui-27.md +33 -0
  18. pr_forge_ai-0.3.0/pr_forge/skills/uikit-modern.md +20 -0
  19. pr_forge_ai-0.3.0/pr_forge_ai.egg-info/PKG-INFO +173 -0
  20. pr_forge_ai-0.3.0/pr_forge_ai.egg-info/SOURCES.txt +30 -0
  21. pr_forge_ai-0.3.0/pr_forge_ai.egg-info/dependency_links.txt +1 -0
  22. pr_forge_ai-0.3.0/pr_forge_ai.egg-info/entry_points.txt +2 -0
  23. pr_forge_ai-0.3.0/pr_forge_ai.egg-info/requires.txt +5 -0
  24. pr_forge_ai-0.3.0/pr_forge_ai.egg-info/top_level.txt +1 -0
  25. pr_forge_ai-0.3.0/pyproject.toml +54 -0
  26. pr_forge_ai-0.3.0/setup.cfg +4 -0
  27. pr_forge_ai-0.3.0/tests/test_agent_loop.py +97 -0
  28. pr_forge_ai-0.3.0/tests/test_context_optimizer.py +32 -0
  29. pr_forge_ai-0.3.0/tests/test_figma.py +47 -0
  30. pr_forge_ai-0.3.0/tests/test_pr_parser.py +42 -0
  31. pr_forge_ai-0.3.0/tests/test_runner.py +16 -0
  32. pr_forge_ai-0.3.0/tests/test_skill_loader.py +35 -0
@@ -0,0 +1,173 @@
1
+ Metadata-Version: 2.4
2
+ Name: pr-forge-ai
3
+ Version: 0.3.0
4
+ Summary: Token-efficient PR-to-Production autonomous agent with Xcode 27 iOS skills and Zero-Bloat Swift.
5
+ Author: Shubhransh Gupta
6
+ License-Expression: MIT
7
+ Keywords: github-action,pr-agent,ios,swift,swiftui,uikit,xcode-27,swift-6,ai-agent,figma
8
+ Classifier: Development Status :: 4 - Beta
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.10
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Classifier: Programming Language :: Python :: 3.14
16
+ Classifier: Topic :: Software Development :: Code Generators
17
+ Classifier: Topic :: Software Development :: Build Tools
18
+ Requires-Python: >=3.10
19
+ Description-Content-Type: text/markdown
20
+ Requires-Dist: requests>=2.31.0
21
+ Requires-Dist: rich>=13.7.0
22
+ Provides-Extra: dev
23
+ Requires-Dist: pytest>=8.0.0; extra == "dev"
24
+
25
+ # ⚡ PR Forge (`pr-forge-ai`)
26
+
27
+ [![GitHub Release](https://img.shields.io/github/v/release/shubhransh-gupta/pr-forge?style=for-the-badge&color=38bdf8)](https://github.com/shubhransh-gupta/pr-forge/releases)
28
+ [![GitHub Marketplace](https://img.shields.io/badge/Marketplace-PR%20Forge%20%40v1-818cf8?style=for-the-badge&logo=githubactions&logoColor=white)](https://github.com/shubhransh-gupta/pr-forge)
29
+ [![PyPI](https://img.shields.io/pypi/v/pr-forge-ai?style=for-the-badge&color=3775A9&logo=pypi&logoColor=white)](https://pypi.org/project/pr-forge-ai/)
30
+ [![Homebrew](https://img.shields.io/badge/Homebrew-shubhransh--gupta%2Ftap-FBB040?style=for-the-badge&logo=homebrew&logoColor=black)](https://github.com/shubhransh-gupta/homebrew-tap)
31
+ [![Xcode 27](https://img.shields.io/badge/Xcode%2027-SwiftUI%20%2B%20UIKit-0A84FF?style=for-the-badge&logo=apple&logoColor=white)](https://developer.apple.com)
32
+ [![GitHub Stars](https://img.shields.io/github/stars/shubhransh-gupta/pr-forge?style=for-the-badge&color=30d158)](https://github.com/shubhransh-gupta/pr-forge/stargazers)
33
+ [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg?style=for-the-badge)](https://opensource.org/licenses/MIT)
34
+
35
+ **Token-efficient PR-to-Production autonomous agent** built for **iOS / Swift (Xcode 27)** and multi-language repositories — combining **PR Templates + PRDs + Figma + Custom Skills**, **Zero-Bloat 1-line Swift optimization**, and a **self-auditing verify-and-reiterate loop**.
36
+
37
+ <p align="center">
38
+ <img src="assets/demo.svg" alt="PR Forge Live Terminal & Zero-Bloat Swift Demo" width="100%" />
39
+ </p>
40
+
41
+ > If PR Forge saves you tokens or ships cleaner SwiftUI/UIKit PRs, please consider giving it a **Star** — it helps more iOS engineers discover it!
42
+
43
+ ---
44
+
45
+ ## Why iOS & Full-Stack Teams Use PR Forge
46
+
47
+ | Feature | What PR Forge Does |
48
+ | :--- | :--- |
49
+ | **PR-Native Inputs** | Parses `## Template`, `## PRD` (`- [ ]` acceptance criteria), `## Figma` (URL/node-id/tokens), and `## Additional Skills` from any PR |
50
+ | **Token Efficiency** | **Progressive Skill Loading** + **Symbol-Map Planning** + **Figma Vector Pruning** + **O(1) Rolling Iteration Ledger** |
51
+ | **Verify & Reiterate Loop** | Runs `swift test` / `xcodebuild` / `pytest` / `npm test`, audits the `git diff` against every PRD checkbox, and loops until 100% complete |
52
+ | **Zero-Bloat Swift** | Replaces 10-line imperative loops & wrapper bloat with 1-line Swift stdlib higher-order functions & high-level Apple APIs |
53
+ | **Xcode 27 / SDK 27 Skills** | Built-in SwiftUI 27, UIKit Modernization, Liquid Glass, FoundationModels, SwiftData Inheritance, Swift 6.2 Concurrency, and more |
54
+ | **Universal LLM Support** | Works with **Gemini**, **Claude**, **OpenAI**, **DeepSeek**, **OpenRouter**, **NVIDIA**, or local **Ollama** |
55
+
56
+ ---
57
+
58
+ ## Zero-Bloat Swift: 10 Lines → 1 Line
59
+
60
+ Instead of generating verbose loops and redundant service wrappers, PR Forge writes idiomatic, senior-level Swift:
61
+
62
+ ```swift
63
+ // ❌ Bloated imperative code (10+ lines)
64
+ var activeByCategory: [Category: [Workout]] = [:]
65
+ for item in workouts {
66
+ if item.isActive {
67
+ activeByCategory[item.category, default: []].append(item)
68
+ }
69
+ }
70
+
71
+ // ✅ Concise Swift generated by PR Forge (1 line)
72
+ let activeByCategory = Dictionary(grouping: workouts.filter(\.isActive), by: \.category)
73
+ ```
74
+
75
+ ---
76
+
77
+ ## Built-In Xcode 27 & iOS Skill Matrix
78
+
79
+ | Skill Module | Coverage |
80
+ | :--- | :--- |
81
+ | `swift-concise` | Zero-bloat decision ladder, `map`/`compactMap`/`Dictionary(grouping:by:)`, `KeyPathComparator`, `async let`, `@Observable` |
82
+ | `swiftui-27` | `@State` macro migration rules, `@ContentBuilder`, `.reorderable()`, `swipeActionsContainer()`, `ToolbarOverflowMenu`, `alert(item:)`, `AsyncImage(request:)`, Liquid Glass `.glassEffect()`, `WebView`/`WebPage`, `AlarmKit` |
83
+ | `uikit-modern` | `traitCollection.displayScale` + `registerForTraitChanges`, `view.bounds`, `SceneDelegate`, `safeAreaLayoutGuide`, `UIGlassEffect` / `UIGlassContainerEffect` |
84
+ | `apple-frameworks` | `FoundationModels` (`LanguageModelSession`, `@Generable`), `SwiftData` class inheritance, Swift 6.2 concurrency, `InlineArray` & `Span`, `AppIntents`, `StoreKit`, `Chart3D`, `GeoToolbox`, `WidgetKit` / visionOS |
85
+ | `pr-token-efficiency` | Symbol-map planning, minimal diffs, O(1) rolling ledger |
86
+
87
+ ---
88
+
89
+ ## Installation
90
+
91
+ ### 1. Homebrew (macOS / Linux)
92
+ ```bash
93
+ brew tap shubhransh-gupta/tap
94
+ brew install pr-forge
95
+ ```
96
+
97
+ ### 2. PyPI (`pip`)
98
+ ```bash
99
+ pip install pr-forge-ai
100
+ ```
101
+
102
+ ### 3. GitHub Marketplace Action (`.github/workflows/pr-forge.yml`)
103
+ Run `pr-forge init-pr-template --repo .` or paste:
104
+
105
+ ```yaml
106
+ name: PR Forge Autonomous Implementation
107
+
108
+ on:
109
+ pull_request:
110
+ types: [opened, synchronize, labeled]
111
+ issue_comment:
112
+ types: [created]
113
+
114
+ jobs:
115
+ forge:
116
+ if: |
117
+ (github.event_name == 'issue_comment' && github.event.issue.pull_request && contains(github.event.comment.body, '/forge')) ||
118
+ (github.event_name == 'pull_request' && contains(github.event.pull_request.labels.*.name, 'pr-forge'))
119
+ runs-on: macos-latest
120
+ permissions:
121
+ contents: write
122
+ pull-requests: write
123
+ steps:
124
+ - uses: actions/checkout@v4
125
+ with:
126
+ fetch-depth: 0
127
+ - uses: shubhransh-gupta/pr-forge@v1
128
+ with:
129
+ api-key: ${{ secrets.GEMINI_API_KEY }}
130
+ figma-token: ${{ secrets.FIGMA_TOKEN }}
131
+ github-token: ${{ secrets.GITHUB_TOKEN }}
132
+ provider: gemini
133
+ max-iterations: '6'
134
+ auto-commit: 'true'
135
+ post-comment: 'true'
136
+ ```
137
+
138
+ ### 4. As an AI Agent Skill (`SKILL.md`)
139
+ Install [SKILL.md](SKILL.md) + `pr_forge/skills/` into Antigravity, Claude Code, or Cursor.
140
+
141
+ ---
142
+
143
+ ## CLI Quick Start
144
+
145
+ ```bash
146
+ export GEMINI_API_KEY="..."
147
+ export FIGMA_TOKEN="..." # optional, for live Figma node extraction
148
+
149
+ # Verify environment, Xcode 27 docs, and keys
150
+ pr-forge doctor
151
+
152
+ # List bundled Xcode 27 + Zero-Bloat Swift skills
153
+ pr-forge skills
154
+
155
+ # Bootstrap PR template + GitHub workflow in any repo
156
+ pr-forge init-pr-template --repo .
157
+
158
+ # Implement from a local PR spec markdown file
159
+ pr-forge run --repo . --pr-file pr_spec.md --max-iterations 6
160
+
161
+ # Implement directly from a live GitHub PR
162
+ pr-forge pr 1 --gh-repo shubhransh-gupta/xib-to-swiftui --repo . --auto-commit --post-comment
163
+ ```
164
+
165
+ ---
166
+
167
+ ## Example Showcase Built with PR Forge
168
+ - **[XibToSwiftUI](https://github.com/shubhransh-gupta/xib-to-swiftui)** — Native macOS Xcode app that extracts uploaded `.zip` / `.xib` files and generates SwiftUI views head-to-head ([PR #1](https://github.com/shubhransh-gupta/xib-to-swiftui/pull/1)).
169
+
170
+ ---
171
+
172
+ ## License
173
+ MIT — Contributions, issues, and ⭐ stars are welcome!
@@ -0,0 +1,149 @@
1
+ # ⚡ PR Forge (`pr-forge-ai`)
2
+
3
+ [![GitHub Release](https://img.shields.io/github/v/release/shubhransh-gupta/pr-forge?style=for-the-badge&color=38bdf8)](https://github.com/shubhransh-gupta/pr-forge/releases)
4
+ [![GitHub Marketplace](https://img.shields.io/badge/Marketplace-PR%20Forge%20%40v1-818cf8?style=for-the-badge&logo=githubactions&logoColor=white)](https://github.com/shubhransh-gupta/pr-forge)
5
+ [![PyPI](https://img.shields.io/pypi/v/pr-forge-ai?style=for-the-badge&color=3775A9&logo=pypi&logoColor=white)](https://pypi.org/project/pr-forge-ai/)
6
+ [![Homebrew](https://img.shields.io/badge/Homebrew-shubhransh--gupta%2Ftap-FBB040?style=for-the-badge&logo=homebrew&logoColor=black)](https://github.com/shubhransh-gupta/homebrew-tap)
7
+ [![Xcode 27](https://img.shields.io/badge/Xcode%2027-SwiftUI%20%2B%20UIKit-0A84FF?style=for-the-badge&logo=apple&logoColor=white)](https://developer.apple.com)
8
+ [![GitHub Stars](https://img.shields.io/github/stars/shubhransh-gupta/pr-forge?style=for-the-badge&color=30d158)](https://github.com/shubhransh-gupta/pr-forge/stargazers)
9
+ [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg?style=for-the-badge)](https://opensource.org/licenses/MIT)
10
+
11
+ **Token-efficient PR-to-Production autonomous agent** built for **iOS / Swift (Xcode 27)** and multi-language repositories — combining **PR Templates + PRDs + Figma + Custom Skills**, **Zero-Bloat 1-line Swift optimization**, and a **self-auditing verify-and-reiterate loop**.
12
+
13
+ <p align="center">
14
+ <img src="assets/demo.svg" alt="PR Forge Live Terminal & Zero-Bloat Swift Demo" width="100%" />
15
+ </p>
16
+
17
+ > If PR Forge saves you tokens or ships cleaner SwiftUI/UIKit PRs, please consider giving it a **Star** — it helps more iOS engineers discover it!
18
+
19
+ ---
20
+
21
+ ## Why iOS & Full-Stack Teams Use PR Forge
22
+
23
+ | Feature | What PR Forge Does |
24
+ | :--- | :--- |
25
+ | **PR-Native Inputs** | Parses `## Template`, `## PRD` (`- [ ]` acceptance criteria), `## Figma` (URL/node-id/tokens), and `## Additional Skills` from any PR |
26
+ | **Token Efficiency** | **Progressive Skill Loading** + **Symbol-Map Planning** + **Figma Vector Pruning** + **O(1) Rolling Iteration Ledger** |
27
+ | **Verify & Reiterate Loop** | Runs `swift test` / `xcodebuild` / `pytest` / `npm test`, audits the `git diff` against every PRD checkbox, and loops until 100% complete |
28
+ | **Zero-Bloat Swift** | Replaces 10-line imperative loops & wrapper bloat with 1-line Swift stdlib higher-order functions & high-level Apple APIs |
29
+ | **Xcode 27 / SDK 27 Skills** | Built-in SwiftUI 27, UIKit Modernization, Liquid Glass, FoundationModels, SwiftData Inheritance, Swift 6.2 Concurrency, and more |
30
+ | **Universal LLM Support** | Works with **Gemini**, **Claude**, **OpenAI**, **DeepSeek**, **OpenRouter**, **NVIDIA**, or local **Ollama** |
31
+
32
+ ---
33
+
34
+ ## Zero-Bloat Swift: 10 Lines → 1 Line
35
+
36
+ Instead of generating verbose loops and redundant service wrappers, PR Forge writes idiomatic, senior-level Swift:
37
+
38
+ ```swift
39
+ // ❌ Bloated imperative code (10+ lines)
40
+ var activeByCategory: [Category: [Workout]] = [:]
41
+ for item in workouts {
42
+ if item.isActive {
43
+ activeByCategory[item.category, default: []].append(item)
44
+ }
45
+ }
46
+
47
+ // ✅ Concise Swift generated by PR Forge (1 line)
48
+ let activeByCategory = Dictionary(grouping: workouts.filter(\.isActive), by: \.category)
49
+ ```
50
+
51
+ ---
52
+
53
+ ## Built-In Xcode 27 & iOS Skill Matrix
54
+
55
+ | Skill Module | Coverage |
56
+ | :--- | :--- |
57
+ | `swift-concise` | Zero-bloat decision ladder, `map`/`compactMap`/`Dictionary(grouping:by:)`, `KeyPathComparator`, `async let`, `@Observable` |
58
+ | `swiftui-27` | `@State` macro migration rules, `@ContentBuilder`, `.reorderable()`, `swipeActionsContainer()`, `ToolbarOverflowMenu`, `alert(item:)`, `AsyncImage(request:)`, Liquid Glass `.glassEffect()`, `WebView`/`WebPage`, `AlarmKit` |
59
+ | `uikit-modern` | `traitCollection.displayScale` + `registerForTraitChanges`, `view.bounds`, `SceneDelegate`, `safeAreaLayoutGuide`, `UIGlassEffect` / `UIGlassContainerEffect` |
60
+ | `apple-frameworks` | `FoundationModels` (`LanguageModelSession`, `@Generable`), `SwiftData` class inheritance, Swift 6.2 concurrency, `InlineArray` & `Span`, `AppIntents`, `StoreKit`, `Chart3D`, `GeoToolbox`, `WidgetKit` / visionOS |
61
+ | `pr-token-efficiency` | Symbol-map planning, minimal diffs, O(1) rolling ledger |
62
+
63
+ ---
64
+
65
+ ## Installation
66
+
67
+ ### 1. Homebrew (macOS / Linux)
68
+ ```bash
69
+ brew tap shubhransh-gupta/tap
70
+ brew install pr-forge
71
+ ```
72
+
73
+ ### 2. PyPI (`pip`)
74
+ ```bash
75
+ pip install pr-forge-ai
76
+ ```
77
+
78
+ ### 3. GitHub Marketplace Action (`.github/workflows/pr-forge.yml`)
79
+ Run `pr-forge init-pr-template --repo .` or paste:
80
+
81
+ ```yaml
82
+ name: PR Forge Autonomous Implementation
83
+
84
+ on:
85
+ pull_request:
86
+ types: [opened, synchronize, labeled]
87
+ issue_comment:
88
+ types: [created]
89
+
90
+ jobs:
91
+ forge:
92
+ if: |
93
+ (github.event_name == 'issue_comment' && github.event.issue.pull_request && contains(github.event.comment.body, '/forge')) ||
94
+ (github.event_name == 'pull_request' && contains(github.event.pull_request.labels.*.name, 'pr-forge'))
95
+ runs-on: macos-latest
96
+ permissions:
97
+ contents: write
98
+ pull-requests: write
99
+ steps:
100
+ - uses: actions/checkout@v4
101
+ with:
102
+ fetch-depth: 0
103
+ - uses: shubhransh-gupta/pr-forge@v1
104
+ with:
105
+ api-key: ${{ secrets.GEMINI_API_KEY }}
106
+ figma-token: ${{ secrets.FIGMA_TOKEN }}
107
+ github-token: ${{ secrets.GITHUB_TOKEN }}
108
+ provider: gemini
109
+ max-iterations: '6'
110
+ auto-commit: 'true'
111
+ post-comment: 'true'
112
+ ```
113
+
114
+ ### 4. As an AI Agent Skill (`SKILL.md`)
115
+ Install [SKILL.md](SKILL.md) + `pr_forge/skills/` into Antigravity, Claude Code, or Cursor.
116
+
117
+ ---
118
+
119
+ ## CLI Quick Start
120
+
121
+ ```bash
122
+ export GEMINI_API_KEY="..."
123
+ export FIGMA_TOKEN="..." # optional, for live Figma node extraction
124
+
125
+ # Verify environment, Xcode 27 docs, and keys
126
+ pr-forge doctor
127
+
128
+ # List bundled Xcode 27 + Zero-Bloat Swift skills
129
+ pr-forge skills
130
+
131
+ # Bootstrap PR template + GitHub workflow in any repo
132
+ pr-forge init-pr-template --repo .
133
+
134
+ # Implement from a local PR spec markdown file
135
+ pr-forge run --repo . --pr-file pr_spec.md --max-iterations 6
136
+
137
+ # Implement directly from a live GitHub PR
138
+ pr-forge pr 1 --gh-repo shubhransh-gupta/xib-to-swiftui --repo . --auto-commit --post-comment
139
+ ```
140
+
141
+ ---
142
+
143
+ ## Example Showcase Built with PR Forge
144
+ - **[XibToSwiftUI](https://github.com/shubhransh-gupta/xib-to-swiftui)** — Native macOS Xcode app that extracts uploaded `.zip` / `.xib` files and generates SwiftUI views head-to-head ([PR #1](https://github.com/shubhransh-gupta/xib-to-swiftui/pull/1)).
145
+
146
+ ---
147
+
148
+ ## License
149
+ MIT — Contributions, issues, and ⭐ stars are welcome!
@@ -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__"]
@@ -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)