-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreviewer.go
More file actions
410 lines (367 loc) · 10.8 KB
/
reviewer.go
File metadata and controls
410 lines (367 loc) · 10.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
package sight
import (
"context"
"fmt"
"path/filepath"
"sort"
"strings"
"sync"
"time"
"github.com/GrayCodeAI/sight/internal/comment"
gitctx "github.com/GrayCodeAI/sight/internal/context"
"github.com/GrayCodeAI/sight/internal/diff"
"github.com/GrayCodeAI/sight/internal/output"
"github.com/GrayCodeAI/sight/internal/review"
)
// Reviewer is a reusable code reviewer. Create one with NewReviewer and call
// Review multiple times. It is safe for concurrent use.
type Reviewer struct {
cfg *config
}
// NewReviewer creates a configured Reviewer.
func NewReviewer(opts ...Option) *Reviewer {
return &Reviewer{cfg: buildConfig(opts)}
}
// Review parses the diff, builds context, and runs multi-concern analysis.
func (r *Reviewer) Review(ctx context.Context, rawDiff string) (*Result, error) {
if ctx.Err() != nil {
return nil, ErrContextCancelled
}
if r.cfg.provider == nil {
return nil, ErrNoProvider
}
if rawDiff == "" {
return nil, ErrEmptyDiff
}
files := diff.Parse(rawDiff)
if len(files) == 0 {
return &Result{Report: "No reviewable changes found."}, nil
}
// Normalize file paths
for i := range files {
files[i].Path = filepath.Clean(files[i].Path)
}
// Filter excluded files before sending to LLM
if len(r.cfg.exclude) > 0 {
files = filterFiles(files, r.cfg.exclude)
if len(files) == 0 {
return &Result{Report: "All changed files matched exclude patterns."}, nil
}
}
// Gather git context if enabled
var gitContextStr string
if r.cfg.gitContext {
var filePaths []string
for _, f := range files {
if f.Path != "" {
filePaths = append(filePaths, f.Path)
}
}
contexts := gitctx.Enrich(filePaths)
gitContextStr = gitctx.FormatContext(contexts)
}
concerns := review.BuildConcerns(r.cfg.concerns)
// Append custom concerns loaded from .sight/checks/ markdown files
if len(r.cfg.customConcerns) > 0 {
concerns = append(concerns, r.cfg.customConcerns...)
}
var (
mu sync.Mutex
allFindings []Finding
tokensUsed int
durations = make(map[string]time.Duration)
llmErrors []string
)
// Token budget: estimate prompt size and chunk if needed
maxPromptTokens := r.cfg.maxTokens * 4 // assume 4:1 input:output ratio
runConcern := func(concern review.Concern) {
start := time.Now()
chunks := review.ChunkFiles(files, concern, r.cfg.contextLines, maxPromptTokens)
var concernFindings []review.Finding
var concernTokens int
var concernErrors []string
for _, chunk := range chunks {
prompt := review.BuildPromptEnhanced(concern, chunk, r.cfg.contextLines)
if gitContextStr != "" {
prompt += gitContextStr
}
systemPrompt := review.SystemPrompt(concern)
if r.cfg.projectRules != "" {
systemPrompt += "\n\n## Project Rules\n\nThe following project-specific rules and coding standards MUST be respected:\n\n" + r.cfg.projectRules
}
resp, err := r.cfg.provider.Chat(ctx, []Message{
{Role: "user", Content: prompt},
}, ChatOpts{
Model: r.cfg.model,
MaxTokens: r.cfg.maxTokens,
Temperature: 0.1,
System: systemPrompt,
})
if err != nil {
concernErrors = append(concernErrors, fmt.Sprintf("[%s] %v", concern.Name, err))
continue
}
parsed := review.ParseResponse(resp.Content, concern.Name)
concernFindings = append(concernFindings, parsed...)
concernTokens += resp.TokensUsed
}
mu.Lock()
allFindings = append(allFindings, toPublicFindings(concernFindings)...)
tokensUsed += concernTokens
durations[concern.Name] = time.Since(start)
llmErrors = append(llmErrors, concernErrors...)
mu.Unlock()
}
if r.cfg.parallel && len(concerns) > 1 {
var wg sync.WaitGroup
for _, concern := range concerns {
wg.Add(1)
go func(c review.Concern) {
defer wg.Done()
runConcern(c)
}(concern)
}
wg.Wait()
} else {
for _, concern := range concerns {
runConcern(concern)
}
}
allFindings = dedup(allFindings)
// Self-reflection pass: validate findings with a second LLM call
if r.cfg.reflection && len(allFindings) > 0 && ctx.Err() == nil {
allFindings = r.reflect(ctx, allFindings, rawDiff, &tokensUsed)
}
sort.Slice(allFindings, func(i, j int) bool {
if allFindings[i].Severity != allFindings[j].Severity {
return allFindings[i].Severity > allFindings[j].Severity
}
if allFindings[i].File != allFindings[j].File {
return allFindings[i].File < allFindings[j].File
}
return allFindings[i].Line < allFindings[j].Line
})
commentInputs := make([]comment.FindingInput, len(allFindings))
for i, f := range allFindings {
commentInputs[i] = comment.FindingInput{
Concern: f.Concern,
Severity: int(f.Severity),
File: f.File,
Line: f.Line,
EndLine: f.EndLine,
Message: f.Message,
Fix: f.Fix,
Reasoning: f.Reasoning,
}
}
comments := comment.MapToInlineFiltered(commentInputs, files, r.cfg.filterMode)
bySev := make(map[Severity]int)
byConcern := make(map[string]int)
for _, f := range allFindings {
bySev[f.Severity]++
byConcern[f.Concern]++
}
result := &Result{
Findings: allFindings,
Comments: toPublicComments(comments),
Stats: Stats{
FilesReviewed: len(files),
HunksAnalyzed: countHunks(files),
FindingsTotal: len(allFindings),
BySeverity: bySev,
ByConcern: byConcern,
TokensUsed: tokensUsed,
DurationPerConcern: durations,
},
FailOn: r.cfg.failOn,
}
outputFindings := make([]output.Finding, len(allFindings))
for i, f := range allFindings {
outputFindings[i] = output.Finding{
Concern: f.Concern,
Severity: int(f.Severity),
File: f.File,
Line: f.Line,
EndLine: f.EndLine,
Message: f.Message,
Fix: f.Fix,
Reasoning: f.Reasoning,
CWE: f.CWE,
}
}
outputStats := output.Stats{
FilesReviewed: result.Stats.FilesReviewed,
HunksAnalyzed: result.Stats.HunksAnalyzed,
FindingsTotal: result.Stats.FindingsTotal,
BySeverity: make(map[int]int),
ByConcern: result.Stats.ByConcern,
TokensUsed: result.Stats.TokensUsed,
DurationPerConcern: result.Stats.DurationPerConcern,
}
for sev, count := range bySev {
outputStats.BySeverity[int(sev)] = count
}
result.Report = output.FormatTerminal(outputFindings, outputStats)
// Include LLM errors in the report if any occurred
if len(llmErrors) > 0 {
result.Report += "\n\nLLM provider errors (" + fmt.Sprintf("%d", len(llmErrors)) + "):\n"
for _, e := range llmErrors {
result.Report += " - " + e + "\n"
}
}
return result, nil
}
// ReviewFiles reviews a set of file changes with explicit content.
func (r *Reviewer) ReviewFiles(ctx context.Context, files []FileChange) (*Result, error) {
if r.cfg.provider == nil {
return nil, ErrNoProvider
}
inputs := make([]diff.FileChangeInput, len(files))
for i, f := range files {
inputs[i] = diff.FileChangeInput{
Path: f.Path,
OldPath: f.OldPath,
Diff: f.Diff,
Content: f.Content,
}
}
combined := diff.CombineFileChanges(inputs)
return r.Review(ctx, combined)
}
func toPublicFindings(internal []review.Finding) []Finding {
out := make([]Finding, len(internal))
for i, f := range internal {
// Prefer LLM-provided CWE; fall back to keyword-based MatchCWE.
cwe := f.CWE
if cwe == "" {
cwe = review.MatchCWE(f.Message, f.Fix)
}
out[i] = Finding{
Concern: f.Concern,
Severity: Severity(f.Severity),
File: f.File,
Line: f.Line,
EndLine: f.EndLine,
Message: f.Message,
Fix: f.Fix,
Reasoning: f.Reasoning,
CWE: cwe,
}
}
return out
}
func toPublicComments(internal []comment.Inline) []InlineComment {
out := make([]InlineComment, len(internal))
for i, c := range internal {
out[i] = InlineComment{
Path: c.Path,
StartLine: c.StartLine,
EndLine: c.EndLine,
Body: c.Body,
Suggestion: c.Suggestion,
}
}
return out
}
func dedup(findings []Finding) []Finding {
type key struct {
file string
line int
concern string
message string
}
seen := make(map[key]bool)
var result []Finding
for _, f := range findings {
// Use file+line+concern+message for unique identification.
// If two different concerns produce the exact same message for the same
// location, keep only the first (higher severity wins due to sort order).
k := key{file: f.File, line: f.Line, concern: f.Concern, message: f.Message}
// Also check without concern for cross-concern dedup of identical findings
kNoConcern := key{file: f.File, line: f.Line, message: f.Message}
if seen[k] || seen[kNoConcern] {
continue
}
seen[k] = true
seen[kNoConcern] = true
result = append(result, f)
}
return result
}
func countHunks(files []diff.File) int {
total := 0
for _, f := range files {
total += len(f.Hunks)
}
return total
}
// filterFiles removes files whose paths match any of the exclude patterns.
// Patterns support exact basename matching and filepath.Match-style globs.
func filterFiles(files []diff.File, patterns []string) []diff.File {
var result []diff.File
for _, f := range files {
if !matchesExclude(f.Path, patterns) {
result = append(result, f)
}
}
return result
}
// matchesExclude checks if a file path matches any exclusion pattern.
// It checks both the full path and the basename against each pattern.
func matchesExclude(path string, patterns []string) bool {
base := filepath.Base(path)
for _, pattern := range patterns {
// Check if the pattern contains a path separator — if so, match
// against the full path; otherwise match against the basename.
if strings.Contains(pattern, "/") {
if matched, _ := filepath.Match(pattern, path); matched {
return true
}
} else {
// Exact basename match
if base == pattern {
return true
}
// Glob match on basename
if matched, _ := filepath.Match(pattern, base); matched {
return true
}
}
}
return false
}
// reflect runs the self-reflection pass to validate findings.
func (r *Reviewer) reflect(ctx context.Context, findings []Finding, rawDiff string, tokensUsed *int) []Finding {
internalFindings := make([]review.Finding, len(findings))
for i, f := range findings {
internalFindings[i] = review.Finding{
Concern: f.Concern,
Severity: review.Severity(f.Severity),
File: f.File,
Line: f.Line,
EndLine: f.EndLine,
Message: f.Message,
Fix: f.Fix,
Reasoning: f.Reasoning,
}
}
prompt := review.BuildReflectPrompt(internalFindings, rawDiff)
resp, err := r.cfg.provider.Chat(ctx, []Message{
{Role: "user", Content: prompt},
}, ChatOpts{
Model: r.cfg.model,
MaxTokens: r.cfg.maxTokens,
Temperature: 0.1,
System: review.ReflectSystemPrompt,
})
if err != nil {
return findings
}
*tokensUsed += resp.TokensUsed
reflections := review.ParseReflectResponse(resp.Content)
if len(reflections) == 0 {
return findings
}
validated := review.ApplyReflectionWithScore(internalFindings, reflections, r.cfg.minScore)
return toPublicFindings(validated)
}