gunk-dev/the-valley

pr.go

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