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