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
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
//! OpenRouter chat-completions client. Sends the review prompt to a Claude model
//! via OpenRouter and parses the structured review back.

use anyhow::Result;
use reqwest::Client;
use serde::{Deserialize, Serialize};

use crate::clip;
use crate::config::{require, Config};
use crate::prompt::{
    build_user_prompt, ASK_SYSTEM_PROMPT, CRITIQUE_SYSTEM_PROMPT, DESCRIBE_SYSTEM_PROMPT,
    FILE_REVIEW_SYSTEM_PROMPT,
};
use crate::providers::PrMeta;

#[derive(Serialize)]
struct Msg {
    role: String,
    content: String,
}

#[derive(Serialize)]
struct ChatReq {
    model: String,
    max_tokens: u32,
    temperature: f32,
    messages: Vec<Msg>,
}

/// Token accounting echoed back by OpenRouter.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Usage {
    pub prompt_tokens: Option<u32>,
    pub completion_tokens: Option<u32>,
    pub total_tokens: Option<u32>,
}

/// Severity assumed when the model omits the field. Deliberately not `LOW`:
/// `severity_rank` ranks LOW and unknown equally at 0, so an unlabelled finding
/// would sort last and be first out under `max_findings`. MEDIUM keeps a real
/// finding visible without inventing urgency.
fn default_severity() -> String {
    "MEDIUM".to_string()
}

/// One review finding from the model.
///
/// Only `body` is required. `severity` and `file` are defaulted rather than
/// demanded because a model that drops one field must not cost the whole review:
/// an unlabelled severity becomes MEDIUM, and an empty `file` simply fails to
/// anchor and folds into the summary.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Finding {
    #[serde(default = "default_severity")]
    pub severity: String,
    #[serde(default)]
    pub file: String,
    #[serde(default)]
    pub line: Option<u64>,
    pub body: String,
    /// Model's confidence (0–100) that this is a real, actionable issue a senior
    /// reviewer would flag. Absent on older responses; treated as full confidence.
    #[serde(default)]
    pub confidence: Option<u8>,
}

/// Parse a findings array element-by-element, dropping (with a warning) any element
/// that still can't be understood. One malformed finding must never invalidate the
/// review it sits in — that trades a whole expensive review for a formatting slip.
///
/// Returns `(kept, dropped)`.
pub(crate) fn findings_from_values(raw: Vec<serde_json::Value>) -> (Vec<Finding>, usize) {
    let mut kept = Vec::with_capacity(raw.len());
    let mut dropped = 0usize;
    for v in raw {
        match serde_json::from_value::<Finding>(v) {
            Ok(f) => kept.push(f),
            Err(e) => {
                dropped += 1;
                tracing::warn!("dropping malformed finding ({e})");
            }
        }
    }
    (kept, dropped)
}

fn lenient_findings<'de, D>(d: D) -> std::result::Result<Vec<Finding>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let raw = Vec::<serde_json::Value>::deserialize(d)?;
    Ok(findings_from_values(raw).0)
}

/// The structured review the model returns.
#[derive(Debug, Clone, Deserialize)]
pub struct Review {
    pub summary: String,
    pub recommendation: String,
    #[serde(default, deserialize_with = "lenient_findings")]
    pub findings: Vec<Finding>,
}

#[derive(Deserialize)]
struct ChoiceMsg {
    content: Option<String>,
}
#[derive(Deserialize)]
struct Choice {
    message: Option<ChoiceMsg>,
}
#[derive(Deserialize)]
struct ApiErr {
    message: Option<String>,
}
#[derive(Deserialize)]
struct ChatRes {
    choices: Option<Vec<Choice>>,
    usage: Option<Usage>,
    error: Option<ApiErr>,
}

/// The outcome of one review call.
#[derive(Debug)]
pub struct ReviewResult {
    pub review: Review,
    pub model: String,
    pub usage: Option<Usage>,
}

/// Pull the JSON object out of a model response that may be wrapped in prose or
/// ```json fences — take the first `{` through the last `}`. Exposed so custom
/// [`crate::backend::ReviewBackend`]s can parse a model's text into a [`Review`].
pub fn extract_json(text: &str) -> Option<&str> {
    let start = text.find('{')?;
    let end = text.rfind('}')?;
    if end > start {
        Some(&text[start..=end])
    } else {
        None
    }
}

/// Pull the first JSON array out of a model response that may be wrapped in prose
/// or ```json fences — take the first `[` through the last `]`.
pub(crate) fn extract_json_array(text: &str) -> Option<&str> {
    let start = text.find('[')?;
    let end = text.rfind(']')?;
    if end > start {
        Some(&text[start..=end])
    } else {
        None
    }
}

