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
//! Bitbucket Cloud provider — Basic auth with an Atlassian API token.
//! Posts a summary comment (deduped/updated by marker) plus inline comments
//! (the bot's prior inline comments are deleted and reposted each run).
//!
//! `BB_API_TOKEN` scopes: `read:repository:bitbucket` (to fetch the diff) +
//! `read:pullrequest:bitbucket` + `write:pullrequest:bitbucket`.

use anyhow::Result;
use base64::Engine;
use reqwest::Client;
use serde::Deserialize;

use super::{is_bot_comment, InlineComment, PrMeta, ReviewPost};
use crate::clip;
use crate::config::{require, Config};

fn auth_header(cfg: &Config) -> Result<String> {
    require(&cfg.bitbucket_email, "BB_EMAIL")?;
    require(&cfg.bitbucket_token, "BB_API_TOKEN")?;
    let raw = format!("{}:{}", cfg.bitbucket_email, cfg.bitbucket_token);
    Ok(format!(
        "Basic {}",
        base64::engine::general_purpose::STANDARD.encode(raw)
    ))
}

fn pr_base(cfg: &Config, repo: &str, pr: u64) -> String {
    format!(
        "{}/repositories/{repo}/pullrequests/{pr}",
        cfg.bitbucket_api_base
    )
}

pub async fn get_diff(client: &Client, cfg: &Config, repo: &str, pr: u64) -> Result<String> {
    let res = client
        .get(format!("{}/diff", pr_base(cfg, repo, pr)))
        .header(reqwest::header::AUTHORIZATION, auth_header(cfg)?)
        .send()
        .await?;
    if !res.status().is_success() {
        let status = res.status();
        anyhow::bail!(
            "Bitbucket getDiff {status}: {}",
            clip(&res.text().await.unwrap_or_default(), 300)
        );
    }
    Ok(res.text().await?)
}

pub async fn get_meta(client: &Client, cfg: &Config, repo: &str, pr: u64) -> Result<PrMeta> {
    #[derive(Deserialize)]
    struct Branch {
        name: Option<String>,
    }
    #[derive(Deserialize)]
    struct Destination {
        branch: Option<Branch>,
    }
    #[derive(Deserialize)]
    struct Commit {
        hash: Option<String>,
    }
    #[derive(Deserialize)]
    struct Source {
        commit: Option<Commit>,
    }
    #[derive(Deserialize)]
    struct Pr {
        title: Option<String>,
        description: Option<String>,
        destination: Option<Destination>,
        source: Option<Source>,
    }

    let res = client
        .get(pr_base(cfg, repo, pr))
        .header(reqwest::header::AUTHORIZATION, auth_header(cfg)?)
        .header("Accept", "application/json")
        .send()
        .await?;
    if !res.status().is_success() {
        let status = res.status();
        anyhow::bail!(
            "Bitbucket getMeta {status}: {}",
            clip(&res.text().await.unwrap_or_default(), 300)
        );
    }
    let pr_data: Pr = res.json().await?;
    // The source commit is fetched only to look up build statuses; `head_sha` stays
    // None because Bitbucket inline comments don't need a commit id.
    let source_sha = pr_data
        .source
        .and_then(|s| s.commit)
        .and_then(|c| c.hash)
        .filter(|h| !h.is_empty());
    let ci_status = match source_sha.as_ref().filter(|_| cfg.ci_status) {
        // Fail-open: build status is context, never a precondition for reviewing.
        Some(sha) => get_build_status(client, cfg, repo, sha)
            .await
            .unwrap_or_else(|e| {
                tracing::warn!("could not fetch build statuses for {repo}@{sha}: {e:#}");
                None
            }),
        None => None,
    };
    Ok(PrMeta {
        repo: repo.to_string(),
        pr,
        title: pr_data.title,
        base_branch: pr_data
            .destination
            .and_then(|d| d.branch)
            .and_then(|b| b.name),
        head_sha: None, // Bitbucket inline comments don't need a commit id
        body: pr_data.description,
        ci_status,
    })
}

/// Fetch a commit's build statuses and render them one per line. Bitbucket's
/// counterpart to GitHub check runs; see [`crate::providers::PrMeta::ci_status`] for
/// why the reviewer is given this at all.
///
/// `None` means no status has reported — "unknown", not "nothing ran".
///
/// # Errors
/// If credentials are missing, the request fails, or the response can't be parsed.
pub async fn get_build_status(
    client: &Client,
    cfg: &Config,
    repo: &str,
    sha: &str,
) -> Result<Option<String>> {
    #[derive(serde::Deserialize)]
    struct Status {
        key: Option<String>,
        name: Option<String>,
        /// `SUCCESSFUL` | `FAILED` | `INPROGRESS` | `STOPPED`.
        state: Option<String>,
    }
    #[derive(serde::Deserialize)]
    struct Page {
        values: Option<Vec<Status>>,
    }

    let url = format!(
        "{}/repositories/{repo}/commit/{sha}/statuses?pagelen=50",
        cfg.bitbucket_api_base
    );
    let res = client
        .get(url)
        .header(reqwest::header::AUTHORIZATION, auth_header(cfg)?)
        .header("Accept", "application/json")
        .send()
        .await?;
    if !res.status().is_success() {
        let status = res.status();
        anyhow::bail!(
            "Bitbucket getStatuses {status}: {}",
            clip(&res.text().await.unwrap_or_default(), 200)
        );
    }
    let values = res.json::<Page>().await?.values.unwrap_or_default();
    if values.is_empty() {
        return Ok(None);
    }
    let rendered = values
        .iter()
        .map(|s| {
            let name = s
                .name
                .as_deref()
                .or(s.key.as_deref())
                .unwrap_or("(unnamed build)");
            format!("- {name}: {}", s.state.as_deref().unwrap_or("unknown"))
        })
        .collect::<Vec<_>>()
        .join("\n");
    Ok(Some(rendered))
}

