gunk-dev/the-valley

pre_review.go

sourceb8e46aa6aaccmain'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/project"
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 := forbiddenTermsFor(cfg, dir, "")
43 if !cfg.PreReviewEnabled() && len(forbidden) == 0 {
44 fmt.Println("Pre-review is disabled in config.")
45 return nil
46 }
47
48 check := startPreReviewCheck()
49 defer func() {
50 if err != nil {
51 check.finish(false, map[string]interface{}{"error": errorLine(err)})
52 }
53 }()
54
55 fmt.Println("=== Pre-PR Review ===")
56 fmt.Println()
57
58 // Every pass reads what HEAD changes since its merge base with the
59 // default branch as origin last held it, which the worktree started
60 // from, so a local default branch behind origin's adds no landed
61 // commits to what is reviewed.
62 base := defaultBranchRef(dir, cfg.DefaultBranch)
63
64 // Forbidden terms go first, so a diff that adds one is never sent
65 // to the peer reviewer, which then reviews the diff they checked.
66 if len(forbidden) > 0 {
67 fmt.Println("Forbidden terms:")
68 hits, err := scanForbiddenTerms(dir, base, "HEAD", forbidden)
69 if err != nil {
70 return fmt.Errorf("checking forbidden terms: %w", err)
71 }
72 printForbiddenTerms(os.Stdout, hits)
73 fmt.Println()
74 if len(hits) > 0 {
75 check.finish(false, map[string]interface{}{"forbidden_terms": len(hits)})
76 fmt.Println("Forbidden terms added — PR creation should be blocked.")
77 os.Exit(1)
78 }
79 if !cfg.PreReviewEnabled() {
80 check.finish(true, nil)
81 fmt.Println("Pre-review is disabled in config; only forbidden terms were checked.")
82 return nil
83 }
84 }
85
86 // Run linters
87 linters := cfg.PreReviewLinters()
88 lintFailed := false
89 if len(linters) > 0 {
90 fmt.Println("Linters:")
91 results, err := review.RunLinters(dir, linters)
92 if err != nil {
93 return fmt.Errorf("running linters: %w", err)
94 }
95 for _, r := range results {
96 if r.Passed {
97 fmt.Printf(" ✓ %s\n", r.Command)
98 } else {
99 lintFailed = true
100 // Count issues from output lines
101 lines := strings.Split(strings.TrimSpace(r.Output), "\n")
102 count := 0
103 for _, l := range lines {
104 if strings.TrimSpace(l) != "" {
105 count++
106 }
107 }
108 fmt.Printf(" ✗ %s (%d issues)\n", r.Command, count)
109 // Print up to 10 lines of output indented
110 for i, line := range lines {
111 if i >= 10 {
112 fmt.Printf(" ... and %d more\n", count-10)
113 break
114 }
115 if strings.TrimSpace(line) != "" {
116 fmt.Printf(" %s\n", line)
117 }
118 }
119 }
120 }
121 fmt.Println()
122 }
123
124 // Run peer review with a different model family than the worker's.
125 authorName := flowenv.Backend.Get()
126 if authorName == "" {
127 selected, err := resolveAgentBackend(cmd, cfg)
128 if err != nil {
129 return err
130 }
131 authorName = string(selected)
132 }
133 author, err := backend.Parse(authorName)
134 if err != nil {
135 return err
136 }
137 kind, model, err := review.ChooseReviewer(author, cfg)
138 if err != nil {
139 return err
140 }
141 fmt.Printf("Peer Review (reviewer: %s; author: %s):\n", review.BackendModel(string(kind), model), author)
142 check.data["reviewer"] = string(kind)
143 check.data["lint_ms"] = time.Since(check.start).Milliseconds()
144 reviewStart := time.Now()
145 reg, _ := project.Load()
146 houseRules := loadHouseRules(cmd.Context(), dir, cfg, reg, cmd.ErrOrStderr()).Text
147 printProse := startProsePass(cmd.Context(), dir, base, cfg, author, houseRules)
148 result, err := review.ReviewDiff(dir, review.ReviewConfig{
149 Backend: string(kind),
150 Model: model,
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 (flowenv.RunID): check:started when it starts, check:completed when
200// it finishes. On a sandbox host (flowenv.RunEvents) 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 flowenv.RunID.Get() != "" && flowenv.RunEvents.Get() == 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}