pr-review-core 0.14.0

Core engine for a self-hosted advisory AI PR reviewer: fetches a pull request diff, reviews it with a Claude model via OpenRouter, and posts line-anchored inline comments plus a summary. Works with GitHub and Bitbucket.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
//! PR comment commands (T3.9): `/review`, `/ask <question>`, and `/describe`.
//!
//! A single entry point — [`run_command`] — lets a bot binary route any
//! recognized comment command through the core without wiring each one itself.
//! [`parse_command`] turns a raw comment body into a [`Command`]; the caller is
//! responsible for the gating that's cheap to do provider-side (the event is a
//! newly-created comment on a PR).

use anyhow::Result;

use crate::backend::{OpenRouterBackend, ReviewBackend};
use crate::config::Config;
use crate::providers::{PrMeta, Provider};
use crate::review::{load_repo_config, run_review_with, RunReviewInput};

/// HTML-comment delimiters wrapping the AI-generated section of a PR description
/// so `/describe` can regenerate idempotently while preserving human-written
/// content around it. (GitHub/GitLab hide these; Bitbucket renders them literally
/// — a minor cosmetic quirk on that provider.)
const DESC_START: &str = "<!-- prbot:describe:start -->";
const DESC_END: &str = "<!-- prbot:describe:end -->";

/// A recognized PR comment command.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Command {
    /// `/review` — (re)run the full review.
    Review,
    /// `/ask <question>` — answer a question about the PR.
    Ask(String),
    /// `/describe` — (re)generate the PR description from the diff.
    Describe,
    /// `/review-file <path>` — deep-review an entire file at the PR head.
    ReviewFile(String),
}

/// What a command run did, for the caller to log.
#[derive(Debug, Clone)]
pub struct CommandOutcome {
    /// `"review"`, `"ask"`, `"describe"`, or `"review-file"`.
    pub command: &'static str,
    /// URL of the comment posted (or the review summary), when available.
    pub comment_url: Option<String>,
}

/// Parse a comment body into a [`Command`], or `None` if it isn't one.
///
/// The command must be the first token of the comment. `/ask` takes the rest of
/// the comment (which may span multiple lines) as its question; an empty question
/// yields `None`. Surrounding whitespace is ignored.
///
/// # Examples
/// ```
/// # use pr_review_core::command::{parse_command, Command};
/// assert_eq!(parse_command("/review"), Some(Command::Review));
/// assert_eq!(parse_command("  /describe \n"), Some(Command::Describe));
/// assert_eq!(parse_command("/ask why is this safe?"), Some(Command::Ask("why is this safe?".into())));
/// assert_eq!(parse_command("/ask"), None);            // no question
/// assert_eq!(parse_command("please /review"), None);  // not the first token
/// assert_eq!(parse_command("/reviews"), None);        // no fuzzy match
/// ```
pub fn parse_command(body: &str) -> Option<Command> {
    let trimmed = body.trim();
    let mut lines = trimmed.lines();
    let first = lines.next().unwrap_or("").trim();
    let (cmd, rest) = match first.split_once(char::is_whitespace) {
        Some((c, r)) => (c, r.trim()),
        None => (first, ""),
    };
    match cmd {
        "/review" => Some(Command::Review),
        "/describe" => Some(Command::Describe),
        "/review-file" => {
            let path = rest.trim();
            (!path.is_empty()).then(|| Command::ReviewFile(path.to_string()))
        }
        "/ask" => {
            // The question is the remainder of the first line plus any following
            // lines, so a multi-line question survives intact.
            let mut q = rest.to_string();
            let tail: Vec<&str> = lines.collect();
            if !tail.is_empty() {
                if !q.is_empty() {
                    q.push('\n');
                }
                q.push_str(&tail.join("\n"));
            }
            let q = q.trim().to_string();
            if q.is_empty() {
                None
            } else {
                Some(Command::Ask(q))
            }
        }
        _ => None,
    }
}

/// Execute a parsed command end-to-end.
///
/// `/review` delegates to [`run_review`] (with an instant "Reviewing…"
/// placeholder). `/ask` and `/describe` fetch the diff, respect a per-repo
/// `.prbot.toml`, and post their result.
///
/// # Errors
/// On unknown provider, or any provider/LLM API failure.
pub async fn run_command(
    cfg: &Config,
    provider_name: &str,
    repo: &str,
    pr: u64,
    cmd: Command,
) -> Result<CommandOutcome> {
    run_command_with(cfg, provider_name, repo, pr, cmd, &OpenRouterBackend).await
}