/// Call OpenRouter and parse the structured review.
///
/// The diff is expected to be pre-packed to fit the size budget (whole files
/// dropped, lowest-priority first) by [`crate::diff::pack_diff`]; `omitted_note`
/// carries the human-readable list of those dropped files so the model is told
/// they were NOT reviewed. A SAFETY clamp (`take(max_diff_chars)`) still applies
/// so a single un-packable oversized file can't blow the budget.
///
/// `system_prompt` is supplied by the caller: the orchestrator composes it from the
/// rubric and the injected rules, and hands it to the backend on
/// [`crate::backend::ReviewContext`]. Callers driving this function directly can
/// build the same string with [`crate::prompt::review_system_prompt`].
///
/// # Errors
/// If `OPENROUTER_API_KEY` is missing, OpenRouter returns an error status, or the
/// response can't be parsed as the expected review JSON.
pub async fn review_diff(
    client: &Client,
    cfg: &Config,
    meta: &PrMeta,
    diff: &str,
    omitted_note: Option<String>,
    structural_context: Option<&str>,
    system_prompt: &str,
) -> Result<ReviewResult> {
    require(&cfg.openrouter_api_key, "OPENROUTER_API_KEY")?;

    // Safety clamp: the diff is already packed to fit, but a lone giant file can
    // still exceed the cap — hard-trim it and flag the truncation.
    let truncated = diff.chars().count() > cfg.max_diff_chars;
    let clipped: String = if truncated {
        diff.chars().take(cfg.max_diff_chars).collect()
    } else {
        diff.to_string()
    };

    let req = ChatReq {
        model: cfg.openrouter_model.clone(),
        max_tokens: cfg.openrouter_max_tokens,
        temperature: cfg.openrouter_temperature,
        messages: vec![
            Msg {
                role: "system".into(),
                content: system_prompt.to_string(),
            },
            Msg {
                role: "user".into(),
                content: build_user_prompt(
                    meta,
                    &clipped,
                    truncated,
                    omitted_note.as_deref(),
                    structural_context,
                ),
            },
        ],
    };

    let res = client
        .post(format!("{}/chat/completions", cfg.openrouter_base_url))
        .bearer_auth(&cfg.openrouter_api_key)
        .header("HTTP-Referer", &cfg.http_referer)
        .header("X-Title", &cfg.x_title)
        .json(&req)
        .send()
        .await?;

    let status = res.status();
    let text = res.text().await?;
    let data: ChatRes = serde_json::from_str(&text).map_err(|e| {
        anyhow::anyhow!(
            "OpenRouter {status}: non-JSON response ({e}): {}",
            clip(&text, 300)
        )
    })?;

    if !status.is_success() || data.error.is_some() {
        let msg = data
            .error
            .and_then(|e| e.message)
            .unwrap_or_else(|| clip(&text, 500));
        anyhow::bail!("OpenRouter {status}: {msg}");
    }

    let content = data
        .choices
        .and_then(|c| c.into_iter().next())
        .and_then(|c| c.message)
        .and_then(|m| m.content)
        .ok_or_else(|| anyhow::anyhow!("OpenRouter returned an empty response."))?;

    let json = extract_json(&content).ok_or_else(|| {
        anyhow::anyhow!(
            "Model did not return a JSON object: {}",
            clip(&content, 300)
        )
    })?;
    let review: Review = serde_json::from_str(json)
        .map_err(|e| anyhow::anyhow!("Could not parse review JSON ({e}): {}", clip(json, 300)))?;

    Ok(ReviewResult {
        review,
        model: cfg.openrouter_model.clone(),
        usage: data.usage,
    })
}

