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