/// Like [`run_command`] but with a caller-supplied [`ReviewBackend`], so `/review`,
/// `/ask`, and `/describe` all run on the same backend (e.g. an agent CLI) instead
/// of always OpenRouter.
///
/// # Errors
/// On unknown provider, or any provider/backend failure.
pub async fn run_command_with(
    cfg: &Config,
    provider_name: &str,
    repo: &str,
    pr: u64,
    cmd: Command,
    backend: &dyn ReviewBackend,
) -> Result<CommandOutcome> {
    match cmd {
        Command::Review => {
            let out = run_review_with(
                cfg,
                RunReviewInput {
                    provider: provider_name.to_string(),
                    repo: repo.to_string(),
                    pr,
                    dry_run: false,
                    placeholder: true,
                },
                backend,
            )
            .await?;
            Ok(CommandOutcome {
                command: "review",
                comment_url: out.comment_url,
            })
        }
        Command::Ask(question) => run_ask(cfg, backend, provider_name, repo, pr, &question).await,
        Command::Describe => run_describe(cfg, backend, provider_name, repo, pr).await,
        Command::ReviewFile(path) => {
            run_review_file(cfg, backend, provider_name, repo, pr, &path).await
        }
    }
}

/// `/review-file <path>`: deep-review an entire file at the PR head and post the
/// findings as a summary comment. Findings can anchor to any line in the file, so
/// they're reported as text (a PR only accepts inline comments on diff lines).
async fn run_review_file(
    cfg: &Config,
    backend: &dyn ReviewBackend,
    provider_name: &str,
    repo: &str,
    pr: u64,
    path: &str,
) -> Result<CommandOutcome> {
    let provider = Provider::from_name(provider_name)?;
    let client = reqwest::Client::new();
    let meta = provider.get_meta(&client, cfg, repo, pr).await?;
    let effective = load_repo_config(&provider, &client, cfg, repo, &meta).await;
    let cfg = &effective;

    // Honour the repo's include/exclude globs so `/review-file` can't be used to
    // pull in a file the diff-based review would have filtered out (e.g. secrets
    // or vendored paths excluded via `.prbot.toml`).
    if !crate::diff::path_matches_globs(path, &cfg.include_globs, &cfg.exclude_globs) {
        let url = provider
            .post_comment(
                &client,
                cfg,
                repo,
                pr,
                &format!(
                    "> **/review-file** `{path}`\n\nThat path is excluded by this repo's review file filters, so I won't review it."
                ),
            )
            .await?;
        return Ok(CommandOutcome {
            command: "review-file",
            comment_url: url,
        });
    }

    // Fetch the file at the PR head (fall back to the base branch if no head SHA).
    let git_ref = match (meta.head_sha.as_deref(), meta.base_branch.as_deref()) {
        (Some(s), _) if !s.is_empty() => s,
        (_, Some(b)) if !b.is_empty() => b,
        _ => anyhow::bail!("no git ref to fetch `{path}` against"),
    };
    let content = match provider
        .get_file_contents(&client, cfg, repo, git_ref, path)
        .await?
    {
        Some(c) => c,
        None => {
            let url = provider
                .post_comment(
                    &client,
                    cfg,
                    repo,
                    pr,
                    &format!(
                        "> **/review-file** `{path}`\n\nCouldn't find that file at the PR head."
                    ),
                )
                .await?;
            return Ok(CommandOutcome {
                command: "review-file",
                comment_url: url,
            });
        }
    };

    let review = crate::llm::review_file(cfg, backend, path, &content).await?;
    // Same post-processing as a diff review: confidence floor, severity sort, cap.
    let mut findings = review.findings.clone();
    findings.retain(|f| f.confidence.unwrap_or(100) >= cfg.min_confidence);
    findings.sort_by(|a, b| {
        crate::review::severity_rank(&b.severity)
            .cmp(&crate::review::severity_rank(&a.severity))
            // Secondary key: higher confidence first — matches the `/review` path.
            .then(b.confidence.unwrap_or(0).cmp(&a.confidence.unwrap_or(0)))
    });
    findings.truncate(cfg.max_findings);

    let body = render_file_review(path, &review, &findings);
    let url = provider.post_comment(&client, cfg, repo, pr, &body).await?;
    Ok(CommandOutcome {
        command: "review-file",
        comment_url: url,
    })
}