/// Second-pass "self-critique": ask the model to prune false positives, duplicates,
/// and out-of-scope nits from a set of proposed findings, and to assign an honest
/// confidence to each survivor.
///
/// Runs on `backend` — the same backend that produced the review — via
/// [`crate::backend::ReviewBackend::complete`]. It used to post to OpenRouter
/// directly, which meant any consumer with its own backend (an agent CLI, a local
/// model) lost the noise filter entirely unless it also held an OpenRouter key. The
/// default backend still resolves `complete()` to the OpenRouter chat path, so
/// nothing changes for the bot.
///
/// The caller MUST treat any error as fail-open (keep the original findings) — a
/// critique hiccup must never drop the review.
///
/// # Errors
/// If the backend call fails, or the response can't be parsed as a JSON array of
/// findings.
pub async fn critique_findings(
    cfg: &Config,
    backend: &dyn crate::backend::ReviewBackend,
    meta: &PrMeta,
    diff: &str,
    findings: &[Finding],
) -> Result<Vec<Finding>> {
    let clipped: String = diff.chars().take(cfg.max_diff_chars).collect();
    let findings_json = serde_json::to_string_pretty(findings)
        .map_err(|e| anyhow::anyhow!("could not serialize findings for critique: {e}"))?;
    let user = format!(
        "Repository: {}\nPull request: #{}\n\n--- BEGIN DIFF ---\n{clipped}\n--- END DIFF ---\n\n--- PROPOSED FINDINGS (JSON) ---\n{findings_json}",
        meta.repo, meta.pr,
    );

    let content = backend.complete(cfg, CRITIQUE_SYSTEM_PROMPT, &user).await?;

    let json = extract_json_array(&content).ok_or_else(|| {
        anyhow::anyhow!(
            "Critique did not return a JSON array: {}",
            clip(&content, 300)
        )
    })?;
    let raw: Vec<serde_json::Value> = serde_json::from_str(json)
        .map_err(|e| anyhow::anyhow!("Could not parse critique JSON ({e}): {}", clip(json, 300)))?;
    let (kept, dropped) = findings_from_values(raw);
    // If the critique returned elements but none survived, its shape is wrong — error
    // so the caller fails open and keeps the original findings. Silently returning an
    // empty list here would delete every finding in the review.
    if kept.is_empty() && dropped > 0 {
        anyhow::bail!(
            "Critique returned {dropped} unparseable finding(s): {}",
            clip(json, 300)
        );
    }

    Ok(kept)
}

/// One-shot chat completion returning the raw assistant text. Shares the same
/// OpenRouter call pattern (headers, base URL, synthesis model) as [`review_diff`].
///
/// # Errors
/// If `OPENROUTER_API_KEY` is missing, OpenRouter returns an error status, or the
/// response has no content.
pub(crate) async fn chat_text(
    client: &Client,
    cfg: &Config,
    system: &str,
    user: &str,
) -> Result<String> {
    require(&cfg.openrouter_api_key, "OPENROUTER_API_KEY")?;

    let req = ChatReq {
        model: cfg.openrouter_model.clone(),
        max_tokens: cfg.openrouter_max_tokens,
        temperature: cfg.openrouter_temperature,
        messages: vec![
            Msg {
                role: "system".into(),
                content: system.to_string(),
            },
            Msg {
                role: "user".into(),
                content: user.to_string(),
            },
        ],
    };

    let res = client
        .post(format!("{}/chat/completions", cfg.openrouter_base_url))
        .bearer_auth(&cfg.openrouter_api_key)
        .header("HTTP-Referer", &cfg.http_referer)
        .header("X-Title", &cfg.x_title)
        .json(&req)
        .send()
        .await?;

    let status = res.status();
    let text = res.text().await?;
    let data: ChatRes = serde_json::from_str(&text).map_err(|e| {
        anyhow::anyhow!(
            "OpenRouter {status}: non-JSON response ({e}): {}",
            clip(&text, 300)
        )
    })?;

    if !status.is_success() || data.error.is_some() {
        let msg = data
            .error
            .and_then(|e| e.message)
            .unwrap_or_else(|| clip(&text, 500));
        anyhow::bail!("OpenRouter {status}: {msg}");
    }

    data.choices
        .and_then(|c| c.into_iter().next())
        .and_then(|c| c.message)
        .and_then(|m| m.content)
        .map(|c| c.trim().to_string())
        .filter(|c| !c.is_empty())
        .ok_or_else(|| anyhow::anyhow!("OpenRouter returned an empty response."))
}

/// Answer a free-form question about a PR (the `/ask` command), grounded in its
/// diff. Returns the answer as markdown.
///
/// # Errors
/// If `OPENROUTER_API_KEY` is missing or the OpenRouter call fails.
pub async fn answer_question(
    cfg: &Config,
    backend: &dyn crate::backend::ReviewBackend,
    meta: &PrMeta,
    diff: &str,
    question: &str,
    structural_context: Option<&str>,
) -> Result<String> {
    let clipped: String = diff.chars().take(cfg.max_diff_chars).collect();
    let truncated = diff.chars().count() > cfg.max_diff_chars;
    let context = build_user_prompt(meta, &clipped, truncated, None, structural_context);
    let user = format!("{context}\n\n--- QUESTION ---\n{}", question.trim());
    let system = if cfg.extra_system_prompt.is_empty() {
        ASK_SYSTEM_PROMPT.to_string()
    } else {
        format!("{ASK_SYSTEM_PROMPT}\n{}", cfg.extra_system_prompt)
    };
    backend.complete(cfg, &system, &user).await
}

