gunk-dev/the-valley

pre_review.go

source6a6791929c36main's published tip history
8.3 KiB
1package cmd
2
3import (
4 "encoding/json"
5 "fmt"
6 "io"
7 "os"
8 "strings"
9 "time"
10
11 "the-valley/flow/internal/backend"
12 "the-valley/flow/internal/config"
13 "the-valley/flow/internal/event"
14 "the-valley/flow/internal/flowenv"
15 "the-valley/flow/internal/review"
16 "the-valley/flow/internal/stream"
17 "github.com/spf13/cobra"
18)
19
20var preReviewCmd = &cobra.Command{
21 Use: "_pre-review",
22 Short: "Run pre-PR linting, peer review and prose rewrites",
23 Hidden: true,
24 RunE: func(cmd *cobra.Command, args []string) (err error) {
25 dir, _ := cmd.Flags().GetString("dir")
26 if dir == "" {
27 var err error
28 dir, err = os.Getwd()
29 if err != nil {
30 return fmt.Errorf("getting working directory: %w", err)
31 }
32 }
33
34 cfg, err := config.Load(dir)
35 if err != nil {
36 return fmt.Errorf("loading config: %w", err)
37 }
38
39 // forbidden_terms is host config, so a repo's pre_review.enabled
40 // doesn't turn its check off.
41 forbidden, err := forbiddenTermsFor(cfg, dir, "")
42 if err != nil {
43 return err
44 }
45 if !cfg.PreReviewEnabled() && len(forbidden) == 0 {
46 fmt.Println("Pre-review is disabled in config.")
47 return nil
48 }
49
50 check := startPreReviewCheck()
51 defer func() {
52 if err != nil {
53 check.finish(false, map[string]interface{}{"error": errorLine(err)})
54 }
55 }()
56
57 fmt.Println("=== Pre-PR Review ===")
58 fmt.Println()
59
60 // Every pass reads what HEAD changes since its merge base with the
61 // default branch as origin last held it, which the worktree started
62 // from, so a local default branch behind origin's adds no landed
63 // commits to what is reviewed.
64 base := defaultBranchRef(dir, cfg.DefaultBranch)
65
66 // Forbidden terms go first, so a diff that adds one is never sent
67 // to the peer reviewer, which then reviews the diff they checked.
68 if len(forbidden) > 0 {
69 fmt.Println("Forbidden terms:")
70 hits, err := scanForbiddenTerms(dir, base, "HEAD", forbidden)
71 if err != nil {
72 return fmt.Errorf("checking forbidden terms: %w", err)
73 }
74 printForbiddenTerms(os.Stdout, hits)
75 fmt.Println()
76 if len(hits) > 0 {
77 check.finish(false, map[string]interface{}{"forbidden_terms": len(hits)})
78 fmt.Println("Forbidden terms added — PR creation should be blocked.")
79 os.Exit(1)
80 }
81 if !cfg.PreReviewEnabled() {
82 check.finish(true, nil)
83 fmt.Println("Pre-review is disabled in config; only forbidden terms were checked.")
84 return nil
85 }
86 }
87
88 // Run linters
89 linters := cfg.PreReviewLinters()
90 lintFailed := false
91 if len(linters) > 0 {
92 fmt.Println("Linters:")
93 results, err := review.RunLinters(dir, linters)
94 if err != nil {
95 return fmt.Errorf("running linters: %w", err)
96 }
97 for _, r := range results {
98 if r.Passed {
99 fmt.Printf(" ✓ %s\n", r.Command)
100 } else {
101 lintFailed = true
102 // Count issues from output lines
103 lines := strings.Split(strings.TrimSpace(r.Output), "\n")
104 count := 0
105 for _, l := range lines {
106 if strings.TrimSpace(l) != "" {
107 count++
108 }
109 }
110 fmt.Printf(" ✗ %s (%d issues)\n", r.Command, count)
111 // Print up to 10 lines of output indented
112 for i, line := range lines {
113 if i >= 10 {
114 fmt.Printf(" ... and %d more\n", count-10)
115 break
116 }
117 if strings.TrimSpace(line) != "" {
118 fmt.Printf(" %s\n", line)
119 }
120 }
121 }
122 }
123 fmt.Println()
124 }
125
126 // Run peer review with a different model family than the worker's.
127 authorName := flowenv.Backend.Get()
128 if authorName == "" {
129 selected, err := resolveAgentBackend(cmd, cfg)
130 if err != nil {
131 return err
132 }
133 authorName = string(selected)
134 }
135 author, err := backend.Parse(authorName)
136 if err != nil {
137 return err
138 }
139 kind, model, err := review.ChooseReviewer(author, cfg)
140 if err != nil {
141 return err
142 }
143 fmt.Printf("Peer Review (reviewer: %s; author: %s):\n", review.BackendModel(string(kind), model), author)
144 check.data["reviewer"] = string(kind)
145 check.data["lint_ms"] = time.Since(check.start).Milliseconds()
146 reviewStart := time.Now()
147 reg, err := registryUnlessConflict()
148 if err != nil {
149 return err
150 }
151 houseRules := loadHouseRules(cmd.Context(), dir, cfg, reg, cmd.ErrOrStderr()).Text
152 printProse := startProsePass(cmd.Context(), dir, base, cfg, author, houseRules)
153 result, err := review.ReviewDiff(dir, review.ReviewConfig{
154 Backend: string(kind),
155 Model: model,
156 HouseRules: houseRules,
157 }, base)
158 if err != nil {
159 printProse(os.Stdout)
160 return fmt.Errorf("running peer review: %w", err)
161 }
162 printFindings(os.Stdout, result.Findings)
163 fmt.Println()
164 printProse(os.Stdout)
165
166 // Determine if we should block
167 blockOn := cfg.PreReviewBlockOn()
168 blockSeverities := severitiesAtOrAbove(blockOn)
169 blockCount := 0
170 for _, f := range result.Findings {
171 if blockSeverities[f.Severity] {
172 blockCount++
173 }
174 }
175
176 // os.Exit skips deferred calls, so the check ends first.
177 check.finish(!lintFailed && blockCount == 0, map[string]interface{}{
178 "review_ms": time.Since(reviewStart).Milliseconds(),
179 "findings": len(result.Findings),
180 "blocking": blockCount,
181 "lint_failed": lintFailed,
182 })
183
184 if lintFailed {
185 fmt.Println("Lint failures detected — PR creation should be blocked.")
186 os.Exit(1)
187 }
188
189 if blockCount > 0 {
190 label := "finding"
191 if blockCount > 1 {
192 label = "findings"
193 }
194 fmt.Printf("%d %s %s — PR creation should be blocked.\n", blockCount, blockOn+"+", label)
195 os.Exit(1)
196 }
197
198 fmt.Println("All checks passed.")
199 return nil
200 },
201}
202
203// preReviewCheck reports a _pre-review run as a check of the run whose pane
204// it runs in (flowenv.RunID): check:started when it starts, check:completed when
205// it finishes. On a sandbox host (flowenv.RunEvents) it prints check:completed in
206// its output instead, for the pane's _format-stream to record. Outside a
207// run's pane it reports nothing.
208type preReviewCheck struct {
209 run *paneRun
210 report io.Writer // where a sandbox run's check is printed; nil otherwise
211 start time.Time
212 data map[string]interface{}
213 started bool
214 done bool
215}
216
217func startPreReviewCheck() *preReviewCheck {
218 c := &preReviewCheck{start: time.Now()}
219 c.data = map[string]interface{}{"kind": event.CheckPreReview, "command": "klaus _pre-review", "source": "pre-review", "started_at": eventTime(c.start)}
220 if flowenv.RunID.Get() != "" && flowenv.RunEvents.Get() == runEventsOutput {
221 c.report = os.Stdout
222 return c
223 }
224 c.run = currentPaneRun()
225 if c.run != nil && c.run.state != nil {
226 c.run.emit(event.CheckStarted, c.data)
227 c.started = true
228 }
229 return c
230}
231
232// finish emits check:completed, once, with extra added to the check's data.
233// A run launch hadn't saved yet when the check started gets both events now,
234// once launch saves it or, after paneRunSaveWait, under the run's ID alone.
235func (c *preReviewCheck) finish(success bool, extra map[string]interface{}) {
236 if c.done || c.run == nil && c.report == nil {
237 return
238 }
239 c.done = true
240 if c.run != nil && !c.started {
241 c.run.awaitState()
242 c.run.emit(event.CheckStarted, c.data)
243 }
244 end := time.Now()
245 data := map[string]interface{}{"ended_at": eventTime(end), "duration_ms": end.Sub(c.start).Milliseconds(), "success": success}
246 for k, v := range c.data {
247 data[k] = v
248 }
249 for k, v := range extra {
250 data[k] = v
251 }
252 if c.report != nil {
253 if line, err := json.Marshal(data); err == nil {
254 fmt.Fprintf(c.report, "%s%s\n", stream.ReportPrefix, line)
255 }
256 return
257 }
258 c.run.emit(event.CheckCompleted, data)
259}
260
261func printFindings(w io.Writer, findings []review.Finding) {
262 if len(findings) == 0 {
263 fmt.Fprintln(w, " No issues found.")
264 return
265 }
266 for _, f := range findings {
267 sev := strings.ToUpper(f.Severity)
268 if f.Line > 0 {
269 fmt.Fprintf(w, " %-8s %s:%d — %s\n", sev, f.File, f.Line, f.Description)
270 } else {
271 fmt.Fprintf(w, " %-8s %s — %s\n", sev, f.File, f.Description)
272 }
273 }
274}
275
276// severitiesAtOrAbove returns a set of severity levels at or above the given level.
277func severitiesAtOrAbove(level string) map[string]bool {
278 order := []string{"low", "medium", "high", "critical"}
279 result := make(map[string]bool)
280 found := false
281 for _, s := range order {
282 if s == strings.ToLower(level) {
283 found = true
284 }
285 if found {
286 result[s] = true
287 }
288 }
289 // If level not recognized, block on critical only
290 if !found {
291 result["critical"] = true
292 }
293 return result
294}
295
296func init() {
297 preReviewCmd.Flags().String("dir", "", "Worktree directory to review (defaults to current directory)")
298 rootCmd.AddCommand(preReviewCmd)
299}