/// Post a standalone PR comment (NOT deduped) — used for `/ask` answers and
/// `/describe` confirmations. Returns the new comment's URL.
///
/// # Errors
/// If credentials are missing or the request fails.
pub async fn post_comment(
    client: &Client,
    cfg: &Config,
    repo: &str,
    pr: u64,
    body: &str,
) -> Result<Option<String>> {
    #[derive(Deserialize)]
    struct Html {
        href: Option<String>,
    }
    #[derive(Deserialize)]
    struct Links {
        html: Option<Html>,
    }
    #[derive(Deserialize)]
    struct Created {
        links: Option<Links>,
    }
    let marked = format!("{body}\n\n_{}_", cfg.comment_marker);
    let res = client
        .post(format!("{}/comments", pr_base(cfg, repo, pr)))
        .header(reqwest::header::AUTHORIZATION, auth_header(cfg)?)
        .json(&serde_json::json!({ "content": { "raw": marked } }))
        .send()
        .await?;
    if !res.status().is_success() {
        let status = res.status();
        anyhow::bail!(
            "Bitbucket postComment {status}: {}",
            clip(&res.text().await.unwrap_or_default(), 300)
        );
    }
    let c: Created = res.json().await?;
    Ok(c.links.and_then(|l| l.html).and_then(|h| h.href))
}

/// Replace the PR description (the `/describe` command). Bitbucket's PR update
/// requires the `title`, so it's sent alongside (from `meta`).
///
/// # Errors
/// If credentials are missing or the request fails.
pub async fn update_pr_description(
    client: &Client,
    cfg: &Config,
    meta: &PrMeta,
    description: &str,
) -> Result<()> {
    let title = meta.title.clone().unwrap_or_default();
    let res = client
        .put(pr_base(cfg, &meta.repo, meta.pr))
        .header(reqwest::header::AUTHORIZATION, auth_header(cfg)?)
        .json(&serde_json::json!({ "title": title, "description": description }))
        .send()
        .await?;
    if !res.status().is_success() {
        let status = res.status();
        anyhow::bail!(
            "Bitbucket updatePrDescription {status}: {}",
            clip(&res.text().await.unwrap_or_default(), 300)
        );
    }
    Ok(())
}

