| 1 | package cmd |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "fmt" |
| 7 | "io" |
| 8 | "os" |
| 9 | "os/signal" |
| 10 | "path/filepath" |
| 11 | "sort" |
| 12 | "strings" |
| 13 | "syscall" |
| 14 | "time" |
| 15 | |
| 16 | "the-valley/flow/internal/backend" |
| 17 | "the-valley/flow/internal/config" |
| 18 | "the-valley/flow/internal/event" |
| 19 | "the-valley/flow/internal/github" |
| 20 | "the-valley/flow/internal/jobs" |
| 21 | "the-valley/flow/internal/location" |
| 22 | "the-valley/flow/internal/review" |
| 23 | "the-valley/flow/internal/run" |
| 24 | "github.com/spf13/cobra" |
| 25 | ) |
| 26 | |
| 27 | var reviewCmd = &cobra.Command{ |
| 28 | Use: "review <pr-ref>", |
| 29 | Short: "Get a second opinion on a PR from a different model family", |
| 30 | Long: `Reviews an open PR with a model family other than the one that wrote it. |
| 31 | |
| 32 | The PR author's backend comes from the flow run that opened the PR (claude when |
| 33 | no run is found). The reviewer is --backend, else backends.<author>.review_backend, |
| 34 | else the first cross_review.order entry that is not the author and whose CLI is |
| 35 | on PATH. flow refuses to review a PR with its own family unless you pass both |
| 36 | --backend and --allow-same-family. |
| 37 | |
| 38 | The reviewer sees only the diff (gh pr diff) plus the PR title and description, |
| 39 | and runs read-only in an empty temp directory (claude: Read/Grep/Glob tools |
| 40 | only; codex: read-only sandbox, no user config; agy: temporary read-only agent); |
| 41 | no checkout is needed. |
| 42 | |
| 43 | With --post (default: cross_review.post), findings are submitted as ONE GitHub |
| 44 | review with event COMMENT: findings on diff lines become inline comments, the |
| 45 | rest go in the body with the verdict. Reviews are second opinions for the |
| 46 | operator, never approvals. Posting is refused when this backend already |
| 47 | reviewed the PR's head commit or cross_review.max_rounds reviews exist. |
| 48 | |
| 49 | Accepts PR numbers, full GitHub PR URLs, or owner/repo#number references. For a |
| 50 | bare number the repo is --repo, else the repo of the flow run that opened the |
| 51 | PR, else the session target, else the current checkout. |
| 52 | |
| 53 | Inside a flow session (or the most recent one outside a pane) the review |
| 54 | emits review:started and review:completed events (see valley flow watch) and |
| 55 | leaves a job record with its findings: valley flow status, valley flow jobs and the |
| 56 | dashboard list it, and 'valley flow jobs show <id>' prints it. |
| 57 | |
| 58 | Examples: |
| 59 | valley flow review 303 |
| 60 | valley flow review 303 --repo acme/widget --backend codex |
| 61 | valley flow review acme/widget#303 --post`, |
| 62 | Args: cobra.ExactArgs(1), |
| 63 | RunE: func(cmd *cobra.Command, args []string) error { |
| 64 | repoFlag, _ := cmd.Flags().GetString("repo") |
| 65 | backendFlag, _ := cmd.Flags().GetString("backend") |
| 66 | modelFlag, _ := cmd.Flags().GetString("model") |
| 67 | allowSame, _ := cmd.Flags().GetBool("allow-same-family") |
| 68 | |
| 69 | repoRef, prNumber, err := parsePRRef(args[0]) |
| 70 | if err != nil { |
| 71 | return err |
| 72 | } |
| 73 | cmd.SilenceUsage = true // args are valid; later errors are not usage errors |
| 74 | ctx := cmd.Context() |
| 75 | if ctx == nil { |
| 76 | ctx = context.Background() |
| 77 | } |
| 78 | // SIGINT/SIGTERM cancel the review rather than killing klaus, so its |
| 79 | // job record and completion event say it was interrupted. |
| 80 | ctx, stop := signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM) |
| 81 | defer stop() |
| 82 | var states []*run.State |
| 83 | store, err := sessionStore() // best effort: no session → author claude |
| 84 | if err == nil { |
| 85 | states, _ = store.List() |
| 86 | } |
| 87 | if repoRef == "" { |
| 88 | repoRef = repoFlag |
| 89 | } |
| 90 | if repoRef == "" { |
| 91 | repoRef = buildRepoResolver(store, "")(prNumber) |
| 92 | } |
| 93 | ownerRepo, err := reviewRepoSlug(ctx, repoRef) |
| 94 | if err != nil { |
| 95 | return err |
| 96 | } |
| 97 | |
| 98 | repoDir, err := existingRepoDir(ownerRepo) |
| 99 | if err != nil { |
| 100 | return err |
| 101 | } |
| 102 | cfg, err := config.Load(repoDir) |
| 103 | if err != nil { |
| 104 | return fmt.Errorf("could not load configuration: %w", err) |
| 105 | } |
| 106 | author := prAuthorBackend(states, ownerRepo, prNumber) |
| 107 | |
| 108 | var reviewer backend.Kind |
| 109 | var model string |
| 110 | if backendFlag != "" { |
| 111 | if reviewer, err = backend.Parse(backendFlag); err != nil { |
| 112 | return err |
| 113 | } |
| 114 | model = review.ReviewModel(reviewer, cfg) |
| 115 | } else if reviewer, model, err = review.ChooseReviewer(author, cfg); err != nil { |
| 116 | return err |
| 117 | } |
| 118 | if modelFlag != "" { |
| 119 | model = modelFlag |
| 120 | } |
| 121 | if reviewer == author && backendFlag == "" { |
| 122 | return fmt.Errorf("PR #%s was written by %s and no other reviewer family is available: install another backend CLI, set cross_review.order or backends.%s.review_backend, or pass --backend %s --allow-same-family", prNumber, author, author, author) |
| 123 | } |
| 124 | if reviewer == author && !allowSame { |
| 125 | return fmt.Errorf("PR #%s was written by %s; refusing a same-family review: pick another --backend or add --allow-same-family", prNumber, author) |
| 126 | } |
| 127 | |
| 128 | post := cfg.CrossReviewPost() |
| 129 | if cmd.Flags().Changed("post") { |
| 130 | post, _ = cmd.Flags().GetBool("post") |
| 131 | } |
| 132 | |
| 133 | out := cmd.OutOrStdout() |
| 134 | fmt.Fprintf(out, "Cross-model review of %s#%s (author: %s; reviewer: %s)\n", ownerRepo, prNumber, author, review.BackendModel(string(reviewer), model)) |
| 135 | finish := startReviewJob(store, ownerRepo, prNumber, author, reviewer, model, post, cmd.ErrOrStderr()) |
| 136 | result, err := review.RunPRReview(ctx, ownerRepo, prNumber, review.PROptions{ |
| 137 | Backend: reviewer, Model: model, Post: post, MaxRounds: cfg.CrossReviewMaxRounds(), |
| 138 | LockDirs: reviewLockDirs(store), |
| 139 | }) |
| 140 | finish(result, err, ctx.Err() != nil) |
| 141 | if result != nil { |
| 142 | printPRReview(out, result) |
| 143 | } |
| 144 | if err != nil { |
| 145 | return err |
| 146 | } |
| 147 | if result.ReviewURL != "" { |
| 148 | fmt.Fprintf(out, "\nPosted COMMENT review: %s\n", result.ReviewURL) |
| 149 | } else if post { |
| 150 | fmt.Fprintln(out, "\nNothing posted: no changes to review.") |
| 151 | } |
| 152 | return nil |
| 153 | }, |
| 154 | } |
| 155 | |
| 156 | // startReviewJob records a review starting, in its session's job store and |
| 157 | // as a review:started event, and returns the function that records how it |
| 158 | // ended. Outside a session it records nothing. |
| 159 | func startReviewJob(store run.StateStore, ownerRepo, prNumber string, author, reviewer backend.Kind, model string, post bool, warn io.Writer) func(result *review.ReviewResult, err error, interrupted bool) { |
| 160 | hds, ok := store.(*run.HomeDirStore) |
| 161 | if !ok { |
| 162 | return func(*review.ReviewResult, error, bool) {} |
| 163 | } |
| 164 | baseDir, jobStore := hds.BaseDir(), jobs.NewStore(hds.BaseDir()) |
| 165 | job := &jobs.Job{ID: eventID("review"), Kind: jobs.KindReview, Backend: string(reviewer), Model: model, |
| 166 | Repo: ownerRepo, PR: ownerRepo + "#" + prNumber} |
| 167 | data := map[string]interface{}{"backend": reviewer, "model": model, "repo": ownerRepo, "pr_number": prNumber, "author": author, "post": post, |
| 168 | "repo_key": ownerRepo, "key": ownerRepo + "#" + prNumber} |
| 169 | warnJob(warn, job, jobStore.Start(job)) |
| 170 | emitEvent(baseDir, job.ID, event.ReviewStarted, data) |
| 171 | start := time.Now() |
| 172 | return func(result *review.ReviewResult, err error, interrupted bool) { |
| 173 | timeoutMsg := "" |
| 174 | if err != nil { |
| 175 | timeoutMsg = errorLine(err) |
| 176 | } |
| 177 | status, errText := jobOutcome(err, interrupted, errors.Is(err, context.DeadlineExceeded), timeoutMsg) |
| 178 | done := make(map[string]interface{}, len(data)+5) |
| 179 | for k, v := range data { |
| 180 | done[k] = v |
| 181 | } |
| 182 | done["duration_ms"] = time.Since(start).Milliseconds() |
| 183 | done["success"] = err == nil |
| 184 | if errText != "" { |
| 185 | done["error"] = errText |
| 186 | } |
| 187 | if result != nil { |
| 188 | job.Review = &jobs.Review{Verdict: result.Verdict, Summary: result.Summary, Findings: result.Findings, ReviewURL: result.ReviewURL} |
| 189 | done["findings"] = len(result.Findings) |
| 190 | if result.ReviewURL != "" { |
| 191 | done["review_url"] = result.ReviewURL |
| 192 | } |
| 193 | } |
| 194 | emitEvent(baseDir, job.ID, event.ReviewCompleted, done) |
| 195 | warnJob(warn, job, jobStore.Finish(job, status, errText)) |
| 196 | } |
| 197 | } |
| 198 | |
| 199 | // reviewLockDirs: <session>/locks, else the global review lock directories |
| 200 | // when no session exists. |
| 201 | func reviewLockDirs(store run.StateStore) []string { |
| 202 | if hds, ok := store.(*run.HomeDirStore); ok { |
| 203 | return []string{filepath.Join(hds.BaseDir(), "locks")} |
| 204 | } |
| 205 | if l, err := location.Host(); err == nil { |
| 206 | return l.ReviewLockDirs() |
| 207 | } |
| 208 | return nil |
| 209 | } |
| 210 | |
| 211 | // reviewRepoSlug normalizes owner/repo, URLs, and registered project names to owner/repo; "" → the current checkout's repo. |
| 212 | func reviewRepoSlug(ctx context.Context, ref string) (string, error) { |
| 213 | if ref == "" { |
| 214 | owner, repo, err := github.NewGHCLIClient("").GetRepoOwnerAndName(ctx) |
| 215 | if err != nil { |
| 216 | return "", fmt.Errorf("no repo given (use --repo owner/repo): %w", err) |
| 217 | } |
| 218 | return owner + "/" + repo, nil |
| 219 | } |
| 220 | if slug := repoSlug(ref); slug != "" { |
| 221 | return slug, nil |
| 222 | } |
| 223 | dir, err := existingRepoDir(ref) |
| 224 | if err != nil { |
| 225 | return "", err |
| 226 | } |
| 227 | if slug := repoSlugForDir(dir); slug != "" { |
| 228 | return slug, nil |
| 229 | } |
| 230 | return "", fmt.Errorf("cannot resolve repo %q to owner/repo", ref) |
| 231 | } |
| 232 | |
| 233 | // prAuthorBackend returns the backend of the earliest run whose PR URL is ownerRepo#prNumber; claude when none. |
| 234 | func prAuthorBackend(states []*run.State, ownerRepo, prNumber string) backend.Kind { |
| 235 | var matches []*run.State |
| 236 | for _, s := range states { |
| 237 | if s.PRURL != nil && extractPRNumber(s) == prNumber && strings.EqualFold(github.OwnerRepoFromPRURL(*s.PRURL), ownerRepo) { |
| 238 | matches = append(matches, s) |
| 239 | } |
| 240 | } |
| 241 | if len(matches) == 0 { |
| 242 | return backend.Claude |
| 243 | } |
| 244 | sort.SliceStable(matches, func(i, j int) bool { return matches[i].CreatedAt < matches[j].CreatedAt }) |
| 245 | k, err := backend.Parse(matches[0].Backend) |
| 246 | if err != nil { |
| 247 | return backend.Claude |
| 248 | } |
| 249 | return k |
| 250 | } |
| 251 | |
| 252 | func printPRReview(w io.Writer, r *review.ReviewResult) { |
| 253 | if r.Verdict != "" { |
| 254 | fmt.Fprintf(w, "\nVerdict: %s\n", r.Verdict) |
| 255 | } |
| 256 | fmt.Fprintln(w, "\nFindings:") |
| 257 | printFindings(w, r.Findings) |
| 258 | if r.Summary != "" { |
| 259 | fmt.Fprintf(w, "\nSummary: %s\n", r.Summary) |
| 260 | } |
| 261 | } |
| 262 | |
| 263 | func init() { |
| 264 | reviewCmd.Flags().String("repo", "", "Target repo (owner/repo or registered project) for a bare PR number") |
| 265 | reviewCmd.Flags().String("backend", "", "Reviewer backend: claude, codex, or agy (default: cross-review choice)") |
| 266 | reviewCmd.Flags().String("model", "", "Reviewer model (default: backends.<reviewer>.review_model)") |
| 267 | reviewCmd.Flags().Bool("post", false, "Submit findings as one COMMENT review on the PR (default: cross_review.post)") |
| 268 | reviewCmd.Flags().Bool("allow-same-family", false, "With --backend, allow reviewing with the PR author's own family") |
| 269 | rootCmd.AddCommand(reviewCmd) |
| 270 | } |