diff --git a/internal/forge/forge.go b/internal/forge/forge.go index be36177dc..64126b4ea 100644 --- a/internal/forge/forge.go +++ b/internal/forge/forge.go @@ -7,6 +7,8 @@ import ( "context" "fmt" "log/slog" + "strings" + "time" ) // New creates a Forge implementation for the given type. @@ -113,3 +115,67 @@ type RepoForge interface { // development link in the issue sidebar. LinkBranch(ctx context.Context, owner, repo string, issueNumber int, branch string) error } + +// ReviewState values for Review.State, normalised across forges. +const ( + ReviewStateApproved = "approved" + ReviewStateRequestedChanges = "requested_changes" + ReviewStateCommented = "commented" + ReviewStateDismissed = "dismissed" +) + +// Review is a forge-neutral review of an existing PR: an approval, a +// request-changes, a plain comment, or a dismissal. +type Review struct { + ID int64 + Author string + State string // one of the ReviewState* constants + SubmittedAt time.Time +} + +// ReviewComment is a forge-neutral review comment on an existing PR. +// Line is a location hint, not authoritative: the remediation agent reads +// the whole file. InReplyTo is the parent comment ID on GitHub; Gitea's +// inline comments are flat under a review, so it is 0 there. +type ReviewComment struct { + ID int64 + Author string + Body string + Path string + Line int + InReplyTo int64 + CreatedAt time.Time +} + +// PullRequestReviewReader reads review activity on an existing PR. Forge +// implementations that cannot read reviews (the noop forge) do not implement +// it; callers type-assert and refuse when the capability is absent. +// +// sinceID is the dedup cursor: only entries with ID > sinceID are returned, +// so a poller and a webhook delivery of the same comment collapse on the same +// ID (the TaskEnvelope.IdempotencyKey pattern applied to reviews). +type PullRequestReviewReader interface { + ListReviews(ctx context.Context, owner, repo string, number int, sinceID int64) ([]Review, error) + ListReviewComments(ctx context.Context, owner, repo string, number int, sinceID int64) ([]ReviewComment, error) + // ReplyToReview posts a reply to an existing review comment (commentID). + // A summary for a whole review (e.g. "requested changes" addressed) is a + // plain PR comment via Forge.Comment, not this method. + ReplyToReview(ctx context.Context, owner, repo string, number int, commentID int64, body string) error +} + +// normalizeReviewState maps a GitHub review state string onto the neutral +// ReviewState* constants. Unknown states pass through lowercased. +func normalizeReviewState(s string) string { + switch s { + case "APPROVED": + return ReviewStateApproved + case "CHANGES_REQUESTED": + return ReviewStateRequestedChanges + case "COMMENTED": + return ReviewStateCommented + case "DISMISSED": + return ReviewStateDismissed + default: + return strings.ToLower(s) + } +} diff --git a/internal/forge/gitea.go b/internal/forge/gitea.go index e9c933ca7..19fb7382e 100644 --- a/internal/forge/gitea.go +++ b/internal/forge/gitea.go @@ -190,6 +190,98 @@ func (c *GiteaClient) GetPullRequest(ctx context.Context, owner, repo string, nu }, nil } +// ListReviews returns the reviews on a PR with ID > sinceID. +func (c *GiteaClient) ListReviews(ctx context.Context, owner, repo string, number int, sinceID int64) ([]Review, error) { + var out []Review + opts := gitea.ListPullReviewsOptions{} + for { + reviews, resp, err := c.cli.ListPullReviews(owner, repo, int64(number), opts) + if err != nil { + return nil, fmt.Errorf("list reviews %s/%s#%d: %w", owner, repo, number, err) + } + for _, r := range reviews { + if r.ID <= sinceID { + continue + } + out = append(out, Review{ + ID: r.ID, + Author: giteaReviewAuthor(r.Reviewer), + State: normalizeGiteaReviewState(r.State), + SubmittedAt: r.Submitted, + }) + } + if resp.NextPage == 0 { + break + } + opts.Page = resp.NextPage + } + return out, nil +} + +// ListReviewComments returns the inline review comments on a PR with +// ID > sinceID. Gitea nests comments under reviews, so this lists each +// review's comments. +func (c *GiteaClient) ListReviewComments(ctx context.Context, owner, repo string, number int, sinceID int64) ([]ReviewComment, error) { + reviews, err := c.ListReviews(ctx, owner, repo, number, 0) + if err != nil { + return nil, err + } + var out []ReviewComment + for _, rv := range reviews { + comments, _, err := c.cli.ListPullReviewComments(owner, repo, int64(number), rv.ID) + if err != nil { + return nil, fmt.Errorf("list review comments %s/%s#%d review %d: %w", owner, repo, number, rv.ID, err) + } + for _, cm := range comments { + if cm.ID <= sinceID { + continue + } + out = append(out, ReviewComment{ + ID: cm.ID, + Author: giteaReviewAuthor(cm.Reviewer), + Body: cm.Body, + Path: cm.Path, + Line: int(cm.LineNum), + CreatedAt: cm.Created, + }) + } + } + return out, nil +} + +// ReplyToReview posts a reply to an existing review comment. +func (c *GiteaClient) ReplyToReview(ctx context.Context, owner, repo string, number int, commentID int64, body string) error { + if _, _, err := c.cli.CreatePullReviewCommentReply(owner, repo, int64(number), commentID, gitea.CreatePullReviewCommentReplyOptions{Body: body}); err != nil { + return fmt.Errorf("reply to review comment %d on %s/%s#%d: %w", commentID, owner, repo, number, err) + } + return nil +} + +// giteaReviewAuthor returns a review/comment author's login, or "" when the +// author is absent (a team review, or a deleted user). +func giteaReviewAuthor(u *gitea.User) string { + if u == nil { + return "" + } + return u.UserName +} + +// normalizeGiteaReviewState maps a Gitea review state onto the neutral +// ReviewState* constants. Pending and request-review reviews are not a +// decision and pass through lowercased so the caller can ignore them. +func normalizeGiteaReviewState(s gitea.ReviewStateType) string { + switch s { + case gitea.ReviewStateApproved: + return ReviewStateApproved + case gitea.ReviewStateRequestChanges: + return ReviewStateRequestedChanges + case gitea.ReviewStateComment: + return ReviewStateCommented + default: + return strings.ToLower(string(s)) + } +} + // CloseIssue closes an issue with an optional final comment. func (c *GiteaClient) CloseIssue(ctx context.Context, owner, repo string, number int, comment string) error { if comment != "" { diff --git a/internal/forge/github.go b/internal/forge/github.go index b73347aa4..e1011b244 100644 --- a/internal/forge/github.go +++ b/internal/forge/github.go @@ -214,6 +214,77 @@ func (c *GitHubClient) GetPullRequest(ctx context.Context, owner, repo string, n }, nil } +// ListReviews returns the reviews on a PR with ID > sinceID. +func (c *GitHubClient) ListReviews(ctx context.Context, owner, repo string, number int, sinceID int64) ([]Review, error) { + var out []Review + opts := &github.ListOptions{PerPage: 100} + for { + reviews, resp, err := c.gh.PullRequests.ListReviews(ctx, owner, repo, number, opts) + if err != nil { + return nil, fmt.Errorf("list reviews %s/%s#%d: %w", owner, repo, number, err) + } + for _, r := range reviews { + if r.GetID() <= sinceID { + continue + } + out = append(out, Review{ + ID: r.GetID(), + Author: r.GetUser().GetLogin(), + State: normalizeReviewState(r.GetState()), + SubmittedAt: r.GetSubmittedAt().Time, + }) + } + if resp.NextPage == 0 { + break + } + opts.Page = resp.NextPage + } + return out, nil +} + +// ListReviewComments returns the review comments on a PR with ID > sinceID. +func (c *GitHubClient) ListReviewComments(ctx context.Context, owner, repo string, number int, sinceID int64) ([]ReviewComment, error) { + var out []ReviewComment + opts := &github.PullRequestListCommentsOptions{PerPage: 100} + for { + comments, resp, err := c.gh.PullRequests.ListComments(ctx, owner, repo, number, opts) + if err != nil { + return nil, fmt.Errorf("list review comments %s/%s#%d: %w", owner, repo, number, err) + } + for _, cm := range comments { + if cm.GetID() <= sinceID { + continue + } + line := cm.GetOriginalLine() + if line == 0 { + line = cm.GetLine() + } + out = append(out, ReviewComment{ + ID: cm.GetID(), + Author: cm.GetUser().GetLogin(), + Body: cm.GetBody(), + Path: cm.GetPath(), + Line: line, + InReplyTo: cm.GetInReplyTo(), + CreatedAt: cm.GetCreatedAt().Time, + }) + } + if resp.NextPage == 0 { + break + } + opts.Page = resp.NextPage + } + return out, nil +} + +// ReplyToReview posts a reply to an existing review comment. +func (c *GitHubClient) ReplyToReview(ctx context.Context, owner, repo string, number int, commentID int64, body string) error { + if _, _, err := c.gh.PullRequests.CreateCommentInReplyTo(ctx, owner, repo, number, body, commentID); err != nil { + return fmt.Errorf("reply to review comment %d on %s/%s#%d: %w", commentID, owner, repo, number, err) + } + return nil +} + // CloseIssue closes an issue with a final comment (feasibility "won't do"). func (c *GitHubClient) CloseIssue(ctx context.Context, owner, repo string, number int, comment string) error { if comment != "" { diff --git a/internal/forge/review_methods_test.go b/internal/forge/review_methods_test.go new file mode 100644 index 000000000..fc38f7ff1 --- /dev/null +++ b/internal/forge/review_methods_test.go @@ -0,0 +1,170 @@ +package forge + +import ( + "encoding/json" + "net/http" + "testing" +) + +func TestGitHubListReviews(t *testing.T) { + c, mux := newTestClient(t) + mux.HandleFunc("GET /repos/o/r/pulls/7/reviews", func(w http.ResponseWriter, r *http.Request) { + writeJSON(t, w, []map[string]any{ + {"id": 1, "state": "APPROVED", "user": map[string]any{"login": "alice"}}, + {"id": 2, "state": "CHANGES_REQUESTED", "user": map[string]any{"login": "bob"}}, + }) + }) + + reviews, err := c.ListReviews(t.Context(), "o", "r", 7, 0) + if err != nil { + t.Fatal(err) + } + if len(reviews) != 2 { + t.Fatalf("reviews = %d, want 2", len(reviews)) + } + if reviews[0].ID != 1 || reviews[0].Author != "alice" || reviews[0].State != ReviewStateApproved { + t.Errorf("reviews[0] = %+v", reviews[0]) + } + if reviews[1].State != ReviewStateRequestedChanges { + t.Errorf("reviews[1].State = %q, want %q", reviews[1].State, ReviewStateRequestedChanges) + } + + // sinceID cursor excludes already-seen reviews. + reviews, err = c.ListReviews(t.Context(), "o", "r", 7, 1) + if err != nil { + t.Fatal(err) + } + if len(reviews) != 1 || reviews[0].ID != 2 { + t.Fatalf("sinceID-filtered reviews = %+v, want only id 2", reviews) + } +} + +func TestGitHubListReviewComments(t *testing.T) { + c, mux := newTestClient(t) + mux.HandleFunc("GET /repos/o/r/pulls/7/comments", func(w http.ResponseWriter, r *http.Request) { + writeJSON(t, w, []map[string]any{ + {"id": 10, "body": "nil deref here", "path": "a.go", "original_line": 42, "in_reply_to_id": 5, "user": map[string]any{"login": "alice"}}, + }) + }) + + comments, err := c.ListReviewComments(t.Context(), "o", "r", 7, 0) + if err != nil { + t.Fatal(err) + } + if len(comments) != 1 { + t.Fatalf("comments = %d, want 1", len(comments)) + } + got := comments[0] + if got.ID != 10 || got.Author != "alice" || got.Body != "nil deref here" || + got.Path != "a.go" || got.Line != 42 || got.InReplyTo != 5 { + t.Errorf("comment = %+v", got) + } +} + +func TestGitHubReplyToReview(t *testing.T) { + c, mux := newTestClient(t) + var gotBody map[string]any + mux.HandleFunc("POST /repos/o/r/pulls/7/comments", func(w http.ResponseWriter, r *http.Request) { + if err := json.NewDecoder(r.Body).Decode(&gotBody); err != nil { + t.Fatal(err) + } + writeJSON(t, w, map[string]any{"id": 99}) + }) + + if err := c.ReplyToReview(t.Context(), "o", "r", 7, 42, "fixed"); err != nil { + t.Fatal(err) + } + if gotBody["body"] != "fixed" || gotBody["in_reply_to"] != float64(42) { + t.Errorf("request body = %v, want body=fixed in_reply_to=42", gotBody) + } +} + +func TestGiteaListReviews(t *testing.T) { + c, mux := newTestGiteaClient(t) + mux.HandleFunc("GET /api/v1/repos/o/r/pulls/7/reviews", func(w http.ResponseWriter, r *http.Request) { + writeJSON(t, w, []map[string]any{ + {"id": 1, "state": "APPROVED", "user": map[string]any{"login": "alice"}}, + {"id": 2, "state": "REQUEST_CHANGES", "user": map[string]any{"login": "bob"}}, + }) + }) + + reviews, err := c.ListReviews(t.Context(), "o", "r", 7, 0) + if err != nil { + t.Fatal(err) + } + if len(reviews) != 2 { + t.Fatalf("reviews = %d, want 2", len(reviews)) + } + if reviews[0].State != ReviewStateApproved || reviews[0].Author != "alice" { + t.Errorf("reviews[0] = %+v", reviews[0]) + } + if reviews[1].State != ReviewStateRequestedChanges { + t.Errorf("reviews[1].State = %q, want %q", reviews[1].State, ReviewStateRequestedChanges) + } +} + +func TestGiteaListReviewComments(t *testing.T) { + c, mux := newTestGiteaClient(t) + mux.HandleFunc("GET /api/v1/repos/o/r/pulls/7/reviews", func(w http.ResponseWriter, r *http.Request) { + writeJSON(t, w, []map[string]any{{"id": 3, "state": "COMMENT", "user": map[string]any{"login": "alice"}}}) + }) + mux.HandleFunc("GET /api/v1/repos/o/r/pulls/7/reviews/3/comments", func(w http.ResponseWriter, r *http.Request) { + writeJSON(t, w, []map[string]any{ + {"id": 20, "body": "race here", "path": "b.go", "position": 12, "user": map[string]any{"login": "bob"}}, + }) + }) + + comments, err := c.ListReviewComments(t.Context(), "o", "r", 7, 0) + if err != nil { + t.Fatal(err) + } + if len(comments) != 1 { + t.Fatalf("comments = %d, want 1", len(comments)) + } + got := comments[0] + if got.ID != 20 || got.Author != "bob" || got.Body != "race here" || got.Path != "b.go" || got.Line != 12 { + t.Errorf("comment = %+v", got) + } + + // sinceID cursor excludes already-seen comments. + comments, err = c.ListReviewComments(t.Context(), "o", "r", 7, 20) + if err != nil { + t.Fatal(err) + } + if len(comments) != 0 { + t.Fatalf("sinceID-filtered comments = %+v, want empty", comments) + } +} + +func TestGiteaReplyToReview(t *testing.T) { + c, mux := newTestGiteaClient(t) + var got map[string]any + mux.HandleFunc("POST /api/v1/repos/o/r/pulls/7/comments/42/replies", func(w http.ResponseWriter, r *http.Request) { + if err := json.NewDecoder(r.Body).Decode(&got); err != nil { + t.Fatal(err) + } + writeJSON(t, w, map[string]any{"id": 99}) + }) + + if err := c.ReplyToReview(t.Context(), "o", "r", 7, 42, "fixed"); err != nil { + t.Fatal(err) + } + if got["body"] != "fixed" { + t.Errorf("request body = %v, want body=fixed", got) + } +} + +func TestNormalizeReviewState(t *testing.T) { + tests := map[string]string{ + "APPROVED": ReviewStateApproved, + "CHANGES_REQUESTED": ReviewStateRequestedChanges, + "COMMENTED": ReviewStateCommented, + "DISMISSED": ReviewStateDismissed, + "SOMETHING_NEW": "something_new", + } + for in, want := range tests { + if got := normalizeReviewState(in); got != want { + t.Errorf("normalizeReviewState(%q) = %q, want %q", in, got, want) + } + } +}