gunk-dev/the-valley

pre_review.go

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