/// Fetch a repo file's text at a git ref via the `src` endpoint.
///
/// Returns `Ok(None)` when the file doesn't exist (404) so the caller can treat
/// a missing `.prbot.toml` as "no overrides" rather than an error.
///
/// # Errors
/// If credentials are missing or the request fails with a non-404 error status.
pub async fn get_file_contents(
    client: &Client,
    cfg: &Config,
    repo: &str,
    r#ref: &str,
    path: &str,
) -> Result<Option<String>> {
    // Encode ref + path (slashes preserved) so a caller-supplied path can't inject
    // a query/fragment and change which ref/file is fetched.
    let res = client
        .get(format!(
            "{}/repositories/{repo}/src/{}/{}",
            cfg.bitbucket_api_base,
            super::github::enc_path(r#ref),
            super::github::enc_path(path)
        ))
        .header(reqwest::header::AUTHORIZATION, auth_header(cfg)?)
        .send()
        .await?;
    if res.status() == reqwest::StatusCode::NOT_FOUND {
        return Ok(None);
    }
    if !res.status().is_success() {
        let status = res.status();
        anyhow::bail!(
            "Bitbucket getFileContents {status}: {}",
            clip(&res.text().await.unwrap_or_default(), 300)
        );
    }
    Ok(Some(res.text().await?))
}

/// Authenticated HTTPS clone URL.
///
/// Git-over-HTTPS on Bitbucket Cloud authenticates an Atlassian API token with
/// the fixed username `x-bitbucket-api-token-auth` (NOT the account email — the
/// `email:token` form works for the REST API but is rejected by git, which fails
/// the clone and drops the reviewer to diff-only). The token has no `@`, so no
/// percent-encoding is needed.
pub fn clone_url(cfg: &Config, repo: &str) -> Result<String> {
    require(&cfg.bitbucket_email, "BB_EMAIL")?;
    require(&cfg.bitbucket_token, "BB_API_TOKEN")?;
    Ok(format!(
        "https://x-bitbucket-api-token-auth:{}@bitbucket.org/{repo}.git",
        cfg.bitbucket_token
    ))
}

/// All of the bot's prior comments, split into (summary id, inline ids).
async fn find_bot_comments(
    client: &Client,
    cfg: &Config,
    repo: &str,
    pr: u64,
) -> Result<(Option<u64>, Vec<u64>)> {
    #[derive(Deserialize)]
    struct Content {
        raw: Option<String>,
    }
    #[derive(Deserialize)]
    struct Inline {}
    #[derive(Deserialize)]
    struct Comment {
        id: u64,
        content: Option<Content>,
        inline: Option<Inline>,
        deleted: Option<bool>,
    }
    #[derive(Deserialize)]
    struct Page {
        values: Vec<Comment>,
        next: Option<String>,
    }

    let mut url = format!("{}/comments?pagelen=100", pr_base(cfg, repo, pr));
    let mut summary: Option<u64> = None;
    let mut inline: Vec<u64> = Vec::new();
    loop {
        let res = client
            .get(&url)
            .header(reqwest::header::AUTHORIZATION, auth_header(cfg)?)
            .send()
            .await?;
        if !res.status().is_success() {
            let status = res.status();
            anyhow::bail!(
                "Bitbucket listComments {status}: {}",
                clip(&res.text().await.unwrap_or_default(), 300)
            );
        }
        let page: Page = res.json().await?;
        for c in page.values {
            if c.deleted == Some(true) {
                continue;
            }
            let is_ours = c
                .content
                .as_ref()
                .and_then(|x| x.raw.as_deref())
                .is_some_and(|b| is_bot_comment(cfg, b));
            if !is_ours {
                continue;
            }
            if c.inline.is_some() {
                inline.push(c.id);
            } else if summary.is_none() {
                summary = Some(c.id);
            }
        }
        match page.next {
            Some(n) => url = n,
            None => return Ok((summary, inline)),
        }
    }
}

async fn upsert_summary(
    client: &Client,
    cfg: &Config,
    repo: &str,
    pr: u64,
    body: &str,
    existing: Option<u64>,
) -> Result<Option<String>> {
    #[derive(Deserialize)]
    struct Html {
        href: Option<String>,
    }
    #[derive(Deserialize)]
    struct Links {
        html: Option<Html>,
    }
    #[derive(Deserialize)]
    struct Created {
        links: Option<Links>,
    }
    let marked = format!("{body}\n\n_{}_", cfg.comment_marker);
    let (req, action) = match existing {
        Some(id) => (
            client.put(format!("{}/comments/{id}", pr_base(cfg, repo, pr))),
            "updateComment",
        ),
        None => (
            client.post(format!("{}/comments", pr_base(cfg, repo, pr))),
            "postComment",
        ),
    };
    let res = req
        .header(reqwest::header::AUTHORIZATION, auth_header(cfg)?)
        .json(&serde_json::json!({ "content": { "raw": marked } }))
        .send()
        .await?;
    if !res.status().is_success() {
        let status = res.status();
        anyhow::bail!(
            "Bitbucket {action} {status}: {}",
            clip(&res.text().await.unwrap_or_default(), 300)
        );
    }
    let c: Created = res.json().await?;
    Ok(c.links.and_then(|l| l.html).and_then(|h| h.href))
}

async fn post_inline(
    client: &Client,
    cfg: &Config,
    repo: &str,
    pr: u64,
    c: &InlineComment,
) -> Result<()> {
    let body = format!("{}\n\n_{}_", c.body, cfg.comment_marker);
    let res = client
        .post(format!("{}/comments", pr_base(cfg, repo, pr)))
        .header(reqwest::header::AUTHORIZATION, auth_header(cfg)?)
        .json(&serde_json::json!({ "content": { "raw": body }, "inline": { "path": c.path, "to": c.line } }))
        .send()
        .await?;
    if !res.status().is_success() {
        let status = res.status();
        tracing::warn!(
            "Bitbucket inline comment failed ({status}) on {}:{}: {}",
            c.path,
            c.line,
            clip(&res.text().await.unwrap_or_default(), 200)
        );
    }
    Ok(())
}

pub async fn post_review(
    client: &Client,
    cfg: &Config,
    meta: &PrMeta,
    review: &ReviewPost,
) -> Result<Option<String>> {
    let (summary_id, inline_ids) = find_bot_comments(client, cfg, &meta.repo, meta.pr).await?;

    // Refresh inline comments: delete the bot's prior ones, post the new set.
    if !review.inline.is_empty() || !inline_ids.is_empty() {
        for id in inline_ids {
            let url = format!("{}/comments/{id}", pr_base(cfg, &meta.repo, meta.pr));
            let _ = client
                .delete(url)
                .header(reqwest::header::AUTHORIZATION, auth_header(cfg)?)
                .send()
                .await;
        }
        for c in &review.inline {
            post_inline(client, cfg, &meta.repo, meta.pr, c).await?;
        }
    }

    upsert_summary(
        client,
        cfg,
        &meta.repo,
        meta.pr,
        &review.summary,
        summary_id,
    )
    .await
}