pr-review-core 0.10.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
//! 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, 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>,
}

/// One review finding from the model.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Finding {
    pub severity: String,
    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>,
}

/// The structured review the model returns.
#[derive(Debug, Clone, Deserialize)]
pub struct Review {
    pub summary: String,
    pub recommendation: String,
    #[serde(default)]
    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.
///
/// # 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>,
) -> 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 system_prompt = if cfg.extra_system_prompt.is_empty() {
        SYSTEM_PROMPT.to_string()
    } else {
        format!("{SYSTEM_PROMPT}\n{}", cfg.extra_system_prompt)
    };

    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,
            },
            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. Uses the same OpenRouter call pattern as
/// [`review_diff`] (same headers, base URL, and synthesis model).
///
/// The caller MUST treat any error as fail-open (keep the original findings) — a
/// critique hiccup must never drop the review.
///
/// # Errors
/// If `OPENROUTER_API_KEY` is missing, OpenRouter returns an error status, or the
/// response can't be parsed as a JSON array of findings.
pub async fn critique_findings(
    client: &Client,
    cfg: &Config,
    meta: &PrMeta,
    diff: &str,
    findings: &[Finding],
) -> Result<Vec<Finding>> {
    require(&cfg.openrouter_api_key, "OPENROUTER_API_KEY")?;

    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 req = ChatReq {
        model: cfg.openrouter_model.clone(),
        max_tokens: cfg.openrouter_max_tokens,
        temperature: cfg.openrouter_temperature,
        messages: vec![
            Msg {
                role: "system".into(),
                content: CRITIQUE_SYSTEM_PROMPT.to_string(),
            },
            Msg {
                role: "user".into(),
                content: user,
            },
        ],
    };

    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 critique response."))?;

    let json = extract_json_array(&content).ok_or_else(|| {
        anyhow::anyhow!(
            "Critique did not return a JSON array: {}",
            clip(&content, 300)
        )
    })?;
    let kept: Vec<Finding> = serde_json::from_str(json)
        .map_err(|e| anyhow::anyhow!("Could not parse critique JSON ({e}): {}", 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)
}