/// Render a `/review-file` result as a summary comment.
fn render_file_review(
    path: &str,
    review: &crate::llm::Review,
    findings: &[crate::llm::Finding],
) -> String {
    let mut s = format!(
        "🔍 **File review — `{path}`**\n\n{}\n\n**Recommendation:** {}",
        review.summary.trim(),
        review.recommendation.trim()
    );
    if findings.is_empty() {
        s.push_str("\n\nNo issues found.");
    } else {
        s.push_str("\n\n## Findings");
        for f in findings {
            let loc = f.line.map(|l| format!(" (line {l})")).unwrap_or_default();
            s.push_str(&format!(
                "\n- {} **{}** — `{path}`{loc}{}",
                crate::review::severity_emoji(&f.severity),
                f.severity.to_uppercase(),
                f.body.trim()
            ));
        }
    }
    s.push_str("\n\n_Automated advisory review — a human still owns the merge decision._");
    s
}

/// Fetch the PR diff and prepare it exactly as the review path does — glob
/// filter, size packing, and (optionally) structural context — so `/ask` and
/// `/describe` reason over the same trimmed, budgeted diff the reviewer sees.
async fn prepared_diff(
    provider: &Provider,
    client: &reqwest::Client,
    cfg: &Config,
    repo: &str,
    meta: &PrMeta,
) -> Result<(String, String)> {
    let raw = provider.get_diff(client, cfg, repo, meta.pr).await?;
    let (diff, _dropped) =
        crate::diff::filter_diff_by_globs(&raw, &cfg.include_globs, &cfg.exclude_globs);
    let (diff, _packed) = crate::diff::pack_diff(&diff, cfg.max_diff_chars);
    let structural = if cfg.structural_context && !diff.trim().is_empty() {
        crate::structure::structural_context(provider, client, cfg, repo, meta, &diff).await
    } else {
        String::new()
    };
    Ok((diff, structural))
}

/// `/ask`: answer a question about the PR and post it as a reply comment.
async fn run_ask(
    cfg: &Config,
    backend: &dyn ReviewBackend,
    provider_name: &str,
    repo: &str,
    pr: u64,
    question: &str,
) -> Result<CommandOutcome> {
    let provider = Provider::from_name(provider_name)?;
    let client = reqwest::Client::new();
    let meta = provider.get_meta(&client, cfg, repo, pr).await?;
    let effective = load_repo_config(&provider, &client, cfg, repo, &meta).await;
    let cfg = &effective;

    let (diff, structural) = prepared_diff(&provider, &client, cfg, repo, &meta).await?;
    if diff.trim().is_empty() {
        let body = format!(
            "> **/ask** {question}\n\nThere are no reviewable source changes in this PR to answer against."
        );
        let url = provider.post_comment(&client, cfg, repo, pr, &body).await?;
        return Ok(CommandOutcome {
            command: "ask",
            comment_url: url,
        });
    }

    let structural_opt = (!structural.is_empty()).then_some(structural.as_str());
    let answer =
        crate::llm::answer_question(cfg, backend, &meta, &diff, question, structural_opt).await?;
    // Echo the question so the thread reads as a Q&A exchange.
    let body = format!("> **/ask** {question}\n\n{answer}");
    let url = provider.post_comment(&client, cfg, repo, pr, &body).await?;
    Ok(CommandOutcome {
        command: "ask",
        comment_url: url,
    })
}

/// `/describe`: generate a PR description, merge it into the existing body
/// (preserving human-written content), update the PR, and confirm in a comment.
async fn run_describe(
    cfg: &Config,
    backend: &dyn ReviewBackend,
    provider_name: &str,
    repo: &str,
    pr: u64,
) -> Result<CommandOutcome> {
    let provider = Provider::from_name(provider_name)?;
    let client = reqwest::Client::new();
    let meta = provider.get_meta(&client, cfg, repo, pr).await?;
    let effective = load_repo_config(&provider, &client, cfg, repo, &meta).await;
    let cfg = &effective;

    let (diff, structural) = prepared_diff(&provider, &client, cfg, repo, &meta).await?;
    if diff.trim().is_empty() {
        let url = provider
            .post_comment(
                &client,
                cfg,
                repo,
                pr,
                "No reviewable source changes to describe.",
            )
            .await?;
        return Ok(CommandOutcome {
            command: "describe",
            comment_url: url,
        });
    }

    let structural_opt = (!structural.is_empty()).then_some(structural.as_str());
    let generated = crate::llm::describe_pr(cfg, backend, &meta, &diff, structural_opt).await?;
    let merged = merge_description(meta.body.as_deref().unwrap_or(""), &generated);
    provider
        .update_pr_description(&client, cfg, &meta, &merged)
        .await?;
    let url = provider
        .post_comment(&client, cfg, repo, pr, "📝 Updated the PR description.")
        .await?;
    Ok(CommandOutcome {
        command: "describe",
        comment_url: url,
    })
}

