gunk-dev/the-valley

pre_review.go

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