-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpipeline.go
More file actions
2146 lines (2012 loc) · 79.3 KB
/
Copy pathpipeline.go
File metadata and controls
2146 lines (2012 loc) · 79.3 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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bytes"
"context"
"crypto/sha256"
"database/sql"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"net/url"
"os"
osexec "os/exec"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"time"
)
const (
RunKindCodexImplement = "codex_implement"
RunKindGrokReview = "grok_review"
RunKindCodexFix = "codex_fix"
RunKindCodexAddressFeedback = "codex_address_feedback"
RunKindCodexResolveConflicts = "codex_resolve_conflicts"
feedbackFingerprintPrefix = "feedback_fingerprint:"
eventAwaitingHumanReview = "awaiting_human_review"
eventAddressingFeedback = "addressing_feedback"
eventFeedbackAddressed = "feedback_addressed"
eventFeedbackNoChanges = "feedback_no_changes"
eventResolvingConflicts = "resolving_conflicts"
eventConflictsResolved = "conflicts_resolved"
eventMergeConflictDetected = "merge_conflict_detected"
PipelinePhasePreflight = "preflight"
PipelinePhaseBranching = "branching"
PipelinePhaseImplement = "implementing"
PipelinePhasePush = "pushing"
PipelinePhaseCreatePR = "creating_pr"
PipelinePhaseReview = "reviewing"
PipelinePhaseFix = "fixing"
PipelinePhaseQualityGate = "quality_gate"
PipelinePhaseMerge = "merging"
PipelinePhaseAwaitingHuman = "awaiting_human"
PipelinePhaseAddressFeedback = "addressing_feedback"
PipelinePhaseResolveConflicts = "resolving_conflicts"
PipelinePhaseCompleted = "completed"
)
// pipelineResult is the successful outcome of runStoryPipeline.
// AwaitingHuman means supervised mode paused after PR + agent review (story is in_review).
type pipelineResult struct {
FinalMessage string
AwaitingHuman bool
}
type StoryPipeline struct {
ID int64
QueueRunID int64
StoryID string
Phase string
Branch string
DefaultBranch string
PRNumber int
PRURL string
ReviewJSON string
Error string
// MergeConflict is set when GitHub reports the PR cannot merge cleanly (usually after another PR landed).
MergeConflict bool
}
type pipelineContext struct {
QueueRunID int64
BaseURL string
Project Project
Story Story
Branch string
DefaultBranch string
PRNumber int
PRURL string
}
func storyBranchName(project Project, story Story) string {
slug := slugifyBranchSegment(story.Title)
if slug == "" {
slug = "work"
}
prefix := strings.TrimSpace(project.Prefix)
if prefix == "" {
prefix = strings.TrimSpace(story.ProjectPrefix)
}
tmpl := normalizeBranchNameTemplate(project.BranchNameTemplate)
branch := tmpl
branch = strings.ReplaceAll(branch, "{id}", story.ID)
branch = strings.ReplaceAll(branch, "{slug}", slug)
branch = strings.ReplaceAll(branch, "{prefix}", prefix)
branch = strings.Trim(branch, "/")
if branch == "" || strings.Contains(branch, "{") {
return fmt.Sprintf("ripple/%s-%s", story.ID, slug)
}
return branch
}
var branchSlugPattern = regexp.MustCompile(`[^a-z0-9]+`)
func slugifyBranchSegment(text string) string {
text = strings.ToLower(strings.TrimSpace(text))
text = branchSlugPattern.ReplaceAllString(text, "-")
text = strings.Trim(text, "-")
if len(text) > 48 {
text = strings.Trim(text[:48], "-")
}
return text
}
func resolveGhBinary() (string, error) {
if configured := firstEnv("RIPPLE_GH_BIN", "TASKMANAGER_GH_BIN"); configured != "" {
return configured, nil
}
path, err := osexec.LookPath("gh")
if err != nil {
return "", badRequest("GitHub CLI (gh) was not found. Install gh and authenticate with `gh auth login`, or set RIPPLE_GH_BIN.")
}
return path, nil
}
func runCommand(ctx context.Context, dir string, name string, args ...string) (string, string, error) {
return runCommandEnv(ctx, dir, nil, name, args...)
}
func runCommandEnv(ctx context.Context, dir string, env []string, name string, args ...string) (string, string, error) {
cmd := osexec.CommandContext(ctx, name, args...)
if dir != "" {
cmd.Dir = dir
}
if len(env) > 0 {
cmd.Env = env
}
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err := cmd.Run()
return stdout.String(), stderr.String(), err
}
func gitPreflight(ctx context.Context, dir string, defaultBranchOverride string) (string, error) {
if !isGitWorkTree(dir) {
return "", fmt.Errorf("working directory is not a git repository: %s", dir)
}
if _, _, err := runCommand(ctx, dir, "git", "rev-parse", "--is-inside-work-tree"); err != nil {
return "", err
}
status, _, err := runCommand(ctx, dir, "git", "status", "--porcelain")
if err != nil {
return "", err
}
if strings.TrimSpace(status) != "" {
return "", fmt.Errorf("repository has uncommitted changes; commit, stash, or discard local changes before running the queue:\n%s", truncate(status, 1200))
}
var defaultBranch string
if override := strings.TrimSpace(defaultBranchOverride); override != "" {
defaultBranch = override
} else {
defaultBranch, err = detectDefaultBranch(ctx, dir)
if err != nil {
return "", err
}
}
// Always refresh from origin so feature branches are cut from current main/master,
// not a stale local copy left behind by earlier PR merges.
if err := gitFetchOrigin(ctx, dir); err != nil {
return "", err
}
if err := gitUpdateLocalBranchFromOrigin(ctx, dir, defaultBranch); err != nil {
return "", err
}
current, _, err := runCommand(ctx, dir, "git", "branch", "--show-current")
if err != nil {
return "", err
}
current = strings.TrimSpace(current)
if current != defaultBranch {
if _, stderr, err := runCommand(ctx, dir, "git", "checkout", defaultBranch); err != nil {
detail := strings.TrimSpace(stderr)
if detail == "" {
detail = err.Error()
}
return "", fmt.Errorf("could not checkout %s: %s", defaultBranch, detail)
}
}
return defaultBranch, nil
}
func gitFetchOrigin(ctx context.Context, dir string) error {
// Skip when there is no origin remote (local-only / test repos).
if _, _, err := runCommand(ctx, dir, "git", "remote", "get-url", "origin"); err != nil {
return nil
}
if _, stderr, err := runCommand(ctx, dir, "git", "fetch", "origin"); err != nil {
detail := strings.TrimSpace(stderr)
if detail == "" {
detail = err.Error()
}
return fmt.Errorf("git fetch origin failed: %s", detail)
}
return nil
}
// gitUpdateLocalBranchFromOrigin fast-forwards local defaultBranch to origin/defaultBranch.
func gitUpdateLocalBranchFromOrigin(ctx context.Context, dir, branch string) error {
remoteRef := "origin/" + branch
if _, _, err := runCommand(ctx, dir, "git", "rev-parse", "--verify", remoteRef); err != nil {
// No remote tracking ref yet (offline / first clone without origin) — keep local branch.
return nil
}
if _, stderr, err := runCommand(ctx, dir, "git", "checkout", branch); err != nil {
detail := strings.TrimSpace(stderr)
if detail == "" {
detail = err.Error()
}
return fmt.Errorf("checkout %s failed: %s", branch, detail)
}
if _, stderr, err := runCommand(ctx, dir, "git", "merge", "--ff-only", remoteRef); err != nil {
// Fall back to hard reset when local main diverged (common after GitHub-side merges).
if _, stderr2, err2 := runCommand(ctx, dir, "git", "reset", "--hard", remoteRef); err2 != nil {
detail := strings.TrimSpace(stderr2)
if detail == "" {
detail = strings.TrimSpace(stderr)
}
if detail == "" {
detail = err2.Error()
}
return fmt.Errorf("update %s from %s failed: %s", branch, remoteRef, detail)
}
}
return nil
}
func gitHasUnresolvedConflicts(ctx context.Context, dir string) (bool, error) {
stdout, _, err := runCommand(ctx, dir, "git", "ls-files", "-u")
if err != nil {
return false, err
}
return strings.TrimSpace(stdout) != "", nil
}
func gitMergeInProgress(ctx context.Context, dir string) bool {
// MERGE_HEAD exists while a merge is unfinished.
if _, _, err := runCommand(ctx, dir, "git", "rev-parse", "-q", "--verify", "MERGE_HEAD"); err == nil {
return true
}
return false
}
func gitCurrentBranch(ctx context.Context, dir string) (string, error) {
stdout, stderr, err := runCommand(ctx, dir, "git", "branch", "--show-current")
if err != nil {
detail := strings.TrimSpace(stderr)
if detail == "" {
detail = err.Error()
}
return "", fmt.Errorf("current branch: %s", detail)
}
return strings.TrimSpace(stdout), nil
}
func gitAbortMerge(ctx context.Context, dir string) {
_, _, _ = runCommand(ctx, dir, "git", "merge", "--abort")
}
// gitWorktreeHasConflictMarkers reports whether any tracked file still contains merge markers.
// Agents often rewrite conflicted files without git-add; the index can still look "unmerged"
// even when the working tree content is clean — so marker scan is the source of truth after an agent pass.
func gitWorktreeHasConflictMarkers(ctx context.Context, dir string) (bool, error) {
// git grep exits 1 when there are no matches.
stdout, stderr, err := runCommand(ctx, dir, "git", "grep", "-n", "-E", `^<<<<<<< |^>>>>>>> `, "--", ".")
if strings.TrimSpace(stdout) != "" {
return true, nil
}
if err == nil {
return false, nil
}
if strings.Contains(err.Error(), "exit status 1") {
return false, nil
}
detail := strings.TrimSpace(stderr)
if detail == "" {
detail = err.Error()
}
return false, fmt.Errorf("scan conflict markers: %s", detail)
}
// gitMergeBaseIntoFeature merges origin/defaultBranch into featureBranch.
// Returns hadConflicts=true when the merge stopped with unresolved paths (agent should fix).
// If a merge is already in progress on featureBranch (retry after a partial agent pass), resumes that merge.
func gitMergeBaseIntoFeature(ctx context.Context, dir, featureBranch, defaultBranch string) (hadConflicts bool, err error) {
if err := gitFetchOrigin(ctx, dir); err != nil {
return false, err
}
if gitMergeInProgress(ctx, dir) {
current, curErr := gitCurrentBranch(ctx, dir)
if curErr != nil {
gitAbortMerge(ctx, dir)
} else if current == featureBranch {
conflicts, confErr := gitHasUnresolvedConflicts(ctx, dir)
if confErr != nil {
return false, confErr
}
if conflicts {
return true, nil
}
// Merge in progress but index is clean — ready to commit.
return false, nil
} else {
// Stale merge on another branch — reset so we can start cleanly.
gitAbortMerge(ctx, dir)
}
}
if err := gitCheckoutBranch(ctx, dir, featureBranch); err != nil {
// Index may still be locked from a prior failed merge attempt.
if gitMergeInProgress(ctx, dir) {
gitAbortMerge(ctx, dir)
if err2 := gitCheckoutBranch(ctx, dir, featureBranch); err2 != nil {
return false, err2
}
} else {
return false, err
}
}
// Ensure we have the latest pushed feature tip when the branch tracks origin.
remoteFeature := "origin/" + featureBranch
if _, _, revErr := runCommand(ctx, dir, "git", "rev-parse", "--verify", remoteFeature); revErr == nil {
_, _, _ = runCommand(ctx, dir, "git", "merge", "--ff-only", remoteFeature)
}
// Prefer origin/default when available; also update local default so later ops are consistent.
_ = gitUpdateLocalBranchFromOrigin(ctx, dir, defaultBranch)
if err := gitCheckoutBranch(ctx, dir, featureBranch); err != nil {
return false, err
}
remoteBase := "origin/" + defaultBranch
if _, _, revErr := runCommand(ctx, dir, "git", "rev-parse", "--verify", remoteBase); revErr != nil {
// Fall back to local default branch if remote is missing.
remoteBase = defaultBranch
}
_, stderr, mergeErr := runCommand(ctx, dir, "git", "merge", "--no-edit", remoteBase)
if mergeErr == nil {
return false, nil
}
conflicts, confErr := gitHasUnresolvedConflicts(ctx, dir)
if confErr != nil {
return false, confErr
}
if conflicts {
return true, nil
}
detail := strings.TrimSpace(stderr)
if detail == "" {
detail = mergeErr.Error()
}
return false, fmt.Errorf("merge %s into %s failed: %s", remoteBase, featureBranch, detail)
}
func gitCompleteMergeCommit(ctx context.Context, dir, message string, id GitHubIdentityConfig) error {
if _, stderr, err := runCommand(ctx, dir, "git", "add", "-A"); err != nil {
detail := strings.TrimSpace(stderr)
if detail == "" {
detail = err.Error()
}
return fmt.Errorf("git add failed: %s", detail)
}
if still, err := gitHasUnresolvedConflicts(ctx, dir); err != nil {
return err
} else if still {
return errors.New("unmerged paths remain after staging; conflict markers may still be present")
}
message = id.decorateCommitMessage(ctx, dir, message)
env := mergeEnv(id.commitEnv(ctx, dir))
if gitMergeInProgress(ctx, dir) {
if _, stderr, err := runCommandEnv(ctx, dir, env, "git", "commit", "--no-edit", "-m", message); err != nil {
// --no-edit may fail if no MERGE_MSG; retry with explicit message only.
if _, stderr2, err2 := runCommandEnv(ctx, dir, env, "git", "commit", "-m", message); err2 != nil {
detail := strings.TrimSpace(stderr2)
if detail == "" {
detail = strings.TrimSpace(stderr)
}
if detail == "" {
detail = err2.Error()
}
return fmt.Errorf("git commit (merge) failed: %s", detail)
}
}
return nil
}
return gitCommitAll(ctx, dir, message, id)
}
func detectDefaultBranch(ctx context.Context, dir string) (string, error) {
for _, candidate := range []string{"main", "master"} {
if _, _, err := runCommand(ctx, dir, "git", "show-ref", "--verify", "--quiet", "refs/heads/"+candidate); err == nil {
return candidate, nil
}
if _, _, err := runCommand(ctx, dir, "git", "show-ref", "--verify", "--quiet", "refs/remotes/origin/"+candidate); err == nil {
return candidate, nil
}
}
stdout, _, err := runCommand(ctx, dir, "git", "symbolic-ref", "refs/remotes/origin/HEAD")
if err == nil {
ref := strings.TrimSpace(stdout)
if parts := strings.Split(ref, "/"); len(parts) > 0 {
return parts[len(parts)-1], nil
}
}
return "", errors.New("could not detect default branch; expected main or master")
}
func gitCreateFeatureBranch(ctx context.Context, dir, defaultBranch, branch string) error {
if _, stderr, err := runCommand(ctx, dir, "git", "checkout", defaultBranch); err != nil {
detail := strings.TrimSpace(stderr)
if detail == "" {
detail = err.Error()
}
return fmt.Errorf("checkout %s failed: %s", defaultBranch, detail)
}
if _, stderr, err := runCommand(ctx, dir, "git", "checkout", "-b", branch); err != nil {
detail := strings.TrimSpace(stderr)
if detail == "" {
detail = err.Error()
}
return fmt.Errorf("create branch %s failed: %s", branch, detail)
}
return nil
}
func gitCommitAll(ctx context.Context, dir, message string, id GitHubIdentityConfig) error {
status, _, err := runCommand(ctx, dir, "git", "status", "--porcelain")
if err != nil {
return err
}
if strings.TrimSpace(status) == "" {
return nil
}
if _, stderr, err := runCommand(ctx, dir, "git", "add", "-A"); err != nil {
detail := strings.TrimSpace(stderr)
if detail == "" {
detail = err.Error()
}
return fmt.Errorf("git add failed: %s", detail)
}
message = id.decorateCommitMessage(ctx, dir, message)
env := mergeEnv(id.commitEnv(ctx, dir))
if _, stderr, err := runCommandEnv(ctx, dir, env, "git", "commit", "-m", message); err != nil {
detail := strings.TrimSpace(stderr)
if detail == "" {
detail = err.Error()
}
return fmt.Errorf("git commit failed: %s", detail)
}
return nil
}
func gitBranchAheadCount(ctx context.Context, dir, baseBranch, branch string) (int, error) {
stdout, _, err := runCommand(ctx, dir, "git", "rev-list", "--count", baseBranch+".."+branch)
if err != nil {
return 0, err
}
var count int
if _, scanErr := fmt.Sscanf(strings.TrimSpace(stdout), "%d", &count); scanErr != nil {
return 0, scanErr
}
return count, nil
}
func gitPushBranch(ctx context.Context, dir, branch string) error {
if _, stderr, err := runCommand(ctx, dir, "git", "push", "-u", "origin", branch); err != nil {
detail := strings.TrimSpace(stderr)
if detail == "" {
detail = err.Error()
}
return fmt.Errorf("push branch %s failed: %s", branch, detail)
}
return nil
}
func gitCheckoutBranch(ctx context.Context, dir, branch string) error {
if _, stderr, err := runCommand(ctx, dir, "git", "checkout", branch); err != nil {
detail := strings.TrimSpace(stderr)
if detail == "" {
detail = err.Error()
}
return fmt.Errorf("checkout %s failed: %s", branch, detail)
}
return nil
}
func gitDeleteLocalBranch(ctx context.Context, dir, branch, defaultBranch string) error {
_ = gitCheckoutBranch(ctx, dir, defaultBranch)
if _, _, err := runCommand(ctx, dir, "git", "branch", "-D", branch); err != nil {
return err
}
return nil
}
func ghCreatePR(ctx context.Context, ghBin, dir, baseBranch, headBranch, title, body string, id GitHubIdentityConfig) (int, string, error) {
if err := id.validateBotFor(id.PRAuthorMode, "open pull requests"); err != nil {
return 0, "", err
}
env := mergeEnv(id.ghEnvFor(id.PRAuthorMode))
stdout, stderr, err := runCommandEnv(ctx, dir, env, ghBin, "pr", "create",
"--base", baseBranch,
"--head", headBranch,
"--title", title,
"--body", body,
)
if err != nil {
detail := strings.TrimSpace(stderr)
if detail == "" {
detail = strings.TrimSpace(stdout)
}
if detail == "" {
detail = err.Error()
}
return 0, "", fmt.Errorf("create PR failed: %s", detail)
}
prNumber, prURL, err := parseCreatedPRURL(stdout)
if err != nil {
return 0, "", fmt.Errorf("parse PR create response: %w", err)
}
return prNumber, prURL, nil
}
func parseCreatedPRURL(output string) (int, string, error) {
lines := strings.Fields(output)
if len(lines) == 0 {
return 0, "", errors.New("create PR returned no URL")
}
prURL := lines[len(lines)-1]
parsed, err := url.Parse(prURL)
if err != nil || parsed.Scheme == "" || parsed.Host == "" {
return 0, "", fmt.Errorf("create PR returned invalid URL %q", prURL)
}
parts := strings.Split(strings.Trim(parsed.Path, "/"), "/")
if len(parts) < 2 || parts[len(parts)-2] != "pull" {
return 0, "", fmt.Errorf("create PR returned unexpected URL %q", prURL)
}
prNumber, err := strconv.Atoi(parts[len(parts)-1])
if err != nil || prNumber <= 0 {
return 0, "", fmt.Errorf("create PR returned invalid PR number in %q", prURL)
}
return prNumber, prURL, nil
}
func ghPRDiff(ctx context.Context, ghBin, dir string, prNumber int) (string, error) {
stdout, stderr, err := runCommand(ctx, dir, ghBin, "pr", "diff", fmt.Sprintf("%d", prNumber))
if err != nil {
detail := strings.TrimSpace(stderr)
if detail == "" {
detail = err.Error()
}
return "", fmt.Errorf("gh pr diff failed: %s", detail)
}
return stdout, nil
}
func ghPRComment(ctx context.Context, ghBin, dir string, prNumber int, body string, id GitHubIdentityConfig) error {
if err := id.validateBotFor(id.CommentMode, "post agent review comments"); err != nil {
return err
}
env := mergeEnv(id.ghEnvFor(id.CommentMode))
_, stderr, err := runCommandEnv(ctx, dir, env, ghBin, "pr", "comment", fmt.Sprintf("%d", prNumber), "--body", body)
if err != nil {
detail := strings.TrimSpace(stderr)
if detail == "" {
detail = err.Error()
}
return fmt.Errorf("post PR comment failed: %s", detail)
}
return nil
}
func ghPRMerge(ctx context.Context, ghBin, dir string, prNumber int, deleteRemoteBranch bool) error {
args := []string{"pr", "merge", fmt.Sprintf("%d", prNumber), "--merge"}
if deleteRemoteBranch {
args = append(args, "--delete-branch")
}
_, stderr, err := runCommand(ctx, dir, ghBin, args...)
if err != nil {
detail := strings.TrimSpace(stderr)
if detail == "" {
detail = err.Error()
}
return fmt.Errorf("merge PR failed: %s", detail)
}
return nil
}
// ghPRIsMerged reports whether the given pull request is already merged on GitHub.
func ghPRIsMerged(ctx context.Context, ghBin, dir string, prNumber int) (bool, error) {
stdout, stderr, err := runCommand(ctx, dir, ghBin, "pr", "view", fmt.Sprintf("%d", prNumber), "--json", "state,mergedAt")
if err != nil {
detail := strings.TrimSpace(stderr)
if detail == "" {
detail = err.Error()
}
return false, fmt.Errorf("check PR status failed: %s", detail)
}
var view struct {
State string `json:"state"`
MergedAt string `json:"mergedAt"`
}
if err := json.Unmarshal([]byte(stdout), &view); err != nil {
return false, fmt.Errorf("parse PR status: %w", err)
}
if strings.EqualFold(view.State, "MERGED") {
return true, nil
}
if strings.TrimSpace(view.MergedAt) != "" {
return true, nil
}
return false, nil
}
// ghPRHasMergeConflicts reports whether GitHub currently sees the PR as conflicting with its base.
// UNKNOWN is treated as not conflicting so we do not block on transient GitHub calculation delays.
func ghPRHasMergeConflicts(ctx context.Context, ghBin, dir string, prNumber int) (bool, string, error) {
conflicted, unknown, detail, err := inspectPRMergeConflicts(ctx, ghBin, dir, prNumber)
if err != nil {
return false, "", err
}
if unknown {
return false, "", nil
}
return conflicted, detail, nil
}
func looksLikeMergeConflictError(msg string) bool {
lower := strings.ToLower(msg)
return strings.Contains(lower, "merge conflict") || strings.Contains(lower, "has merge conflicts")
}
func runQualityGate(ctx context.Context, dir string) error {
checks := qualityGateChecks(dir)
if len(checks) == 0 {
return nil
}
var failures []string
for _, check := range checks {
parts := strings.Fields(check)
if len(parts) == 0 {
continue
}
_, stderr, err := runCommand(ctx, dir, parts[0], parts[1:]...)
if err != nil {
detail := strings.TrimSpace(stderr)
if detail == "" {
detail = err.Error()
}
failures = append(failures, fmt.Sprintf("%s failed:\n%s", check, truncate(detail, 1200)))
}
}
if len(failures) > 0 {
return errors.New(strings.Join(failures, "\n\n"))
}
return nil
}
func qualityGateChecks(dir string) []string {
var checks []string
if _, err := os.Stat(filepath.Join(dir, "go.mod")); err == nil {
checks = append(checks, "go test ./...")
checks = append(checks, "go vet ./...")
}
if _, err := os.Stat(filepath.Join(dir, "package.json")); err == nil {
for _, script := range []string{"test", "lint", "typecheck", "build"} {
if hasNPMScript(dir, script) {
checks = append(checks, "npm run "+script)
}
}
}
return checks
}
func hasNPMScript(dir, name string) bool {
data, err := os.ReadFile(filepath.Join(dir, "package.json"))
if err != nil {
return false
}
var pkg struct {
Scripts map[string]string `json:"scripts"`
}
if err := json.Unmarshal(data, &pkg); err != nil {
return false
}
script, ok := pkg.Scripts[name]
return ok && strings.TrimSpace(script) != ""
}
func buildCodexImplementPrompt(baseURL, botDocs string, project Project, story Story, branch, previousSummary string) string {
var b strings.Builder
fmt.Fprintf(&b, "You are being run by Ripple to implement one queued story on a feature branch.\n\n")
fmt.Fprintf(&b, "# Working Rules\n\n")
fmt.Fprintf(&b, "- You are already on feature branch `%s`. Do not create, rename, push, or merge branches.\n", branch)
fmt.Fprintf(&b, "- Do not open pull requests, push commits, or merge. Ripple handles git and GitHub after you finish.\n")
fmt.Fprintf(&b, "- Do not change story status through the API. The orchestrator marks the story done after the PR is merged.\n")
fmt.Fprintf(&b, "- Work only on the current story unless a tiny adjacent change is required.\n")
fmt.Fprintf(&b, "- Before editing, inspect the project structure and look for AGENTS.md, README files, styleguides, shared components, existing similar screens, routes, tests, and CSS patterns.\n")
fmt.Fprintf(&b, "- Follow the style and conventions of the existing app. Prefer existing helpers and patterns over new abstractions.\n")
fmt.Fprintf(&b, "- Run relevant tests and linting before finishing. If checks cannot run, explain why in your final response.\n")
fmt.Fprintf(&b, "- The sandbox may block network access, writes outside the project, and localhost servers. Do not repeatedly retry commands that fail for those reasons.\n")
fmt.Fprintf(&b, "- Do not use network-backed package loaders such as `pnpm dlx` or `npx` unless the required package is already cached. Prefer installed package sources and repository documentation.\n")
fmt.Fprintf(&b, "- If repository guidance references a missing file or unmatched glob, note it once and continue with the guidance that is available.\n")
fmt.Fprintf(&b, "- Do not launch a long-running development server for verification. Use finite tests and builds; explain any browser-test limitation in your final response.\n")
fmt.Fprintf(&b, "- Leave all completed work as local file changes. The orchestrator will commit and push after you finish.\n")
fmt.Fprintf(&b, "- If you cannot complete the work, explain the blocker in your final response.\n\n")
fmt.Fprintf(&b, "# Ripple API\n\n")
fmt.Fprintf(&b, "Base URL: %s\n\n", baseURL)
fmt.Fprintf(&b, "Bot docs from %s/api/docs:\n\n%s\n\n", baseURL, botDocs)
if strings.TrimSpace(previousSummary) != "" {
fmt.Fprintf(&b, "# Previous Completed Story\n\n%s\n\n", previousSummary)
}
fmt.Fprintf(&b, "# Project\n\n")
fmt.Fprintf(&b, "Name: %s\nID: %s\nPrefix: %s\nWorking directory: %s\nFeature branch: %s\n\n", project.Name, project.ID, project.Prefix, project.WorkingDirectory, branch)
fmt.Fprintf(&b, "# Current Story\n\n")
fmt.Fprintf(&b, "ID: %s\nTitle: %s\nStatus: %s\n", story.ID, story.Title, story.Status)
if story.EpicName != nil {
fmt.Fprintf(&b, "Epic: %s\n", *story.EpicName)
}
fmt.Fprintf(&b, "\nDescription:\n%s\n", story.Description)
return b.String()
}
func buildCodexFixPrompt(baseURL, botDocs string, project Project, story Story, branch string, prNumber int, prURL, reviewJSON string) string {
var b strings.Builder
fmt.Fprintf(&b, "You are being run by Ripple to address one round of pull request review feedback.\n\n")
fmt.Fprintf(&b, "# Working Rules\n\n")
fmt.Fprintf(&b, "- You are on feature branch `%s` for PR #%d (%s).\n", branch, prNumber, prURL)
fmt.Fprintf(&b, "- Read the Grok review feedback below and address valid issues.\n")
fmt.Fprintf(&b, "- Do not merge the PR, change story status, or create a new branch.\n")
fmt.Fprintf(&b, "- Run relevant tests and linting and fix failures before finishing.\n")
fmt.Fprintf(&b, "- The sandbox may block network access, writes outside the project, and localhost servers. Do not repeatedly retry commands that fail for those reasons.\n")
fmt.Fprintf(&b, "- Do not use network-backed package loaders such as `pnpm dlx` or `npx` unless the required package is already cached. Prefer installed package sources and repository documentation.\n")
fmt.Fprintf(&b, "- If repository guidance references a missing file or unmatched glob, note it once and continue with the guidance that is available.\n")
fmt.Fprintf(&b, "- Leave all fixes as local file changes. The orchestrator will commit and push after you finish.\n\n")
fmt.Fprintf(&b, "# Grok Review Feedback\n\n%s\n\n", reviewJSON)
fmt.Fprintf(&b, "# Ripple API\n\nBase URL: %s\n\nBot docs:\n\n%s\n\n", baseURL, botDocs)
fmt.Fprintf(&b, "# Story\n\nID: %s\nTitle: %s\n\nDescription:\n%s\n", story.ID, story.Title, story.Description)
return b.String()
}
// PRFeedback is review input collected for a supervised "Act on review comments" pass.
type PRFeedback struct {
Items []PRFeedbackItem
AgentReviewJSON string
}
type PRFeedbackItem struct {
Kind string // review | review_comment | issue_comment
Author string
Body string
Path string
Line int
}
func (f PRFeedback) HasActionableComments() bool {
for _, item := range f.Items {
if strings.TrimSpace(item.Body) != "" {
return true
}
}
return agentReviewHasActionableContent(f.AgentReviewJSON)
}
func agentReviewHasActionableContent(reviewJSON string) bool {
reviewJSON = strings.TrimSpace(reviewJSON)
if reviewJSON == "" {
return false
}
review, err := parseGrokReview(reviewJSON)
if err != nil {
return true
}
if strings.TrimSpace(review.Summary) != "" {
return true
}
for _, c := range review.Comments {
if strings.TrimSpace(c.Body) != "" {
return true
}
}
return !review.Approved
}
func feedbackFingerprint(f PRFeedback) string {
var b strings.Builder
for _, item := range f.Items {
fmt.Fprintf(&b, "%s|%s|%s|%s|%d\n", item.Kind, item.Author, strings.TrimSpace(item.Body), item.Path, item.Line)
}
b.WriteString("agent:")
b.WriteString(strings.TrimSpace(f.AgentReviewJSON))
sum := sha256.Sum256([]byte(b.String()))
return hex.EncodeToString(sum[:])
}
func lastFeedbackFingerprint(events []StoryEvent) string {
for _, ev := range events {
if ev.Type != eventFeedbackAddressed && ev.Type != eventFeedbackNoChanges {
continue
}
if idx := strings.Index(ev.Message, feedbackFingerprintPrefix); idx >= 0 {
return strings.TrimSpace(ev.Message[idx+len(feedbackFingerprintPrefix):])
}
}
return ""
}
func evaluateAddressFeedback(feedback PRFeedback, events []StoryEvent) error {
if !feedback.HasActionableComments() {
return badRequest("No review comments found to act on. Leave feedback on the pull request, then try again. The story stays in review.")
}
fp := feedbackFingerprint(feedback)
if prev := lastFeedbackFingerprint(events); prev != "" && prev == fp {
return badRequest("No new review comments since the last fix pass. Add feedback on the pull request, then try again. The story stays in review.")
}
return nil
}
func (f PRFeedback) FormatForPrompt() string {
var b strings.Builder
if len(f.Items) == 0 {
b.WriteString("(No pull request comments were collected from GitHub.)\n")
} else {
for i, item := range f.Items {
fmt.Fprintf(&b, "%d. [%s] %s", i+1, item.Kind, item.Author)
if item.Path != "" {
fmt.Fprintf(&b, " · %s", item.Path)
if item.Line > 0 {
fmt.Fprintf(&b, ":%d", item.Line)
}
}
fmt.Fprintf(&b, "\n%s\n\n", strings.TrimSpace(item.Body))
}
}
if strings.TrimSpace(f.AgentReviewJSON) != "" {
fmt.Fprintf(&b, "---\nPrior agent review JSON (secondary context):\n%s\n", f.AgentReviewJSON)
}
return b.String()
}
func buildCodexAddressFeedbackPrompt(baseURL, botDocs string, project Project, story Story, branch string, prNumber int, prURL string, feedback PRFeedback) string {
var b strings.Builder
fmt.Fprintf(&b, "You are being run by Ripple to address pull request review comments for a supervised story.\n\n")
fmt.Fprintf(&b, "# Working Rules\n\n")
fmt.Fprintf(&b, "- You are on feature branch `%s` for PR #%d (%s).\n", branch, prNumber, prURL)
fmt.Fprintf(&b, "- Prioritize **human** review comments and issue comments on the PR. Treat them as the primary source of truth.\n")
fmt.Fprintf(&b, "- Use the prior agent review only as secondary context when it does not conflict with human feedback.\n")
fmt.Fprintf(&b, "- Do not merge the PR, push, change story status, or create a new branch. Ripple commits and pushes after you finish.\n")
fmt.Fprintf(&b, "- Run relevant tests and linting and fix failures before finishing.\n")
fmt.Fprintf(&b, "- The sandbox may block network access, writes outside the project, and localhost servers. Do not repeatedly retry commands that fail for those reasons.\n")
fmt.Fprintf(&b, "- Do not use network-backed package loaders such as `pnpm dlx` or `npx` unless the required package is already cached.\n")
fmt.Fprintf(&b, "- Leave all fixes as local file changes. The orchestrator will commit and push after you finish.\n")
fmt.Fprintf(&b, "- If nothing needs changing, explain that briefly in your final response and leave the tree clean.\n\n")
fmt.Fprintf(&b, "# Review Feedback (human comments first)\n\n%s\n", feedback.FormatForPrompt())
fmt.Fprintf(&b, "# Ripple API\n\nBase URL: %s\n\nBot docs:\n\n%s\n\n", baseURL, botDocs)
fmt.Fprintf(&b, "# Project\n\nName: %s\nWorking directory: %s\n\n", project.Name, project.WorkingDirectory)
fmt.Fprintf(&b, "# Story\n\nID: %s\nTitle: %s\n\nDescription:\n%s\n", story.ID, story.Title, story.Description)
return b.String()
}
func ghCollectPRFeedback(ctx context.Context, ghBin, dir string, prNumber int, agentReviewJSON string) (PRFeedback, error) {
feedback := PRFeedback{AgentReviewJSON: strings.TrimSpace(agentReviewJSON)}
// Review submission bodies (top-level review text). Note: gh pr view --json comments
// is conversation/issue comments, NOT inline review comments — those come from the REST API below.
stdout, stderr, err := runCommand(ctx, dir, ghBin, "pr", "view", fmt.Sprintf("%d", prNumber), "--json", "reviews")
if err != nil {
detail := strings.TrimSpace(stderr)
if detail == "" {
detail = err.Error()
}
return PRFeedback{}, fmt.Errorf("collect PR reviews failed: %s", detail)
}
if err := appendPRReviewBodies(&feedback, stdout); err != nil {
return PRFeedback{}, err
}
repoStdout, _, repoErr := runCommand(ctx, dir, ghBin, "repo", "view", "--json", "nameWithOwner", "-q", ".nameWithOwner")
if repoErr != nil {
// Still return review bodies if we cannot resolve the repo for comment APIs.
prioritizeHumanFeedback(&feedback)
return feedback, nil
}
repo := strings.TrimSpace(repoStdout)
if repo == "" {
prioritizeHumanFeedback(&feedback)
return feedback, nil
}
// Inline code review comments (line comments on the diff).
reviewCommentsPath := fmt.Sprintf("repos/%s/pulls/%d/comments", repo, prNumber)
reviewOut, reviewErrOut, reviewErr := runCommand(ctx, dir, ghBin, "api", reviewCommentsPath)
if reviewErr != nil {
detail := strings.TrimSpace(reviewErrOut)
if detail == "" {
detail = reviewErr.Error()
}
return PRFeedback{}, fmt.Errorf("collect PR review comments failed: %s", detail)
}
if err := appendPRInlineReviewComments(&feedback, reviewOut); err != nil {
return PRFeedback{}, err
}
// Conversation / issue comments on the PR.
issuePath := fmt.Sprintf("repos/%s/issues/%d/comments", repo, prNumber)
issueOut, issueErrOut, issueErr := runCommand(ctx, dir, ghBin, "api", issuePath)
if issueErr != nil {
detail := strings.TrimSpace(issueErrOut)
if detail == "" {
detail = issueErr.Error()
}
return PRFeedback{}, fmt.Errorf("collect PR issue comments failed: %s", detail)
}
if err := appendPRIssueComments(&feedback, issueOut); err != nil {
return PRFeedback{}, err
}
prioritizeHumanFeedback(&feedback)
return feedback, nil
}
func appendPRReviewBodies(feedback *PRFeedback, raw string) error {
var view struct {
Reviews []struct {
Author struct {
Login string `json:"login"`
} `json:"author"`
Body string `json:"body"`
State string `json:"state"`
} `json:"reviews"`
}
if err := json.Unmarshal([]byte(raw), &view); err != nil {
return fmt.Errorf("parse PR review payload: %w", err)
}
for _, review := range view.Reviews {
body := strings.TrimSpace(review.Body)
if body == "" {
continue
}
author := strings.TrimSpace(review.Author.Login)
if author == "" {
author = "unknown"
}
if state := strings.TrimSpace(review.State); state != "" {
body = fmt.Sprintf("(%s) %s", state, body)
}
feedback.Items = append(feedback.Items, PRFeedbackItem{
Kind: "review", Author: author, Body: body,
})
}
return nil
}
func appendPRInlineReviewComments(feedback *PRFeedback, raw string) error {
var comments []struct {
User struct {
Login string `json:"login"`
} `json:"user"`
Body string `json:"body"`
Path string `json:"path"`
Line int `json:"line"`
// GitHub may only populate original_line when the line moved.
OriginalLine int `json:"original_line"`
}
if err := json.Unmarshal([]byte(raw), &comments); err != nil {
return fmt.Errorf("parse PR review comments: %w", err)
}
for _, comment := range comments {
body := strings.TrimSpace(comment.Body)
if body == "" {
continue
}
author := strings.TrimSpace(comment.User.Login)
if author == "" {
author = "unknown"
}
line := comment.Line
if line == 0 {
line = comment.OriginalLine
}
feedback.Items = append(feedback.Items, PRFeedbackItem{
Kind: "review_comment", Author: author, Body: body, Path: comment.Path, Line: line,
})
}
return nil
}