gunk-dev/the-valley

pr.go

sourcecaaa5bee5e11main's published tip history
9.7 KiB
1package review
2
3import (
4 "context"
5 "encoding/json"
6 "errors"
7 "fmt"
8 "os"
9 "strings"
10
11 "the-valley/flow/internal/backend"
12 "the-valley/flow/internal/github"
13)
14
15// CrossReviewMarker opens the hidden line tagging a posted cross-review; re-exported as pipeline.CrossReviewMarker.
16const CrossReviewMarker = "<!-- klaus-cross-review"
17
18const (
19 defaultMaxRounds = 2
20 maxPRBodyBytes = 8_000
21)
22
23var (
24 ErrAlreadyReviewed = errors.New("head commit already cross-reviewed by this backend")
25 ErrMaxRounds = errors.New("cross-review round limit reached")
26 ErrHeadMoved = errors.New("PR head moved during review; not posting stale findings")
27)
28
29// Marker is the metadata in a cross-review's hidden marker line.
30type Marker struct{ Backend, Model, SHA string }
31
32func (m Marker) String() string {
33 return fmt.Sprintf("%s backend=%s model=%s sha=%s -->", CrossReviewMarker, m.Backend, m.Model, m.SHA)
34}
35
36// ParseMarker reads the first cross-review marker in body.
37func ParseMarker(body string) (Marker, bool) {
38 _, rest, ok := strings.Cut(body, CrossReviewMarker)
39 if !ok {
40 return Marker{}, false
41 }
42 fields, _, ok := strings.Cut(rest, "-->")
43 if !ok {
44 return Marker{}, false
45 }
46 var m Marker
47 for _, f := range strings.Fields(fields) {
48 switch k, v, _ := strings.Cut(f, "="); k {
49 case "backend":
50 m.Backend = v
51 case "model":
52 m.Model = v
53 case "sha":
54 m.SHA = v
55 }
56 }
57 return m, true
58}
59
60// PROptions configures RunPRReview.
61type PROptions struct {
62 Backend backend.Kind // reviewer family
63 Model string // "" → CLI default
64 Post bool // submit one COMMENT review
65 MaxRounds int // posted cross-reviews allowed per PR; ≤0 → 2
66 LockDir string // required with Post: per-PR lock held from eligibility check to post
67}
68
69type prInfo struct {
70 Title string `json:"title"`
71 Body string `json:"body"`
72 Head struct {
73 SHA string `json:"sha"`
74 } `json:"head"`
75}
76
77// RunPRReview reviews PR prNumber of repo ("owner/repo") from its diff alone, in an empty temp dir, and with opts.Post submits one COMMENT review (never APPROVE/REQUEST_CHANGES).
78// A refused or failed post still returns the result alongside the error.
79func RunPRReview(ctx context.Context, repo, prNumber string, opts PROptions) (*ReviewResult, error) {
80 if opts.Post {
81 if opts.LockDir == "" {
82 return nil, errors.New("RunPRReview: Post requires LockDir")
83 }
84 unlock, err := lockPR(opts.LockDir, repo, prNumber)
85 if err != nil {
86 return nil, err
87 }
88 defer unlock()
89 }
90 gh := github.NewGHCLIClient(repo)
91 pr, err := fetchPR(ctx, gh, repo, prNumber)
92 if err != nil {
93 return nil, err
94 }
95 if opts.Post {
96 if err := checkRounds(ctx, gh, repo, prNumber, pr.Head.SHA, opts); err != nil {
97 return nil, err
98 }
99 }
100 diff, err := gh.PRDiff(ctx, prNumber)
101 if err != nil {
102 return nil, err
103 }
104 if opts.Post { // inline lines must belong to commit_id
105 if err := checkHead(ctx, gh, repo, prNumber, pr.Head.SHA); err != nil {
106 return nil, err
107 }
108 }
109 if strings.TrimSpace(diff) == "" {
110 return &ReviewResult{Summary: "No changes to review.", HeadSHA: pr.Head.SHA}, nil
111 }
112
113 dir, err := os.MkdirTemp("", "klaus-pr-review-")
114 if err != nil {
115 return nil, err
116 }
117 defer os.RemoveAll(dir)
118 text, err := runReviewer(ctx, opts.Backend, opts.Model, prReviewSystemPrompt, buildPRReviewPrompt(pr.Title, pr.Body, promptDiff("", diff, maxDiffBytes)), dir)
119 if err != nil {
120 return nil, err
121 }
122 result, err := parseReviewResponse(text)
123 if err != nil {
124 return nil, err
125 }
126 result.HeadSHA = pr.Head.SHA
127 if !opts.Post {
128 return result, nil
129 }
130
131 // Re-check: the lock is per session, and the model run can take minutes.
132 // Stale findings posted after a push would read as unaddressed and dispatch a fix agent.
133 if err := checkHead(ctx, gh, repo, prNumber, pr.Head.SHA); err != nil {
134 return result, err
135 }
136 if err := checkRounds(ctx, gh, repo, prNumber, pr.Head.SHA, opts); err != nil {
137 return result, err
138 }
139 req := buildPRReview(result, DiffLines(diff), Marker{Backend: string(opts.Backend), Model: opts.Model, SHA: pr.Head.SHA})
140 resp, err := gh.APIPostJSON(ctx, "repos/"+repo+"/pulls/"+prNumber+"/reviews", req)
141 if err != nil {
142 return result, fmt.Errorf("posting review: %w", err)
143 }
144 var posted struct {
145 HTMLURL string `json:"html_url"`
146 }
147 _ = json.Unmarshal(resp, &posted)
148 result.ReviewURL = posted.HTMLURL
149 return result, nil
150}
151
152func fetchPR(ctx context.Context, gh *github.GHCLIClient, repo, prNumber string) (*prInfo, error) {
153 out, err := gh.APIGet(ctx, "repos/"+repo+"/pulls/"+prNumber)
154 if err != nil {
155 return nil, fmt.Errorf("fetching PR #%s: %w", prNumber, err)
156 }
157 var pr prInfo
158 if err := json.Unmarshal(out, &pr); err != nil {
159 return nil, fmt.Errorf("parsing PR #%s: %w", prNumber, err)
160 }
161 return &pr, nil
162}
163
164func checkHead(ctx context.Context, gh *github.GHCLIClient, repo, prNumber, sha string) error {
165 pr, err := fetchPR(ctx, gh, repo, prNumber)
166 if err != nil {
167 return err
168 }
169 if pr.Head.SHA != sha {
170 return fmt.Errorf("%w: PR #%s %.7s → %.7s; rerun", ErrHeadMoved, prNumber, sha, pr.Head.SHA)
171 }
172 return nil
173}
174
175// checkRounds refuses a post that would repeat this backend on the same head or exceed opts.MaxRounds, so review → fix → review cannot spin.
176func checkRounds(ctx context.Context, gh *github.GHCLIClient, repo, prNumber, sha string, opts PROptions) error {
177 max := opts.MaxRounds
178 if max <= 0 {
179 max = defaultMaxRounds
180 }
181 out, err := gh.APIGet(ctx, "repos/"+repo+"/pulls/"+prNumber+"/reviews?per_page=100")
182 if err != nil {
183 return fmt.Errorf("listing reviews on PR #%s: %w", prNumber, err)
184 }
185 var reviews []struct {
186 Body string `json:"body"`
187 User struct {
188 Login string `json:"login"`
189 } `json:"user"`
190 }
191 if err := json.Unmarshal(out, &reviews); err != nil {
192 return fmt.Errorf("parsing reviews on PR #%s: %w", prNumber, err)
193 }
194 operator, err := gh.GetAuthenticatedUser(ctx)
195 if err != nil {
196 return err
197 }
198 rounds := 0
199 for _, r := range reviews {
200 m, ok := ParseMarker(r.Body)
201 if !ok || r.User.Login != operator { // others' copied markers neither block nor count
202 continue
203 }
204 if m.SHA == sha && m.Backend == string(opts.Backend) {
205 return fmt.Errorf("%w (%s at %.7s)", ErrAlreadyReviewed, opts.Backend, sha)
206 }
207 rounds++
208 }
209 if rounds >= max {
210 return fmt.Errorf("%w: PR #%s has %d posted cross-reviews (cross_review.max_rounds=%d)", ErrMaxRounds, prNumber, rounds, max)
211 }
212 return nil
213}
214
215type reviewComment struct {
216 Path string `json:"path"`
217 Line int `json:"line"`
218 Side string `json:"side"`
219 Body string `json:"body"`
220}
221
222type reviewRequest struct {
223 CommitID string `json:"commit_id,omitempty"`
224 Body string `json:"body"`
225 Event string `json:"event"`
226 Comments []reviewComment `json:"comments,omitempty"`
227}
228
229// buildPRReview inlines findings on lines shown in the diff and folds the rest into the body.
230func buildPRReview(r *ReviewResult, lines map[string]map[int]bool, m Marker) reviewRequest {
231 req := reviewRequest{CommitID: m.SHA, Event: "COMMENT"}
232 var folded []Finding
233 for _, f := range r.Findings {
234 if p, ok := diffPath(lines, f.File); ok && lines[p][f.Line] {
235 req.Comments = append(req.Comments, reviewComment{
236 Path: p, Line: f.Line, Side: "RIGHT",
237 Body: fmt.Sprintf("**%s** (%s cross-review): %s", strings.ToUpper(f.Severity), m.Backend, f.Description),
238 })
239 continue
240 }
241 folded = append(folded, f)
242 }
243 req.Body = prReviewBody(r, folded, m)
244 return req
245}
246
247// BackendModel names a backend and the model it ran, e.g. "codex gpt-6" or
248// "agy (default model)" when none was set. Reviews, status and the dashboard
249// all use it so they read alike.
250func BackendModel(backend, model string) string {
251 if model == "" {
252 model = "(default model)"
253 }
254 return backend + " " + model
255}
256
257func prReviewBody(r *ReviewResult, folded []Finding, m Marker) string {
258 var b strings.Builder
259 fmt.Fprintf(&b, "**Cross-model review** by %s: a second opinion for the operator, not an approval.\n\n", BackendModel(m.Backend, m.Model))
260 if r.Verdict != "" {
261 fmt.Fprintf(&b, "**Verdict:** %s\n\n", r.Verdict)
262 }
263 if r.Summary != "" {
264 fmt.Fprintf(&b, "**Summary:** %s\n\n", r.Summary)
265 }
266 if len(folded) > 0 {
267 b.WriteString("**Findings not on a diff line:**\n")
268 for _, f := range folded {
269 loc := f.File
270 if loc == "" {
271 loc = "general"
272 } else if f.Line > 0 {
273 loc = fmt.Sprintf("%s:%d", f.File, f.Line)
274 }
275 fmt.Fprintf(&b, "- **%s** `%s`: %s\n", strings.ToUpper(f.Severity), loc, f.Description)
276 }
277 b.WriteString("\n")
278 }
279 b.WriteString(m.String())
280 return b.String()
281}
282
283const prReviewSystemPrompt = `You are a code reviewer giving a second opinion on a pull request written by a different AI model. Judge whether the change does what its title and description claim, and report real problems only. Be concise.
284
285Respond with ONLY a JSON object (no markdown fences) in this exact format:
286{
287 "verdict": "2-4 sentences for the human who approves merges: does the change match its stated intent, what is missing or risky, what to check before approving",
288 "findings": [
289 {"severity": "critical|high|medium|low", "file": "path/in/repo.go", "line": 123, "description": "brief description"}
290 ],
291 "summary": "one sentence summary"
292}
293
294"line" is the line number in the new version of the file and must be an added or context line shown in the diff; use 0 when a finding is not about one line.
295If there are no issues, return an empty "findings" array.`
296
297func buildPRReviewPrompt(title, body, diff string) string {
298 if strings.TrimSpace(body) == "" {
299 body = "(no description)"
300 } else if len(body) > maxPRBodyBytes {
301 body = body[:maxPRBodyBytes] + "\n[... description truncated ...]"
302 }
303 return fmt.Sprintf("Pull request title: %s\n\nPull request description:\n%s\n\n"+
304 "Check whether the diff implements what the title and description claim, and flag anything claimed but missing or changed but unmentioned. Then review it for:\n%s\n\nDiff:\n%s",
305 title, body, reviewChecklist, diff)
306}