| 1 | package review |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "encoding/json" |
| 7 | "fmt" |
| 8 | "os" |
| 9 | "os/exec" |
| 10 | "path/filepath" |
| 11 | "strings" |
| 12 | |
| 13 | "the-valley/flow/internal/backend" |
| 14 | "the-valley/flow/internal/git" |
| 15 | ) |
| 16 | |
| 17 | // ReviewConfig configures the peer review agent. |
| 18 | type ReviewConfig struct { |
| 19 | Backend string |
| 20 | Model string // e.g. "haiku" — passed to claude CLI --model flag |
| 21 | MaxFixRounds int // default 2 |
| 22 | HouseRules string // the operator's house rules, added to the reviewer's context |
| 23 | } |
| 24 | |
| 25 | // Finding represents a single review finding. |
| 26 | type Finding struct { |
| 27 | Severity string `json:"severity"` // critical, high, medium, low |
| 28 | File string `json:"file"` |
| 29 | Line int `json:"line"` |
| 30 | Description string `json:"description"` |
| 31 | } |
| 32 | |
| 33 | // ReviewResult holds the complete review output. |
| 34 | type ReviewResult struct { |
| 35 | Findings []Finding `json:"findings"` |
| 36 | Summary string `json:"summary"` |
| 37 | Verdict string `json:"verdict,omitempty"` // PR mode only |
| 38 | // Set by RunPRReview. |
| 39 | HeadSHA string `json:"-"` |
| 40 | ReviewURL string `json:"-"` // posted review, if any |
| 41 | } |
| 42 | |
| 43 | // maxDiffBytes is the maximum diff size we send to the review model. |
| 44 | // Haiku has 200k context; we cap the diff well under that. |
| 45 | const maxDiffBytes = 80_000 |
| 46 | |
| 47 | // ReviewDiff runs a peer review on what HEAD changes since its merge base |
| 48 | // with base. |
| 49 | func ReviewDiff(dir string, cfg ReviewConfig, base string) (*ReviewResult, error) { |
| 50 | if base == "" { |
| 51 | base = "main" |
| 52 | } |
| 53 | diff, err := getDiff(dir, base) |
| 54 | if err != nil { |
| 55 | return nil, fmt.Errorf("getting diff: %w", err) |
| 56 | } |
| 57 | if strings.TrimSpace(diff) == "" { |
| 58 | return &ReviewResult{Summary: "No changes to review."}, nil |
| 59 | } |
| 60 | |
| 61 | return callReviewInDir(dir, promptDiff(dir, diff, maxDiffBytes), cfg) |
| 62 | } |
| 63 | |
| 64 | // promptDiff is a diff of the repository at dir, if any, as a reviewer is |
| 65 | // sent it: text, with any file that isn't text named with its size but left |
| 66 | // out (git.TextDiff), cut to max bytes. |
| 67 | func promptDiff(dir, diff string, max int) string { |
| 68 | diff = git.TextDiff(context.Background(), dir, diff) |
| 69 | if len(diff) > max { |
| 70 | return git.TruncateText(diff, max) + "\n\n[... diff truncated due to size ...]" |
| 71 | } |
| 72 | return diff |
| 73 | } |
| 74 | |
| 75 | // getDiff diffs the committed bytes: the host's git config can neither |
| 76 | // colour the diff nor run an external diff or textconv on what the change |
| 77 | // holds. |
| 78 | func getDiff(dir, base string) (string, error) { |
| 79 | cmd := exec.Command("git", "diff", "--no-color", "--no-ext-diff", "--no-textconv", base+"...HEAD") |
| 80 | cmd.Dir = dir |
| 81 | var out bytes.Buffer |
| 82 | cmd.Stdout = &out |
| 83 | cmd.Stderr = &bytes.Buffer{} |
| 84 | if err := cmd.Run(); err != nil { |
| 85 | return "", err |
| 86 | } |
| 87 | return out.String(), nil |
| 88 | } |
| 89 | |
| 90 | func callReviewAPI(diff string, cfg ReviewConfig) (*ReviewResult, error) { |
| 91 | return callReviewInDir("", diff, cfg) |
| 92 | } |
| 93 | func callReviewInDir(dir, diff string, cfg ReviewConfig) (*ReviewResult, error) { |
| 94 | kind, err := backend.Parse(cfg.Backend) |
| 95 | if err != nil { |
| 96 | return nil, err |
| 97 | } |
| 98 | model := cfg.Model |
| 99 | if model == "" && kind == backend.Claude { |
| 100 | model = "haiku" |
| 101 | } |
| 102 | text, err := runReviewer(context.Background(), kind, model, withHouseRules(reviewSystemPrompt, cfg.HouseRules), buildReviewPrompt(diff), dir) |
| 103 | if err != nil { |
| 104 | return nil, err |
| 105 | } |
| 106 | return parseReviewResponse(text) |
| 107 | } |
| 108 | |
| 109 | // withHouseRules adds the house rules to a reviewer's system prompt. |
| 110 | func withHouseRules(system, rules string) string { |
| 111 | if strings.TrimSpace(rules) == "" { |
| 112 | return system |
| 113 | } |
| 114 | return system + "\n\nThe operator's house rules for all their projects; flag changes that break them:\n\n<house-rules>\n" + strings.TrimSpace(rules) + "\n</house-rules>" |
| 115 | } |
| 116 | |
| 117 | // runReviewer returns one read-only, non-persistent review response. |
| 118 | func runReviewer(ctx context.Context, kind backend.Kind, model, systemPrompt, userPrompt, dir string) (string, error) { |
| 119 | var lastMessage, agyAgent string |
| 120 | if kind == backend.Codex { |
| 121 | tmp, err := os.MkdirTemp("", "klaus-review-") |
| 122 | if err != nil { |
| 123 | return "", err |
| 124 | } |
| 125 | defer os.RemoveAll(tmp) |
| 126 | lastMessage = filepath.Join(tmp, "response.json") |
| 127 | } |
| 128 | if kind == backend.Agy { |
| 129 | var cleanup func() |
| 130 | var err error |
| 131 | agyAgent, cleanup, err = backend.PrepareAgyReadOnly() |
| 132 | if err != nil { |
| 133 | return "", err |
| 134 | } |
| 135 | defer cleanup() |
| 136 | } |
| 137 | argv, err := backend.OneShot(kind, backend.OneShotOptions{ |
| 138 | SystemPrompt: systemPrompt, Model: model, |
| 139 | LastMessage: lastMessage, AgyAgent: agyAgent, |
| 140 | }) |
| 141 | if err != nil { |
| 142 | return "", err |
| 143 | } |
| 144 | cmd := exec.CommandContext(ctx, argv[0], argv[1:]...) |
| 145 | stdin := kind.Stdin(systemPrompt, userPrompt) |
| 146 | if kind == backend.Codex { |
| 147 | stdin = systemPrompt + "\n\n" + userPrompt |
| 148 | } |
| 149 | |
| 150 | cmd.Dir = dir |
| 151 | cmd.Stdin = strings.NewReader(stdin) |
| 152 | var stdout, stderr bytes.Buffer |
| 153 | cmd.Stdout = &stdout |
| 154 | cmd.Stderr = &stderr |
| 155 | if err := cmd.Run(); err != nil { |
| 156 | return "", fmt.Errorf("calling %s CLI: %w; stderr: %s", kind, err, stderr.String()) |
| 157 | } |
| 158 | if lastMessage != "" { |
| 159 | data, err := os.ReadFile(lastMessage) |
| 160 | if err != nil { |
| 161 | return "", fmt.Errorf("reading Codex review response: %w", err) |
| 162 | } |
| 163 | return string(data), nil |
| 164 | } |
| 165 | return stdout.String(), nil |
| 166 | } |
| 167 | |
| 168 | const reviewSystemPrompt = `You are a code reviewer. Review the given git diff for issues. Be concise and focus only on real problems. |
| 169 | |
| 170 | Respond with ONLY a JSON object (no markdown fences) in this exact format: |
| 171 | { |
| 172 | "findings": [ |
| 173 | {"severity": "critical|high|medium|low", "file": "path/to/file.go", "line": 123, "description": "brief description"} |
| 174 | ], |
| 175 | "summary": "one sentence summary" |
| 176 | } |
| 177 | |
| 178 | If there are no issues, return {"findings": [], "summary": "No issues found."}` |
| 179 | |
| 180 | const reviewChecklist = `- Correctness bugs (logic errors, quoting issues, off-by-one) |
| 181 | - Unchecked errors and type assertions |
| 182 | - Security issues (injection, path traversal, unchecked input) |
| 183 | - Race conditions |
| 184 | - Edge cases and nil pointer dereferences` |
| 185 | |
| 186 | func buildReviewPrompt(diff string) string { |
| 187 | return fmt.Sprintf("Review this diff for:\n%s\n\nDiff:\n%s", reviewChecklist, diff) |
| 188 | } |
| 189 | |
| 190 | func parseReviewResponse(text string) (*ReviewResult, error) { |
| 191 | text = strings.TrimSpace(text) |
| 192 | // Strip markdown code fences if present |
| 193 | text = strings.TrimPrefix(text, "```json") |
| 194 | text = strings.TrimPrefix(text, "```") |
| 195 | text = strings.TrimSuffix(text, "```") |
| 196 | text = strings.TrimSpace(text) |
| 197 | |
| 198 | var result ReviewResult |
| 199 | if err := json.Unmarshal([]byte(text), &result); err != nil { |
| 200 | raw := embeddedReviewObject(text) |
| 201 | if raw == "" || json.Unmarshal([]byte(raw), &result) != nil { |
| 202 | return nil, fmt.Errorf("failed to parse review response: %w; response text: %q", err, text) |
| 203 | } |
| 204 | } |
| 205 | |
| 206 | // Normalize severity values |
| 207 | for i := range result.Findings { |
| 208 | result.Findings[i].Severity = strings.ToLower(result.Findings[i].Severity) |
| 209 | } |
| 210 | |
| 211 | return &result, nil |
| 212 | } |
| 213 | |
| 214 | // embeddedReviewObject finds the first JSON object with a findings or summary key in prose-wrapped output; trailing text is ignored. |
| 215 | func embeddedReviewObject(text string) string { |
| 216 | for i := strings.IndexByte(text, '{'); i >= 0; { |
| 217 | dec := json.NewDecoder(strings.NewReader(text[i:])) |
| 218 | var probe map[string]json.RawMessage |
| 219 | if dec.Decode(&probe) == nil && (probe["findings"] != nil || probe["summary"] != nil) { |
| 220 | return text[i : i+int(dec.InputOffset())] |
| 221 | } |
| 222 | next := strings.IndexByte(text[i+1:], '{') |
| 223 | if next < 0 { |
| 224 | break |
| 225 | } |
| 226 | i += 1 + next |
| 227 | } |
| 228 | return "" |
| 229 | } |