/// Generate a PR description from its diff (the `/describe` command). Returns
/// markdown (no title header — the PR already has a title).
///
/// # Errors
/// If `OPENROUTER_API_KEY` is missing or the OpenRouter call fails.
pub async fn describe_pr(
    cfg: &Config,
    backend: &dyn crate::backend::ReviewBackend,
    meta: &PrMeta,
    diff: &str,
    structural_context: Option<&str>,
) -> Result<String> {
    let clipped: String = diff.chars().take(cfg.max_diff_chars).collect();
    let truncated = diff.chars().count() > cfg.max_diff_chars;
    let user = build_user_prompt(meta, &clipped, truncated, None, structural_context);
    backend.complete(cfg, DESCRIBE_SYSTEM_PROMPT, &user).await
}

/// Deep-review an ENTIRE file (the `/review-file` command): number the file's
/// lines, ask the model for the structured review JSON, and parse it. Findings may
/// anchor to any line in the file (not just diff lines).
///
/// # Errors
/// On a backend failure, or if the model doesn't return a parseable review.
pub async fn review_file(
    cfg: &Config,
    backend: &dyn crate::backend::ReviewBackend,
    path: &str,
    content: &str,
) -> Result<Review> {
    // 1-index the lines so the model can anchor findings to real line numbers.
    let numbered: String = content
        .lines()
        .enumerate()
        .map(|(i, l)| format!("{}: {l}", i + 1))
        .collect::<Vec<_>>()
        .join("\n");
    let clipped: String = numbered.chars().take(cfg.max_diff_chars).collect();
    let truncated = numbered.chars().count() > cfg.max_diff_chars;
    let user = format!(
        "File: {path}{}\n\n{clipped}",
        if truncated {
            "\n[NOTE: file truncated to the size limit — review what is shown]"
        } else {
            ""
        }
    );
    let system = if cfg.extra_system_prompt.is_empty() {
        FILE_REVIEW_SYSTEM_PROMPT.to_string()
    } else {
        format!("{FILE_REVIEW_SYSTEM_PROMPT}\n{}", cfg.extra_system_prompt)
    };
    let raw = backend.complete(cfg, &system, &user).await?;
    let json = extract_json(&raw)
        .ok_or_else(|| anyhow::anyhow!("file review returned no JSON: {}", clip(&raw, 300)))?;
    let review: Review = serde_json::from_str(json)
        .map_err(|e| anyhow::anyhow!("could not parse file review ({e}): {}", clip(json, 300)))?;
    Ok(review)
}

#[cfg(test)]
mod tests {
    //! Deserialization tolerance. A model that drops a field on one finding used to
    //! cost the entire review (seen in production: `missing field \`severity\``
    //! after a ~5-minute agent run). These pin the salvage behaviour.

    use super::{findings_from_values, Review};

    #[test]
    fn finding_missing_severity_defaults_to_medium() {
        let review: Review = serde_json::from_str(
            r#"{"summary":"s","recommendation":"APPROVE WITH CHANGES",
                "findings":[{"file":"a.rs","line":11,"body":"b"}]}"#,
        )
        .expect("a missing severity must not fail the whole review");
        assert_eq!(review.findings.len(), 1);
        assert_eq!(review.findings[0].severity, "MEDIUM");
    }

    #[test]
    fn finding_missing_file_still_parses_and_folds_to_summary() {
        let review: Review = serde_json::from_str(
            r#"{"summary":"s","recommendation":"APPROVE",
                "findings":[{"severity":"HIGH","body":"b"}]}"#,
        )
        .expect("a missing file must not fail the whole review");
        assert_eq!(review.findings[0].file, "");
        assert_eq!(review.findings[0].line, None);
    }

    #[test]
    fn one_malformed_finding_is_dropped_not_fatal() {
        // Element 2 has no `body` — nothing to post — so it goes, and the two real
        // findings survive.
        let review: Review = serde_json::from_str(
            r#"{"summary":"s","recommendation":"BLOCK","findings":[
                {"severity":"HIGH","file":"a.rs","line":3,"body":"real"},
                {"severity":"LOW","file":"b.rs"},
                {"file":"c.rs","body":"also real"}]}"#,
        )
        .expect("one bad element must not fail the whole review");
        assert_eq!(review.findings.len(), 2);
        assert_eq!(review.findings[1].severity, "MEDIUM");
    }

    #[test]
    fn required_fields_of_the_review_itself_still_hard_fail() {
        // `summary`/`recommendation` stay mandatory: without them there is no review
        // to post, so failing loudly is right.
        assert!(serde_json::from_str::<Review>(r#"{"summary":"s","findings":[]}"#).is_err());
    }

    #[test]
    fn findings_from_values_reports_what_it_dropped() {
        let raw = vec![
            serde_json::json!({"file": "a.rs", "body": "real"}),
            serde_json::json!({"file": "b.rs"}),
            serde_json::json!("not even an object"),
        ];
        let (kept, dropped) = findings_from_values(raw);
        assert_eq!(kept.len(), 1);
        assert_eq!(dropped, 2);
    }
}