diff --git a/README.md b/README.md index 3e6148b..dccb144 100644 --- a/README.md +++ b/README.md @@ -170,6 +170,8 @@ The CLI is designed to be driven by schedulers such as Divmora Code Review Conso Every review rates the change from **1 to 100** on **Quality**, **Security** and **Maintainability**. The scores appear in the summary, the CLI output and the JSON result. They're capped by the findings: a critical security finding caps Security at 40, a major one at 70. +The walkthrough step gives the scores. A field the model gets wrong there (a string where a list belongs, say) is ignored and the rest kept. If the walkthrough fails or gives no scores, the review has **no scores** rather than guessed ones: the JSON result leaves `scores` out and says why in `scores_note`, labels are left as they are, and the previous review's scores are kept for the next one to anchor to. + With `--post --score-labels` the scores are also set as labels on the PR/MR, replacing earlier scores: - GitLab: scoped labels, `Quality Score::85`; - GitHub: `Quality Score: 85`. diff --git a/internal/app/runner_test.go b/internal/app/runner_test.go index ebde6ba..b1daf2f 100644 --- a/internal/app/runner_test.go +++ b/internal/app/runner_test.go @@ -366,7 +366,8 @@ func TestCommitStatusLifecycle(t *testing.T) { if len(gh.statuses) != 2 || gh.statuses[0]["state"] != "pending" || gh.statuses[1]["state"] != "success" || gh.statuses[1]["sha"] != "head1" { t.Fatalf("statuses = %v", gh.statuses) } - if d, _ := gh.statuses[1]["description"].(string); !strings.HasPrefix(d, "Reviewed: 1 comment · Quality") { + // The fake model answers the walkthrough with review JSON: no scores, none guessed. + if d, _ := gh.statuses[1]["description"].(string); d != "Reviewed: 1 comment" { t.Errorf("success description = %q", d) } diff --git a/internal/review/engine.go b/internal/review/engine.go index b575dd0..560dc53 100644 --- a/internal/review/engine.go +++ b/internal/review/engine.go @@ -137,15 +137,22 @@ type Result struct { // ScoreChanges are the scores that moved from the previous review, // with why (empty without a previous review to anchor to). ScoreChanges []ScoreChange `json:"score_changes,omitempty"` + // ScoresNote says why Scores is empty when the review gave none (for + // example, the walkthrough failed). No scores are made up then. + ScoresNote string `json:"scores_note,omitempty"` // Verification reports the second-pass check of the findings. - Verification *Verification `json:"verification,omitempty"` - TooLarge bool `json:"too_large,omitempty"` - Model string `json:"model"` - Usage llm.Usage `json:"usage"` - Duration time.Duration `json:"duration"` - HeadSHA string `json:"head_sha"` - BaseSHA string `json:"base_sha"` - IncrementalOf string `json:"incremental_of,omitempty"` + Verification *Verification `json:"verification,omitempty"` + TooLarge bool `json:"too_large,omitempty"` + Model string `json:"model"` + Usage llm.Usage `json:"usage"` + Duration time.Duration `json:"duration"` + + // carry are the previous review's scores, kept in the summary's state + // when this review gave none, so the next review still anchors to them. + carry *carriedScores + HeadSHA string `json:"head_sha"` + BaseSHA string `json:"base_sha"` + IncrementalOf string `json:"incremental_of,omitempty"` } // allFindings are the new, overflow and repeated findings: everything still @@ -1048,8 +1055,9 @@ func (e *Engine) walkthrough(ctx context.Context, res *Result, in Input, files [ MaxTokens: 4096, }) var out summaryOutput + var dropped []string if err == nil { - err = json.Unmarshal(resp.JSON, &out) + out, dropped, err = decodeSummary(resp.JSON) } if err != nil { if !errors.Is(err, context.Canceled) { @@ -1057,11 +1065,16 @@ func (e *Engine) walkthrough(ctx context.Context, res *Result, in Input, files [ } res.Summary = fmt.Sprintf("Reviewed %d file(s).", len(res.Reviewed)) res.Cohorts = defaultCohorts(paths, res.FileSummaries) - sc := fallbackScores(res.allFindings()) - res.Scores = &sc - e.anchor(res, in, nil) + e.noScores(res, in, "the walkthrough failed") return } + if len(dropped) > 0 { + log := e.Logger + if log == nil { + log = slog.Default() + } + log.Warn("walkthrough: ignored fields the model got wrong", "fields", dropped) + } res.Usage.InputTokens += resp.Usage.InputTokens res.Usage.OutputTokens += resp.Usage.OutputTokens res.Usage.CachedInputTokens += resp.Usage.CachedInputTokens @@ -1086,17 +1099,26 @@ func (e *Engine) walkthrough(ctx context.Context, res *Result, in Input, files [ res.Highlights = append(res.Highlights, Highlight{Type: h.Type, Items: items}) } } - all := res.allFindings() - if out.Scores.Quality == 0 && out.Scores.Security == 0 && out.Scores.Maintainability == 0 { - sc := fallbackScores(all) - res.Scores = &sc - } else { - sc := finalScores(Scores{Quality: int(out.Scores.Quality), Security: int(out.Scores.Security), Maintainability: int(out.Scores.Maintainability)}, all) - res.Scores = &sc + if out.Scores.Quality < 1 || out.Scores.Security < 1 || out.Scores.Maintainability < 1 { + e.noScores(res, in, "the walkthrough gave no scores") + return } + sc := finalScores(Scores{Quality: int(out.Scores.Quality), Security: int(out.Scores.Security), Maintainability: int(out.Scores.Maintainability)}, res.allFindings()) + res.Scores = &sc e.anchor(res, in, map[string]string{"quality": out.ScoreReasons.Quality, "security": out.ScoreReasons.Security, "maintainability": out.ScoreReasons.Maintainability}) } +// noScores leaves the review without scores rather than guessing them +// from the findings (a guess dragged quality to 1 on large changes). The +// previous review's scores are kept in the state for the next review. +func (e *Engine) noScores(res *Result, in Input, why string) { + res.Scores, res.ScoresNote = nil, why + if in.PrevScores != nil { + res.ScoresNote += "; scores are unchanged from the last review" + res.carry = &carriedScores{Scores: *in.PrevScores, SHA: in.PrevScoresSHA, Open: in.PrevOpen} + } +} + // anchor moves res.Scores from the previous review's scores only as far // as the change supports (see anchorScores). The same commit reviewed // again keeps the previous scores. diff --git a/internal/review/engine_test.go b/internal/review/engine_test.go index 3739a63..8ed8d75 100644 --- a/internal/review/engine_test.go +++ b/internal/review/engine_test.go @@ -397,7 +397,7 @@ func TestVerificationPass(t *testing.T) { } } -func TestVerifyDisabledAndFallbackScores(t *testing.T) { +func TestVerifyDisabledAndNoGuessedScores(t *testing.T) { fake := &scripted{review: func(llm.Request) (string, error) { return `{"files":[],"comments":[{"path":"main.go","start_line":4,"end_line":4,"severity":"critical","category":"security","title":"sqli","body":"x","confidence":0.9}]}`, nil }} @@ -415,9 +415,9 @@ func TestVerifyDisabledAndFallbackScores(t *testing.T) { t.Error("verify: false must skip the verification call") } } - // No walkthrough scripted, so scores come from findings: critical security caps at 40. - if res.Scores == nil || res.Scores.Security > 40 || res.Scores.Quality < 90 { - t.Errorf("fallback scores = %+v", res.Scores) + // No walkthrough scripted: no scores are guessed from the findings. + if res.Scores != nil || res.ScoresNote == "" { + t.Errorf("scores without a walkthrough = %+v (%q)", res.Scores, res.ScoresNote) } } @@ -542,7 +542,7 @@ func TestPostedBefore(t *testing.T) { func TestRepeatedFindingsStillCountForScores(t *testing.T) { fake := &scripted{review: func(llm.Request) (string, error) { return `{"files":[],"comments":[{"path":"main.go","start_line":4,"end_line":4,"severity":"critical","category":"security","title":"SQL injection in search query","body":"x","confidence":0.9}]}`, nil - }} + }, summary: `{"summary":"s","cohorts":[],"effort":1,"scores":{"quality":95,"security":95,"maintainability":95}}`} off := false lim := limits() lim.Verify = &off diff --git a/internal/review/prompts.go b/internal/review/prompts.go index c586511..b5153de 100644 --- a/internal/review/prompts.go +++ b/internal/review/prompts.go @@ -1,7 +1,10 @@ package review import ( + "encoding/json" "fmt" + "reflect" + "sort" "strconv" "strings" @@ -254,6 +257,53 @@ type summaryOutput struct { } `json:"score_reasons"` } +// decodeSummary reads the walkthrough leniently: a field the model got +// wrong (a string where a list or object belongs) is dropped, and listed +// in dropped, instead of failing the whole walkthrough. A list or object +// sent as a JSON-encoded string is decoded. err is set only when the +// output isn't a JSON object at all. +func decodeSummary(b []byte) (out summaryOutput, dropped []string, err error) { + var fields map[string]json.RawMessage + if err := json.Unmarshal(b, &fields); err != nil { + return out, nil, err + } + targets := map[string]any{ + "summary": &out.Summary, "cohorts": &out.Cohorts, "effort": &out.Effort, "poem": &out.Poem, + "title": &out.Title, "title_ok": &out.TitleOK, "description_check": &out.DescriptionCheck, + "highlights": &out.Highlights, "scores": &out.Scores, "score_reasons": &out.ScoreReasons, + } + names := make([]string, 0, len(fields)) + for k := range fields { + names = append(names, k) + } + sort.Strings(names) + for _, k := range names { + t, ok := targets[k] + if !ok { + continue + } + raw := fields[k] + if json.Unmarshal(raw, t) == nil { + continue + } + var inner string // "[{...}]": the value encoded once more + if json.Unmarshal(raw, &inner) == nil { + if inner = strings.TrimSpace(inner); inner == "" || json.Unmarshal([]byte(inner), t) == nil { + continue + } + } + reset(t) + dropped = append(dropped, k) + } + return out, dropped, nil +} + +// reset zeroes what a failed decode may have half filled. +func reset(t any) { + v := reflect.ValueOf(t).Elem() + v.Set(reflect.Zero(v.Type())) +} + const chatSystem = `You are a code review assistant replying to a question on a pull request. Answer using the PR diff and context provided. Be concise and concrete; cite files and line numbers. If the answer is not in the provided context, say so instead of guessing. diff --git a/internal/review/render.go b/internal/review/render.go index c325d25..94c0d11 100644 --- a/internal/review/render.go +++ b/internal/review/render.go @@ -232,6 +232,8 @@ func SummaryMarkdown(res *Result, opts SummaryOptions) string { } b.WriteString("Since the last review: " + strings.Join(parts, " · ") + "\n\n") } + } else if res.ScoresNote != "" { + b.WriteString("_No scores this time: " + escapeInline(res.ScoresNote) + "._\n\n") } if res.Effort > 0 { fmt.Fprintf(&b, "## Estimated code review effort\n\n🎯 %d (%s) | ⏱️ %s minutes\n\n", res.Effort, effortLabel[res.Effort], effortMinutes[res.Effort]) @@ -326,6 +328,9 @@ func SummaryMarkdown(res *Result, opts SummaryOptions) string { state := State{FileSummaries: res.FileSummaries} if res.Scores != nil { state.Scores, state.ScoresSHA, state.OpenFindings = res.Scores, res.HeadSHA, OpenFindings(res.allFindings()) + } else if c := res.carry; c != nil { + sc := c.Scores + state.Scores, state.ScoresSHA, state.OpenFindings = &sc, c.SHA, c.Open } st, _ := json.Marshal(state) b.WriteString(vcs.StateTag(st) + "\n") diff --git a/internal/review/scores.go b/internal/review/scores.go index 2f4f1fc..f9e6eb6 100644 --- a/internal/review/scores.go +++ b/internal/review/scores.go @@ -68,27 +68,6 @@ func scoreCaps(fs []Finding) Scores { return c } -// fallbackScores derives scores from findings when the model gives none. -func fallbackScores(fs []Finding) Scores { - s := Scores{Quality: 95, Security: 100, Maintainability: 95} - penalty := map[Severity]int{Critical: 45, Major: 20, Minor: 6, Nitpick: 1} - for _, f := range fs { - if f.Kind == KindQuestion { - continue - } - p := penalty[f.Severity] - switch f.Category { - case "security": - s.Security -= p - case "maintainability", "style", "docs": - s.Maintainability -= p - default: - s.Quality -= p - } - } - return clampScores(s, scoreCaps(fs)) -} - // scoreFloors raises scores the findings do not support: a dimension with no // remaining issue of at least minor severity (questions and findings the // verifier removed do not count) scores at least 85, so a disputed or @@ -270,3 +249,10 @@ func abs(v int) int { } return v } + +// carriedScores are the previous review's scores, passed on unchanged. +type carriedScores struct { + Scores Scores + SHA string + Open map[string]int +} diff --git a/internal/review/walkthrough_test.go b/internal/review/walkthrough_test.go new file mode 100644 index 0000000..8408e0a --- /dev/null +++ b/internal/review/walkthrough_test.go @@ -0,0 +1,95 @@ +package review + +import ( + "context" + "encoding/base64" + "encoding/json" + "regexp" + "strings" + "testing" + + "github.com/divmora/code-review-bot/internal/llm" + "github.com/divmora/code-review-bot/pkg/vcs" +) + +// Issue #14: a string where the schema wants a list or object dropped the +// whole walkthrough, and scores were then guessed from the findings. +func TestDecodeSummaryLenient(t *testing.T) { + out, dropped, err := decodeSummary([]byte(`{ + "summary": "Adds retries", + "cohorts": "main.go and util.go", + "highlights": "[{\"type\":\"Bug Fixes\",\"items\":[\"retry on 503\"]}]", + "score_reasons": "quality went up", + "effort": "2", + "scores": {"quality": 80, "security": "95", "maintainability": 88} + }`)) + if err != nil { + t.Fatal(err) + } + if strings.Join(dropped, ",") != "cohorts,score_reasons" { + t.Errorf("dropped = %v", dropped) + } + if out.Summary != "Adds retries" || out.Effort != 2 || out.Cohorts != nil { + t.Errorf("out = %+v", out) + } + if len(out.Highlights) != 1 || out.Highlights[0].Items[0] != "retry on 503" { + t.Errorf("a list sent as a JSON string is decoded: %+v", out.Highlights) + } + if out.Scores.Quality != 80 || out.Scores.Security != 95 || out.Scores.Maintainability != 88 { + t.Errorf("scores = %+v", out.Scores) + } + if _, _, err := decodeSummary([]byte(`"not an object"`)); err == nil { + t.Error("a non-object fails") + } +} + +func TestWalkthroughWithAStringField(t *testing.T) { + fake := &scripted{review: func(llm.Request) (string, error) { + return `{"files":[],"comments":[]}`, nil + }, summary: `{"summary":"s","cohorts":"all files","effort":1,"scores":{"quality":90,"security":100,"maintainability":90}}`} + res, err := (&Engine{LLM: fake, Limits: limits(), Logger: quiet}).Run(context.Background(), Input{Files: testFiles(t)[:1], Repo: defaults()}) + if err != nil { + t.Fatal(err) + } + if len(res.Errors) != 0 { + t.Errorf("one bad field doesn't make the review partial: %v", res.Errors) + } + if res.Scores == nil || res.Scores.Quality != 90 || len(res.Cohorts) == 0 { + t.Errorf("the rest of the walkthrough is kept: %+v %+v", res.Scores, res.Cohorts) + } +} + +func TestNoScoresKeepsThePreviousInTheState(t *testing.T) { + fake := &scripted{review: func(llm.Request) (string, error) { + return `{"files":[],"comments":[{"path":"main.go","start_line":4,"end_line":4,"severity":"major","category":"bug","title":"t","body":"x","confidence":0.9}]}`, nil + }, summary: `not json`} + off := false + lim := limits() + lim.Verify = &off + files := testFiles(t)[:1] + files[0].Hunks[0].Lines[6].Text = "\tx := 3" + prev := &Scores{Quality: 70, Security: 95, Maintainability: 85} + res, err := (&Engine{LLM: fake, Limits: lim, Logger: quiet}).Run(context.Background(), Input{ + Files: files, Repo: defaults(), PR: &vcs.PR{HeadSHA: "new"}, + PrevScores: prev, PrevScoresSHA: "old", PrevOpen: map[string]int{"quality": 1}, + }) + if err != nil { + t.Fatal(err) + } + if res.Scores != nil || !strings.Contains(res.ScoresNote, "unchanged from the last review") { + t.Fatalf("scores = %+v, note %q", res.Scores, res.ScoresNote) + } + body := SummaryMarkdown(res, SummaryOptions{BotName: "codereview"}) + if strings.Contains(body, "## Scores") || !strings.Contains(body, "_No scores this time:") { + t.Errorf("summary:\n%s", body) + } + m := regexp.MustCompile(``).FindStringSubmatch(body) + if m == nil { + t.Fatal("no state") + } + raw, _ := base64.StdEncoding.DecodeString(m[1]) + var st State + if json.Unmarshal(raw, &st) != nil || st.Scores == nil || *st.Scores != *prev || st.ScoresSHA != "old" || st.OpenFindings["quality"] != 1 { + t.Errorf("the previous scores are carried for the next review: %s", raw) + } +}