gunk-dev/the-valley

pre_review.go

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