/// Merge a freshly-generated description into an existing PR body.
///
/// The generated text is wrapped between [`DESC_START`]/[`DESC_END`] markers. If
/// those markers already exist (a prior `/describe`), only the section between
/// them is replaced, preserving anything the author wrote around it. Otherwise
/// the marked block is prepended to the existing body (or becomes the whole body
/// when it was empty).
///
/// # Examples
/// ```
/// # use pr_review_core::command::merge_description;
/// // First run on an empty body: just the generated block.
/// let out = merge_description("", "## Summary\nDoes a thing.");
/// assert!(out.contains("Does a thing."));
/// // Re-run replaces only the generated section, keeping human notes.
/// let again = merge_description(&out, "## Summary\nUpdated.");
/// assert!(again.contains("Updated."));
/// assert!(!again.contains("Does a thing."));
/// ```
pub fn merge_description(existing: &str, generated: &str) -> String {
    let block = format!("{DESC_START}\n{}\n{DESC_END}", generated.trim());
    if let (Some(s), Some(e)) = (existing.find(DESC_START), existing.find(DESC_END)) {
        if e > s {
            let end = e + DESC_END.len();
            return format!("{}{}{}", &existing[..s], block, &existing[end..]);
        }
    }
    if existing.trim().is_empty() {
        block
    } else {
        format!("{block}\n\n{}", existing.trim())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parses_the_core_commands() {
        assert_eq!(parse_command("/review"), Some(Command::Review));
        assert_eq!(parse_command("/describe"), Some(Command::Describe));
        assert_eq!(
            parse_command("/ask does this leak memory?"),
            Some(Command::Ask("does this leak memory?".into()))
        );
    }

    #[test]
    fn parses_review_file_with_path() {
        assert_eq!(
            parse_command("/review-file src/auth.rs"),
            Some(Command::ReviewFile("src/auth.rs".into()))
        );
        // Extra surrounding whitespace is trimmed off the path.
        assert_eq!(
            parse_command("  /review-file   src/lib.rs  "),
            Some(Command::ReviewFile("src/lib.rs".into()))
        );
    }

    #[test]
    fn review_file_without_path_is_none() {
        assert_eq!(parse_command("/review-file"), None);
        assert_eq!(parse_command("/review-file    "), None);
    }

    #[test]
    fn ask_captures_multiline_question() {
        let cmd = parse_command("/ask first line\nsecond line").unwrap();
        assert_eq!(cmd, Command::Ask("first line\nsecond line".into()));
    }

    #[test]
    fn ask_with_no_question_is_none() {
        assert_eq!(parse_command("/ask"), None);
        assert_eq!(parse_command("/ask    "), None);
    }

    #[test]
    fn non_commands_are_ignored() {
        assert_eq!(parse_command("please /review"), None);
        assert_eq!(parse_command("/reviews"), None);
        assert_eq!(parse_command("just a comment"), None);
        assert_eq!(parse_command(""), None);
    }

    #[test]
    fn leading_and_trailing_whitespace_ok() {
        assert_eq!(parse_command("  /review  \n"), Some(Command::Review));
    }

    #[test]
    fn merge_into_empty_body() {
        let out = merge_description("", "generated text");
        assert_eq!(out, format!("{DESC_START}\ngenerated text\n{DESC_END}"));
    }

    #[test]
    fn merge_prepends_to_human_body() {
        let out = merge_description("Human notes here.", "gen");
        assert!(out.starts_with(DESC_START));
        assert!(out.ends_with("Human notes here."));
        assert!(out.contains("gen"));
    }

    #[test]
    fn merge_replaces_prior_generated_section() {
        let first = merge_description("Keep me.", "old desc");
        // Human edits above and below the block are preserved on re-run.
        let edited = format!("PREFIX\n{first}\nSUFFIX");
        let again = merge_description(&edited, "new desc");
        assert!(again.contains("new desc"));
        assert!(!again.contains("old desc"));
        assert!(again.starts_with("PREFIX"));
        assert!(again.ends_with("SUFFIX"));
        assert!(again.contains("Keep me."));
    }
}