gunk-dev/the-valley

review.go

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