-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcodejob_state.go
More file actions
243 lines (212 loc) · 7.7 KB
/
codejob_state.go
File metadata and controls
243 lines (212 loc) · 7.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
package devflow
import (
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"strings"
"time"
)
// JulesSessionState polls the Jules API for session status.
// Returns (message, prURL, isDone, error).
func JulesSessionState(sessionID, apiKey string, client HTTPClient) (msg, prURL string, done bool, err error) {
url := fmt.Sprintf("https://jules.googleapis.com/v1alpha/sessions/%s", sessionID)
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return "", "", false, fmt.Errorf("could not create request: %w", err)
}
req.Header.Set("X-Goog-Api-Key", apiKey)
resp, err := client.Do(req)
if err != nil {
return "", "", false, fmt.Errorf("Jules API request failed: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return "", "", false, fmt.Errorf("Jules API returned %d: %s", resp.StatusCode, strings.TrimSpace(string(body)))
}
var session struct {
ID string `json:"id"`
Outputs []struct {
PullRequest struct {
URL string `json:"url"`
Title string `json:"title"`
} `json:"pullRequest"`
} `json:"outputs"`
}
if err := json.NewDecoder(resp.Body).Decode(&session); err != nil {
return "", "", false, fmt.Errorf("could not decode Jules response: %w", err)
}
for _, out := range session.Outputs {
if out.PullRequest.URL != "" {
msg := fmt.Sprintf("✅ Jules: PR ready\n %s\n %s", out.PullRequest.Title, out.PullRequest.URL)
return msg, out.PullRequest.URL, true, nil
}
}
return "⏳ Jules: working...", "", false, nil
}
// HandleDone executes cleanup when Jules completes:
// 1. git fetch --all
// 2. git checkout <jules-branch> for local review
// 3. os.Rename("docs/PLAN.md", "docs/CHECK_PLAN.md")
// 4. env.Delete("CODEJOB")
// 5. env.Set("CODEJOB_PR", prURL)
// 6. Update .gitignore
func HandleDone(env *DotEnv, git *Git, prURL string) error {
// 1. git fetch (non-fatal: state cleanup must proceed regardless)
RunCommandSilent("git", "fetch", "--all") //nolint: ignore fetch failure
// 2. checkout Jules branch for local review (non-fatal)
if prURL != "" {
branchOut, err := RunCommandSilent("gh", "pr", "view", prURL,
"--json", "headRefName", "--jq", ".headRefName")
if err == nil {
if branch := strings.TrimSpace(branchOut); branch != "" {
RunCommandSilent("git", "checkout", branch) //nolint: ignore checkout failure
}
}
}
// 3. rename PLAN.md
planPath := DefaultIssuePromptPath
if _, err := os.Stat(planPath); err == nil {
checkPlanPath := "docs/CHECK_PLAN.md"
if err := os.Rename(planPath, checkPlanPath); err != nil {
return fmt.Errorf("could not rename %s: %w", planPath, err)
}
}
// 4. delete from env
if err := env.Delete("CODEJOB"); err != nil {
return fmt.Errorf("could not update .env: %w", err)
}
// 5. persist PR URL for 'codejob done'
if prURL != "" {
if err := env.Set("CODEJOB_PR", prURL); err != nil {
return fmt.Errorf("could not save CODEJOB_PR: %w", err)
}
}
// 6. .gitignore update
if git != nil {
if err := git.GitIgnoreAdd("CHECK_*.md"); err != nil {
return fmt.Errorf("could not update .gitignore: %w", err)
}
}
return nil
}
// MergePR merges the Jules PR persisted in .env as CODEJOB_PR,
// deletes docs/CHECK_PLAN.md, and cleans up state.
func MergePR() error {
env := NewDotEnv(".env")
prURL, ok := env.Get("CODEJOB_PR")
if !ok || prURL == "" {
return fmt.Errorf("no pending PR found. Run 'codejob' first to check status")
}
// 1. merge PR and delete Jules branch
var out string
var err error
for i := 0; i < 5; i++ {
out, err = RunCommandSilent("gh", "pr", "merge", prURL, "--merge", "--delete-branch")
if err == nil {
break
}
if strings.Contains(out, "is not mergeable") || strings.Contains(err.Error(), "is not mergeable") {
time.Sleep(2 * time.Second)
continue
}
break
}
if err != nil {
return fmt.Errorf("gh pr merge failed: %w\n%s", err, out)
}
// 2. delete docs/CHECK_PLAN.md
if _, err := os.Stat("docs/CHECK_PLAN.md"); err == nil {
if err := os.Remove("docs/CHECK_PLAN.md"); err != nil {
return fmt.Errorf("could not delete CHECK_PLAN.md: %w", err)
}
}
// 3. clean up .env
if err := env.Delete("CODEJOB_PR"); err != nil {
return fmt.Errorf("could not clean up .env: %w", err)
}
return nil
}
// MergeAndPublish merges the Jules PR, pulls the merged commit, commits any
// cleanup files (e.g. .gitignore updated by HandleDone), and publishes via gopush.
func MergeAndPublish(publisher Publisher, message, overrideTag string) (PushResult, error) {
env := NewDotEnv(".env")
prURL, ok := env.Get("CODEJOB_PR")
if !ok || prURL == "" {
return PushResult{}, fmt.Errorf("no pending PR found. Run 'codejob' first to check status")
}
// 0. Ensure we are on the Jules branch before committing anything
branchOut, err := RunCommandSilent("gh", "pr", "view", prURL, "--json", "headRefName", "--jq", ".headRefName")
var julesBranch string
if err == nil {
julesBranch = strings.TrimSpace(branchOut)
if julesBranch != "" {
RunCommandSilent("git", "checkout", julesBranch)
}
}
// 1. Pre-merge: if working tree is dirty, commit corrections to Jules branch and push
statusOut, _ := RunCommandSilent("git", "status", "--porcelain")
if strings.TrimSpace(statusOut) != "" {
if out, err := RunCommandSilent("git", "add", "."); err != nil {
return PushResult{}, fmt.Errorf("pre-merge git add failed: %w\n%s", err, out)
}
if out, err := RunCommandSilent("git", "commit", "-m", "review: corrections before merge"); err != nil {
return PushResult{}, fmt.Errorf("pre-merge commit failed: %w\n%s", err, out)
}
if out, err := RunCommandSilent("git", "push"); err != nil {
return PushResult{}, fmt.Errorf("pre-merge push failed: %w\n%s", err, out)
}
}
// Switch to main before merging to avoid 'gh pr merge' branch-switch errors
if out, err := RunCommandSilent("git", "checkout", "main"); err != nil {
return PushResult{}, fmt.Errorf("git checkout main failed: %w\n%s", err, out)
}
// 2. merge PR and delete Jules branch on GitHub
var mergeOut string
var mergeErr error
for i := 0; i < 5; i++ {
mergeOut, mergeErr = RunCommandSilent("gh", "pr", "merge", prURL, "--merge", "--delete-branch")
if mergeErr == nil {
break
}
errMsg := mergeErr.Error()
if strings.Contains(mergeOut, "is not mergeable") || strings.Contains(errMsg, "is not mergeable") ||
strings.Contains(mergeOut, "Base branch was modified") || strings.Contains(errMsg, "Base branch was modified") {
time.Sleep(3 * time.Second)
continue
}
break
}
if mergeErr != nil {
return PushResult{}, fmt.Errorf("gh pr merge failed: %w\n%s", mergeErr, mergeOut)
}
// 2. pull the merged commit locally
if _, err := RunCommandSilent("git", "pull"); err != nil {
return PushResult{}, fmt.Errorf("git pull failed: %w", err)
}
// 3. remove CHECK_PLAN.md (gitignored, local cleanup only)
if _, err := os.Stat("docs/CHECK_PLAN.md"); err == nil {
if err := os.Remove("docs/CHECK_PLAN.md"); err != nil {
return PushResult{}, fmt.Errorf("could not delete CHECK_PLAN.md: %w", err)
}
}
// 4. clean up state
if err := env.Delete("CODEJOB_PR"); err != nil {
return PushResult{}, fmt.Errorf("could not clean up .env: %w", err)
}
// 5. Check for new PLAN.md to re-dispatch
if _, err := os.Stat(DefaultIssuePromptPath); err == nil {
// PLAN.md exists -> call Publisher.Publish (skip deps + tag) + dispatch to agent
res, err := publisher.Publish("chore: sync before re-dispatch", "", true, true, true, true, true)
if err != nil {
return PushResult{}, fmt.Errorf("re-dispatch sync failed: %w", err)
}
res.Summary = "✅ PR merged, 🚀 New plan detected, re-dispatching..."
res.Tag = "RE_DISPATCH"
return res, nil
}
// No PLAN.md -> call full gopush
return publisher.Publish(message, overrideTag, false, false, false, false, false)
}