gunk-dev/the-valley

pre_review.go

sourcecaaa5bee5e11main's published tip history
8.2 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 HouseRules: houseRules,
151 }, base)
152 if err != nil {
153 printProse(os.Stdout)
154 return fmt.Errorf("running peer review: %w", err)
155 }
156 printFindings(os.Stdout, result.Findings)
157 fmt.Println()
158 printProse(os.Stdout)
159
160 // Determine if we should block
161 blockOn := cfg.PreReviewBlockOn()
162 blockSeverities := severitiesAtOrAbove(blockOn)
163 blockCount := 0
164 for _, f := range result.Findings {
165 if blockSeverities[f.Severity] {
166 blockCount++
167 }
168 }
169
170 // os.Exit skips deferred calls, so the check ends first.
171 check.finish(!lintFailed && blockCount == 0, map[string]interface{}{
172 "review_ms": time.Since(reviewStart).Milliseconds(),
173 "findings": len(result.Findings),
174 "blocking": blockCount,
175 "lint_failed": lintFailed,
176 })
177
178 if lintFailed {
179 fmt.Println("Lint failures detected — PR creation should be blocked.")
180 os.Exit(1)
181 }
182
183 if blockCount > 0 {
184 label := "finding"
185 if blockCount > 1 {
186 label = "findings"
187 }
188 fmt.Printf("%d %s %s — PR creation should be blocked.\n", blockCount, blockOn+"+", label)
189 os.Exit(1)
190 }
191
192 fmt.Println("All checks passed.")
193 return nil
194 },
195}
196
197// preReviewCheck reports a _pre-review run as a check of the run whose pane
198// it runs in (runIDEnv): check:started when it starts, check:completed when
199// it finishes. On a sandbox host (runEventsEnv) it prints check:completed in
200// its output instead, for the pane's _format-stream to record. Outside a
201// run's pane it reports nothing.
202type preReviewCheck struct {
203 run *paneRun
204 report io.Writer // where a sandbox run's check is printed; nil otherwise
205 start time.Time
206 data map[string]interface{}
207 started bool
208 done bool
209}
210
211func startPreReviewCheck() *preReviewCheck {
212 c := &preReviewCheck{start: time.Now()}
213 c.data = map[string]interface{}{"kind": event.CheckPreReview, "command": "klaus _pre-review", "source": "pre-review", "started_at": eventTime(c.start)}
214 if os.Getenv(runIDEnv) != "" && os.Getenv(runEventsEnv) == runEventsOutput {
215 c.report = os.Stdout
216 return c
217 }
218 c.run = currentPaneRun()
219 if c.run != nil && c.run.state != nil {
220 c.run.emit(event.CheckStarted, c.data)
221 c.started = true
222 }
223 return c
224}
225
226// finish emits check:completed, once, with extra added to the check's data.
227// A run launch hadn't saved yet when the check started gets both events now,
228// once launch saves it or, after paneRunSaveWait, under the run's ID alone.
229func (c *preReviewCheck) finish(success bool, extra map[string]interface{}) {
230 if c.done || c.run == nil && c.report == nil {
231 return
232 }
233 c.done = true
234 if c.run != nil && !c.started {
235 c.run.awaitState()
236 c.run.emit(event.CheckStarted, c.data)
237 }
238 end := time.Now()
239 data := map[string]interface{}{"ended_at": eventTime(end), "duration_ms": end.Sub(c.start).Milliseconds(), "success": success}
240 for k, v := range c.data {
241 data[k] = v
242 }
243 for k, v := range extra {
244 data[k] = v
245 }
246 if c.report != nil {
247 if line, err := json.Marshal(data); err == nil {
248 fmt.Fprintf(c.report, "%s%s\n", stream.ReportPrefix, line)
249 }
250 return
251 }
252 c.run.emit(event.CheckCompleted, data)
253}
254
255func printFindings(w io.Writer, findings []review.Finding) {
256 if len(findings) == 0 {
257 fmt.Fprintln(w, " No issues found.")
258 return
259 }
260 for _, f := range findings {
261 sev := strings.ToUpper(f.Severity)
262 if f.Line > 0 {
263 fmt.Fprintf(w, " %-8s %s:%d — %s\n", sev, f.File, f.Line, f.Description)
264 } else {
265 fmt.Fprintf(w, " %-8s %s — %s\n", sev, f.File, f.Description)
266 }
267 }
268}
269
270// severitiesAtOrAbove returns a set of severity levels at or above the given level.
271func severitiesAtOrAbove(level string) map[string]bool {
272 order := []string{"low", "medium", "high", "critical"}
273 result := make(map[string]bool)
274 found := false
275 for _, s := range order {
276 if s == strings.ToLower(level) {
277 found = true
278 }
279 if found {
280 result[s] = true
281 }
282 }
283 // If level not recognized, block on critical only
284 if !found {
285 result["critical"] = true
286 }
287 return result
288}
289
290func init() {
291 preReviewCmd.Flags().String("dir", "", "Worktree directory to review (defaults to current directory)")
292 rootCmd.AddCommand(preReviewCmd)
293}