| 1 | //! Tool for structured code reviews of files, diffs, or pull requests. |
| 2 | |
| 3 | use std::borrow::Cow; |
| 4 | use std::fs; |
| 5 | use std::path::{Path, PathBuf}; |
| 6 | |
| 7 | use async_trait::async_trait; |
| 8 | use chrono::{SecondsFormat, Utc}; |
| 9 | use serde::{Deserialize, Serialize}; |
| 10 | use serde_json::{Value, json}; |
| 11 | |
| 12 | use crate::client::CodewhaleClient; |
| 13 | #[cfg(test)] |
| 14 | use codewhale_dependencies::ExternalTool; |
| 15 | use codewhale_models::Usage; |
| 16 | use codewhale_util::utils::truncate_with_ellipsis; |
| 17 | |
| 18 | use super::spec::{ |
| 19 | ApprovalRequirement, ToolCapability, ToolContext, ToolError, ToolResult, ToolSpec, |
| 20 | optional_bool, optional_str, optional_u64, required_str, |
| 21 | }; |
| 22 | |
| 23 | const DEFAULT_MAX_CHARS: usize = 200_000; |
| 24 | const MAX_MAX_CHARS: usize = 1_000_000; |
| 25 | pub const MAX_REVIEW_PASSES: usize = 64; |
| 26 | const FALLBACK_MAX_CHARS: usize = 4000; |
| 27 | const REVIEW_RECEIPT_SCHEMA_VERSION: u32 = 1; |
| 28 | const PR_COVERAGE_RECEIPT_SCHEMA_VERSION: u32 = 2; |
| 29 | |
| 30 | /// Rank used to bound reasoning level without depending on `Ord`. |
| 31 | fn reasoning_effort_rank(effort: crate::reasoning_preference::ReasoningEffort) -> u8 { |
| 32 | use crate::reasoning_preference::ReasoningEffort; |
| 33 | match effort { |
| 34 | ReasoningEffort::Off => 0, |
| 35 | ReasoningEffort::Minimal => 1, |
| 36 | ReasoningEffort::Low => 2, |
| 37 | ReasoningEffort::Medium => 3, |
| 38 | ReasoningEffort::High => 4, |
| 39 | ReasoningEffort::XHigh => 5, |
| 40 | ReasoningEffort::Ultra => 6, |
| 41 | ReasoningEffort::Max => 7, |
| 42 | // `Auto` is resolved from the prompt before this bound is applied; if |
| 43 | // it somehow arrives unresolved, treat it as the medium default rather |
| 44 | // than silently unbounded. |
| 45 | ReasoningEffort::Auto => 3, |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | fn reasoning_effort_from_rank(rank: u8) -> crate::reasoning_preference::ReasoningEffort { |
| 50 | use crate::reasoning_preference::ReasoningEffort; |
| 51 | match rank { |
| 52 | 0 => ReasoningEffort::Off, |
| 53 | 1 => ReasoningEffort::Minimal, |
| 54 | 2 => ReasoningEffort::Low, |
| 55 | 3 => ReasoningEffort::Medium, |
| 56 | 4 => ReasoningEffort::High, |
| 57 | 5 => ReasoningEffort::XHigh, |
| 58 | 6 => ReasoningEffort::Ultra, |
| 59 | _ => ReasoningEffort::Max, |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | /// Highest reasoning level a review pass may request, given the visible-text |
| 64 | /// reserve this exact model needs (`route_budget::review_visible_text_reserve_percent`). |
| 65 | /// |
| 66 | /// A review pass only has to rank findings, so unbounded reasoning buys little |
| 67 | /// while a shared `max_tokens` allowance lets it consume everything: #6285 saw |
| 68 | /// `reasoning_tokens == output_tokens == 65536`, stop reason `length`, zero |
| 69 | /// visible text, and a PR blocked with no findings shown. The cap scales with |
| 70 | /// the reserve the model actually needs and never raises the caller's request. |
| 71 | /// An allowance of 8K or less on a reasoning model caps at Low, because a |
| 72 | /// medium-or-higher pass can spend that whole allowance reasoning (#7067). |
| 73 | /// |
| 74 | /// What this does not do: it cannot separate reasoning from text on a route |
| 75 | /// that exposes no effort knob, and it does not re-request a pass that already |
| 76 | /// exhausted its allowance — that stays a reported budget outcome. |
| 77 | #[must_use] |
| 78 | pub fn bounded_review_reasoning_effort( |
| 79 | requested: crate::reasoning_preference::ReasoningEffort, |
| 80 | reserve_percent: u32, |
| 81 | allowance: u32, |
| 82 | ) -> crate::reasoning_preference::ReasoningEffort { |
| 83 | let mut ceiling = match reserve_percent { |
| 84 | // Nothing reserved: the model does not reason, so nothing to bound. |
| 85 | 0 => u8::MAX, |
| 86 | // A quarter of the allowance must survive as text. |
| 87 | 1..=25 => 3, |
| 88 | // Half the allowance must survive as text. |
| 89 | _ => 2, |
| 90 | }; |
| 91 | if reserve_percent > 0 && allowance <= super::review_triage::REASONING_ROUTE_MIN_OUTPUT_TOKENS { |
| 92 | ceiling = ceiling.min(2); |
| 93 | } |
| 94 | reasoning_effort_from_rank(reasoning_effort_rank(requested).min(ceiling)) |
| 95 | } |
| 96 | |
| 97 | /// Budget for how many lines a committable suggestion may replace. A |
| 98 | /// mechanical fix is small; anything larger is judgement wearing a |
| 99 | /// suggestion fence, so it must degrade to prose. |
| 100 | pub const MAX_COMMITTABLE_SUGGESTION_LINES: u32 = 25; |
| 101 | const REVIEW_CLIENT_UNAVAILABLE: &str = "Review tool requires an active Codewhale model client"; |
| 102 | |
| 103 | /// What kind of claim this is. `defect` is a wrong behaviour in the changed |
| 104 | /// code; `intent` is a mismatch between what the change says it does and what |
| 105 | /// it does; `contract` is a dependent outside the diff that the change broke. |
| 106 | /// The distinction exists because the three need different evidence and a |
| 107 | /// reader triages them differently. |
| 108 | #[derive(Debug, Clone, Default, Serialize, Deserialize)] |
| 109 | pub struct ReviewIssue { |
| 110 | #[serde(default)] |
| 111 | pub severity: String, |
| 112 | #[serde(default)] |
| 113 | pub title: String, |
| 114 | #[serde(default)] |
| 115 | pub description: String, |
| 116 | #[serde(default)] |
| 117 | pub path: Option<String>, |
| 118 | #[serde(default)] |
| 119 | pub line: Option<u32>, |
| 120 | /// `defect`, `intent` or `contract`. Absent on older receipts and model |
| 121 | /// output written before this field existed, and read as `defect`. |
| 122 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 123 | pub kind: Option<String>, |
| 124 | /// How the reviewer established the claim. `reproduced` requires a |
| 125 | /// command; `traced` requires `path:line`; `suspected` is never posted |
| 126 | /// inline and is moved to the summary's "worth a human look" list. |
| 127 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 128 | pub evidence: Option<ReviewEvidence>, |
| 129 | /// For a `contract` claim: what the change made newly true or false, and |
| 130 | /// which dependents were checked against it. |
| 131 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 132 | pub contract: Option<ReviewContract>, |
| 133 | /// Whether this change introduced the defect or merely exposed it. |
| 134 | /// |
| 135 | /// `introduced` or `preexisting`. Set **mechanically** from the diff by the |
| 136 | /// review core, never taken from the model: a reviewer that can label its |
| 137 | /// own accusation as someone else's problem is not a reviewer worth |
| 138 | /// trusting. A `preexisting` claim is a real bug on code this change did |
| 139 | /// not touch, reported without attributing it to the author. |
| 140 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 141 | pub authorship: Option<String>, |
| 142 | /// False when the claim cannot land on a line of this diff. Such a claim is |
| 143 | /// still reported — in the review body rather than inline — because losing |
| 144 | /// a proven finding to a line-number disagreement is worse than reporting |
| 145 | /// it in the wrong place. |
| 146 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 147 | pub inline_anchorable: Option<bool>, |
| 148 | } |
| 149 | |
| 150 | #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] |
| 151 | pub struct ReviewEvidence { |
| 152 | /// `reproduced`, `traced` or `suspected`. |
| 153 | #[serde(default)] |
| 154 | pub tier: String, |
| 155 | /// The command and its output for `reproduced`, or the input and the |
| 156 | /// `path:line` chain for `traced`. Free text, rendered verbatim. |
| 157 | #[serde(default)] |
| 158 | pub detail: String, |
| 159 | } |
| 160 | |
| 161 | #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] |
| 162 | pub struct ReviewContract { |
| 163 | /// What became newly true or newly false at the changed line. |
| 164 | #[serde(default)] |
| 165 | pub became: String, |
| 166 | /// Dependents of that contract the reviewer checked, as `path:line` or a |
| 167 | /// path with a symbol. An empty list is honest: it means none were found. |
| 168 | #[serde(default)] |
| 169 | pub dependents_checked: Vec<String>, |
| 170 | } |
| 171 | |
| 172 | #[derive(Debug, Clone, Default, Serialize, Deserialize)] |
| 173 | pub struct ReviewSuggestion { |
| 174 | #[serde(default)] |
| 175 | pub path: Option<String>, |
| 176 | #[serde(default)] |
| 177 | pub line: Option<u32>, |
| 178 | /// First line of the replaced span (inclusive). `None` means the |
| 179 | /// suggestion covers a single line, `line`. |
| 180 | #[serde(default)] |
| 181 | pub start_line: Option<u32>, |
| 182 | /// Last line of the replaced span (inclusive). Defaults to `line`. |
| 183 | #[serde(default)] |
| 184 | pub end_line: Option<u32>, |
| 185 | /// Prose: why the change is wanted. |
| 186 | #[serde(default)] |
| 187 | pub suggestion: String, |
| 188 | /// Literal replacement source for `start_line..=end_line`, indentation |
| 189 | /// included. `Some` only for mechanical, high-confidence fixes; when it |
| 190 | /// is `None` the reviewer posts prose instead of a committable |
| 191 | /// GitHub suggestion block. |
| 192 | #[serde(default)] |
| 193 | pub replacement: Option<String>, |
| 194 | } |
| 195 | |
| 196 | #[derive(Debug, Clone, Default, Serialize, Deserialize)] |
| 197 | pub struct ReviewOutput { |
| 198 | #[serde(default)] |
| 199 | pub summary: String, |
| 200 | #[serde(default)] |
| 201 | pub issues: Vec<ReviewIssue>, |
| 202 | #[serde(default)] |
| 203 | pub suggestions: Vec<ReviewSuggestion>, |
| 204 | #[serde(default)] |
| 205 | pub overall_assessment: String, |
| 206 | /// `low`, `medium` or `high`, with the reason, so the person merging gets |
| 207 | /// the answer they actually want before reading a single finding. |
| 208 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 209 | pub merge_risk: Option<ReviewMergeRisk>, |
| 210 | /// What the reviewer established rather than suspected: dependents read, |
| 211 | /// commands run and their results. |
| 212 | #[serde(default, skip_serializing_if = "Vec::is_empty")] |
| 213 | pub verified: Vec<String>, |
| 214 | /// What was not reviewed, and why. An honest gap, not a blank cheque. |
| 215 | #[serde(default, skip_serializing_if = "Vec::is_empty")] |
| 216 | pub not_reviewed: Vec<String>, |
| 217 | /// What the reviewer examined and found sound, with the reason. A negative |
| 218 | /// result, not a claim: it never counts toward merge risk and never becomes |
| 219 | /// an inline comment. This is what lets a reader stop checking something. |
| 220 | #[serde(default, skip_serializing_if = "Vec::is_empty")] |
| 221 | pub ruled_out: Vec<String>, |
| 222 | #[serde(default, skip_serializing_if = "Vec::is_empty")] |
| 223 | pub resolved_findings: Vec<ReviewResolution>, |
| 224 | } |
| 225 | |
| 226 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 227 | pub struct ReviewResolution { |
| 228 | pub key: String, |
| 229 | pub evidence: ReviewEvidence, |
| 230 | } |
| 231 | |
| 232 | #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] |
| 233 | pub struct ReviewMergeRisk { |
| 234 | /// `low`, `medium` or `high`. |
| 235 | #[serde(default)] |
| 236 | pub level: String, |
| 237 | #[serde(default)] |
| 238 | pub reason: String, |
| 239 | } |
| 240 | |
| 241 | impl ReviewOutput { |
| 242 | pub fn note_binary_coverage(&mut self, diff: &str) { |
| 243 | if diff.contains("\nGIT binary patch\n") || diff.contains("\nBinary files ") { |
| 244 | self.summary.push_str("\nCoverage limitation: binary changes were represented by metadata; their contents were not semantically inspected."); |
| 245 | } |
| 246 | } |
| 247 | |
| 248 | #[must_use] |
| 249 | pub fn parse(raw: &str) -> Self { |
| 250 | if let Some(parsed) = parse_review_output_json(raw) { |
| 251 | return parsed.normalize(); |
| 252 | } |
| 253 | if let Some(json_block) = extract_json_block(raw) |
| 254 | && let Some(parsed) = parse_review_output_json(json_block) |
| 255 | { |
| 256 | return parsed.normalize(); |
| 257 | } |
| 258 | ReviewOutput::fallback(raw) |
| 259 | } |
| 260 | |
| 261 | /// Parse `raw` only when it is the structured review contract (all four |
| 262 | /// top-level fields present), unlike [`Self::parse`], which falls |
| 263 | /// back to wrapping prose. |
| 264 | pub fn from_structured_str(raw: &str) -> Option<Self> { |
| 265 | let candidate = serde_json::from_str::<Value>(raw) |
| 266 | .ok() |
| 267 | .or_else(|| extract_json_block(raw).and_then(|json| serde_json::from_str(json).ok()))?; |
| 268 | let object = candidate.as_object()?; |
| 269 | (object.get("summary")?.is_string() |
| 270 | && object.get("issues")?.is_array() |
| 271 | && object.get("suggestions")?.is_array() |
| 272 | && object.get("overall_assessment")?.is_string()) |
| 273 | .then(|| serde_json::from_value::<ReviewOutput>(candidate).ok()) |
| 274 | .flatten() |
| 275 | .map(Self::normalize) |
| 276 | } |
| 277 | |
| 278 | fn fallback(raw: &str) -> Self { |
| 279 | let trimmed = raw.trim(); |
| 280 | let summary = if trimmed.is_empty() { |
| 281 | "Review completed but no structured output was returned.".to_string() |
| 282 | } else { |
| 283 | truncate_with_ellipsis(trimmed, FALLBACK_MAX_CHARS, "\n...[truncated]\n") |
| 284 | }; |
| 285 | Self { |
| 286 | summary, |
| 287 | ..Self::default() |
| 288 | } |
| 289 | } |
| 290 | |
| 291 | fn normalize(mut self) -> Self { |
| 292 | self.summary = self.summary.trim().to_string(); |
| 293 | self.overall_assessment = self.overall_assessment.trim().to_string(); |
| 294 | for issue in &mut self.issues { |
| 295 | issue.severity = normalize_severity(&issue.severity); |
| 296 | issue.title = issue.title.trim().to_string(); |
| 297 | issue.description = issue.description.trim().to_string(); |
| 298 | issue.path = normalize_optional(issue.path.take()); |
| 299 | issue.kind = issue |
| 300 | .kind |
| 301 | .take() |
| 302 | .map(|kind| normalize_claim_kind(&kind)) |
| 303 | .filter(|kind| !kind.is_empty()); |
| 304 | if let Some(evidence) = issue.evidence.as_mut() { |
| 305 | evidence.tier = normalize_evidence_tier(&evidence.tier); |
| 306 | evidence.detail = evidence.detail.trim().to_string(); |
| 307 | } |
| 308 | issue.authorship = issue.authorship.take().map(|value| { |
| 309 | match value.trim().to_ascii_lowercase().as_str() { |
| 310 | "preexisting" | "pre-existing" | "pre_existing" | "existing" => "preexisting", |
| 311 | _ => "introduced", |
| 312 | } |
| 313 | .to_string() |
| 314 | }); |
| 315 | if let Some(contract) = issue.contract.as_mut() { |
| 316 | contract.became = contract.became.trim().to_string(); |
| 317 | contract.dependents_checked = contract |
| 318 | .dependents_checked |
| 319 | .iter() |
| 320 | .map(|entry| entry.trim().to_string()) |
| 321 | .filter(|entry| !entry.is_empty()) |
| 322 | .collect(); |
| 323 | } |
| 324 | } |
| 325 | if let Some(risk) = self.merge_risk.as_mut() { |
| 326 | risk.level = match risk.level.trim().to_ascii_lowercase().as_str() { |
| 327 | "high" | "blocking" | "blocker" => "high", |
| 328 | "medium" | "moderate" | "concern" => "medium", |
| 329 | _ => "low", |
| 330 | } |
| 331 | .to_string(); |
| 332 | risk.reason = risk.reason.trim().to_string(); |
| 333 | } |
| 334 | self.verified = self |
| 335 | .verified |
| 336 | .iter() |
| 337 | .map(|entry| entry.trim().to_string()) |
| 338 | .filter(|entry| !entry.is_empty()) |
| 339 | .collect(); |
| 340 | self.not_reviewed = self |
| 341 | .not_reviewed |
| 342 | .iter() |
| 343 | .map(|entry| entry.trim().to_string()) |
| 344 | .filter(|entry| !entry.is_empty()) |
| 345 | .collect(); |
| 346 | self.ruled_out = self |
| 347 | .ruled_out |
| 348 | .iter() |
| 349 | .map(|entry| entry.trim().to_string()) |
| 350 | .filter(|entry| !entry.is_empty()) |
| 351 | .collect(); |
| 352 | for suggestion in &mut self.suggestions { |
| 353 | suggestion.suggestion = suggestion.suggestion.trim().to_string(); |
| 354 | suggestion.path = normalize_optional(suggestion.path.take()); |
| 355 | // Leading whitespace in `replacement` is load-bearing indentation, |
| 356 | // so only trailing newlines and all-whitespace payloads are |
| 357 | // normalized away. |
| 358 | suggestion.replacement = suggestion |
| 359 | .replacement |
| 360 | .take() |
| 361 | .map(|replacement| replacement.trim_end_matches(['\n', '\r']).to_string()) |
| 362 | .filter(|replacement| !replacement.trim().is_empty()); |
| 363 | } |
| 364 | self |
| 365 | } |
| 366 | } |
| 367 | |
| 368 | #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] |
| 369 | pub struct PrReviewPassManifest { |
| 370 | pub number: usize, |
| 371 | pub diff_fingerprint: String, |
| 372 | pub diff_chars: usize, |
| 373 | /// Number of entries in `files`: whole file patches plus, for an |
| 374 | /// oversized text file, its `(part k/n)` parts. Parts of one file never |
| 375 | /// share a pass — their combined size exceeds the whole file, which |
| 376 | /// already exceeded the per-pass limit — so this is also the distinct |
| 377 | /// file count of the pass and parts cannot inflate coverage. |
| 378 | pub file_count: usize, |
| 379 | pub files: Vec<String>, |
| 380 | } |
| 381 | |
| 382 | /// One file patch the plan never scheduled (#6285 AC3/AC4). `file` is the |
| 383 | /// patch label exactly as it would have appeared in a pass manifest |
| 384 | /// (`a/old b/new`, or `… (part k/n)` for a pass-budget cut); `chars` is the |
| 385 | /// budgeted `model_diff` size. |
| 386 | #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] |
| 387 | pub struct PrReviewSkippedFile { |
| 388 | pub file: String, |
| 389 | pub reason: String, |
| 390 | pub chars: usize, |
| 391 | } |
| 392 | |
| 393 | /// Skip reasons are stable sentence fragments rendered into review |
| 394 | /// summaries, receipts, and failure notes; keep them greppable. |
| 395 | const SKIP_REASON_HUNK_EXCEEDS_PASS: &str = "a single hunk exceeds the per-pass limit"; |
| 396 | const SKIP_REASON_NO_HUNK_BOUNDARIES: &str = |
| 397 | "exceeds the per-pass limit with no hunk boundaries to split at"; |
| 398 | const SKIP_REASON_BEYOND_MAX_PASSES: &str = "beyond the max_passes budget"; |
| 399 | |
| 400 | /// Render a skip list the way every consumer shows it: the entries are |
| 401 | /// self-describing, so no caller needs its own format. |
| 402 | pub fn format_skipped_files(skipped: &[PrReviewSkippedFile]) -> String { |
| 403 | skipped |
| 404 | .iter() |
| 405 | .map(|skip| format!("{} ({} chars; {})", skip.file, skip.chars, skip.reason)) |
| 406 | .collect::<Vec<_>>() |
| 407 | .join(", ") |
| 408 | } |
| 409 | |
| 410 | #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] |
| 411 | pub struct PrReviewManifest { |
| 412 | pub base_sha: String, |
| 413 | pub head_sha: String, |
| 414 | pub diff_fingerprint: String, |
| 415 | pub diff_chars: usize, |
| 416 | pub file_count: usize, |
| 417 | pub binary_file_patches: usize, |
| 418 | pub binary_contents_semantically_inspected: bool, |
| 419 | pub max_chars_per_pass: usize, |
| 420 | pub passes: Vec<PrReviewPassManifest>, |
| 421 | /// Files the plan never scheduled, in diff order. Empty means complete |
| 422 | /// coverage; every entry names a file the gate did not read and why. |
| 423 | /// `#[serde(default)]` keeps pre-skip-list receipts readable — those |
| 424 | /// plans were complete by construction. |
| 425 | #[serde(default)] |
| 426 | pub skipped_files: Vec<PrReviewSkippedFile>, |
| 427 | } |
| 428 | |
| 429 | #[derive(Debug, Clone)] |
| 430 | pub struct PrReviewPass { |
| 431 | pub manifest: PrReviewPassManifest, |
| 432 | pub diff: String, |
| 433 | } |
| 434 | |
| 435 | #[derive(Debug, Clone)] |
| 436 | pub struct PrReviewPlan { |
| 437 | pub manifest: PrReviewManifest, |
| 438 | pub passes: Vec<PrReviewPass>, |
| 439 | } |
| 440 | |
| 441 | fn patch_label(patch: &str) -> String { |
| 442 | patch |
| 443 | .lines() |
| 444 | .next() |
| 445 | .and_then(|line| line.strip_prefix("diff --git ")) |
| 446 | .unwrap_or("(unknown file)") |
| 447 | .to_string() |
| 448 | } |
| 449 | |
| 450 | fn pr_file_patches(diff: &str) -> Vec<&str> { |
| 451 | let mut starts = diff |
| 452 | .match_indices("diff --git ") |
| 453 | .filter_map(|(offset, _)| { |
| 454 | (offset == 0 || diff.as_bytes().get(offset.wrapping_sub(1)) == Some(&b'\n')) |
| 455 | .then_some(offset) |
| 456 | }) |
| 457 | .collect::<Vec<_>>(); |
| 458 | starts.push(diff.len()); |
| 459 | starts |
| 460 | .windows(2) |
| 461 | .map(|window| &diff[window[0]..window[1]]) |
| 462 | .collect() |
| 463 | } |
| 464 | |
| 465 | /// Split one file patch into its full header (`diff --git` through the `+++` |
| 466 | /// line) and its complete unified-diff hunks, every slice byte-exact. A patch |
| 467 | /// without hunks (binary or metadata-only) is all header and cannot be split. |
| 468 | fn pr_file_hunks(patch: &str) -> (&str, Vec<&str>) { |
| 469 | let mut starts = patch |
| 470 | .match_indices("@@ ") |
| 471 | .filter_map(|(offset, _)| { |
| 472 | (offset == 0 || patch.as_bytes().get(offset.wrapping_sub(1)) == Some(&b'\n')) |
| 473 | .then_some(offset) |
| 474 | }) |
| 475 | .collect::<Vec<_>>(); |
| 476 | let header = starts.first().map_or(patch, |end| &patch[..*end]); |
| 477 | starts.push(patch.len()); |
| 478 | let hunks = starts |
| 479 | .windows(2) |
| 480 | .map(|window| &patch[window[0]..window[1]]) |
| 481 | .collect(); |
| 482 | (header, hunks) |
| 483 | } |
| 484 | |
| 485 | /// One unit of PR review pass packing: a whole file patch, or one part of an |
| 486 | /// oversized text file split at complete hunk boundaries. `header_bytes` is |
| 487 | /// nonzero only on continuation parts, where the full file header is |
| 488 | /// replayed; it is the exact byte prefix to strip when rebuilding the |
| 489 | /// original diff. |
| 490 | struct PrReviewPiece<'a> { |
| 491 | diff: Cow<'a, str>, |
| 492 | label: String, |
| 493 | header_bytes: usize, |
| 494 | } |
| 495 | |
| 496 | /// One diff-ordered unit of a (possibly degraded) plan: a reviewable piece |
| 497 | /// or a skipped original patch. The partition guard rebuilds the diff from |
| 498 | /// both, so every byte is either reviewed or named as skipped. |
| 499 | enum PrReviewAtom<'a> { |
| 500 | Piece(PrReviewPiece<'a>), |
| 501 | Skipped { |
| 502 | patch: &'a str, |
| 503 | label: String, |
| 504 | chars: usize, |
| 505 | reason: &'static str, |
| 506 | }, |
| 507 | } |
| 508 | |
| 509 | /// Plan PR review passes over `diff`, degrading instead of failing closed |
| 510 | /// (#6285 AC3): files that fit no pass and passes beyond `max_passes` are |
| 511 | /// skipped in diff order and named in `manifest.skipped_files` (AC4). Only a |
| 512 | /// plan that covers nothing still errors. |
| 513 | /// |
| 514 | /// Known limitations, beside the behaviour: skips are whole files — a file |
| 515 | /// with one oversized hunk is skipped entirely, never truncated — and files |
| 516 | /// stay in diff order rather than re-sorted by estimated risk. |
| 517 | pub fn plan_pr_review( |
| 518 | diff: &str, |
| 519 | view: &super::review_pr::GhPullRequest, |
| 520 | max_chars: usize, |
| 521 | max_passes: usize, |
| 522 | ) -> anyhow::Result<PrReviewPlan> { |
| 523 | anyhow::ensure!(max_chars > 0, "Review max_chars must be positive"); |
| 524 | anyhow::ensure!( |
| 525 | (1..=MAX_REVIEW_PASSES).contains(&max_passes), |
| 526 | "Review max_passes must be from 1 to {MAX_REVIEW_PASSES}" |
| 527 | ); |
| 528 | let patches = pr_file_patches(diff); |
| 529 | anyhow::ensure!( |
| 530 | patches.len() == view.changed_files && !patches.is_empty(), |
| 531 | "Complete PR review plan found {} file patches; expected {}", |
| 532 | patches.len(), |
| 533 | view.changed_files |
| 534 | ); |
| 535 | |
| 536 | // A whole file stays together whenever it fits. An oversized text file |
| 537 | // splits only at complete hunk boundaries, with the full file header |
| 538 | // replayed into every part so each part stays a self-describing patch; |
| 539 | // no line is elided, shortened or reordered. Sizes use the model |
| 540 | // representation, so a binary payload already omitted there can never |
| 541 | // drive a split. |
| 542 | let mut atoms: Vec<PrReviewAtom<'_>> = Vec::new(); |
| 543 | for patch in patches { |
| 544 | let patch_chars = super::review_pr::model_diff(patch).chars().count(); |
| 545 | if patch_chars <= max_chars { |
| 546 | atoms.push(PrReviewAtom::Piece(PrReviewPiece { |
| 547 | diff: Cow::Borrowed(patch), |
| 548 | label: patch_label(patch), |
| 549 | header_bytes: 0, |
| 550 | })); |
| 551 | continue; |
| 552 | } |
| 553 | let (header, hunks) = pr_file_hunks(patch); |
| 554 | let header_chars = header.chars().count(); |
| 555 | let largest_hunk_chars = hunks.iter().map(|hunk| hunk.chars().count()).max(); |
| 556 | // A file whose largest hunk cannot share a pass with its own header |
| 557 | // can never be scheduled; it is skipped whole, never truncated, so a |
| 558 | // finding can never rest on half a change. |
| 559 | if !largest_hunk_chars.is_some_and(|hunk_chars| header_chars + hunk_chars <= max_chars) { |
| 560 | atoms.push(PrReviewAtom::Skipped { |
| 561 | patch, |
| 562 | label: patch_label(patch), |
| 563 | chars: patch_chars, |
| 564 | reason: if hunks.is_empty() { |
| 565 | SKIP_REASON_NO_HUNK_BOUNDARIES |
| 566 | } else { |
| 567 | SKIP_REASON_HUNK_EXCEEDS_PASS |
| 568 | }, |
| 569 | }); |
| 570 | continue; |
| 571 | } |
| 572 | let label = patch_label(patch); |
| 573 | let mut parts: Vec<String> = Vec::new(); |
| 574 | let mut part = String::from(header); |
| 575 | let mut part_chars = header_chars; |
| 576 | for hunk in hunks { |
| 577 | let hunk_chars = hunk.chars().count(); |
| 578 | if part_chars > header_chars && part_chars + hunk_chars > max_chars { |
| 579 | parts.push(std::mem::replace(&mut part, String::from(header))); |
| 580 | part_chars = header_chars; |
| 581 | } |
| 582 | part.push_str(hunk); |
| 583 | part_chars += hunk_chars; |
| 584 | } |
| 585 | parts.push(part); |
| 586 | let total = parts.len(); |
| 587 | atoms.extend(parts.into_iter().enumerate().map(|(index, part)| { |
| 588 | PrReviewAtom::Piece(PrReviewPiece { |
| 589 | label: format!("{label} (part {}/{total})", index + 1), |
| 590 | header_bytes: if index == 0 { 0 } else { header.len() }, |
| 591 | diff: Cow::Owned(part), |
| 592 | }) |
| 593 | })); |
| 594 | } |
| 595 | |
| 596 | // The partition guard, byte-for-byte: continuation parts replay the file |
| 597 | // header, so exactly those repeated headers are stripped, skipped |
| 598 | // originals are replayed whole, and the rebuilt plan must equal the |
| 599 | // original diff — every byte is either reviewed or named as skipped. |
| 600 | let mut pieces: Vec<PrReviewPiece<'_>> = Vec::new(); |
| 601 | let mut skipped: Vec<PrReviewSkippedFile> = Vec::new(); |
| 602 | let mut rebuilt = String::with_capacity(diff.len()); |
| 603 | for atom in atoms { |
| 604 | match atom { |
| 605 | PrReviewAtom::Piece(piece) => { |
| 606 | rebuilt.push_str(&piece.diff[piece.header_bytes..]); |
| 607 | pieces.push(piece); |
| 608 | } |
| 609 | PrReviewAtom::Skipped { |
| 610 | patch, |
| 611 | label, |
| 612 | chars, |
| 613 | reason, |
| 614 | } => { |
| 615 | rebuilt.push_str(patch); |
| 616 | skipped.push(PrReviewSkippedFile { |
| 617 | file: label, |
| 618 | reason: reason.to_string(), |
| 619 | chars, |
| 620 | }); |
| 621 | } |
| 622 | } |
| 623 | } |
| 624 | anyhow::ensure!( |
| 625 | rebuilt == diff, |
| 626 | "PR review plan did not partition the complete diff byte-for-byte" |
| 627 | ); |
| 628 | |
| 629 | let mut grouped: Vec<Vec<PrReviewPiece<'_>>> = Vec::new(); |
| 630 | let mut current: Vec<PrReviewPiece<'_>> = Vec::new(); |
| 631 | let mut current_chars = 0; |
| 632 | for piece in pieces { |
| 633 | let piece_chars = super::review_pr::model_diff(&piece.diff).chars().count(); |
| 634 | if !current.is_empty() && current_chars + piece_chars > max_chars { |
| 635 | grouped.push(std::mem::take(&mut current)); |
| 636 | current_chars = 0; |
| 637 | } |
| 638 | current.push(piece); |
| 639 | current_chars += piece_chars; |
| 640 | } |
| 641 | if !current.is_empty() { |
| 642 | grouped.push(current); |
| 643 | } |
| 644 | // Passes beyond the budget are skipped in diff order, never fatal. The |
| 645 | // plan reviews what fits and names the rest. |
| 646 | for group in grouped.split_off(max_passes.min(grouped.len())) { |
| 647 | for piece in group { |
| 648 | let label = piece.label; |
| 649 | let chars = super::review_pr::model_diff(&piece.diff).chars().count(); |
| 650 | skipped.push(PrReviewSkippedFile { |
| 651 | file: label, |
| 652 | reason: SKIP_REASON_BEYOND_MAX_PASSES.to_string(), |
| 653 | chars, |
| 654 | }); |
| 655 | } |
| 656 | } |
| 657 | |
| 658 | // Only a plan that covers nothing still errors — and even then it |
| 659 | // names every skipped file, so the failure reads as limits, not as a |
| 660 | // verdict on the code. |
| 661 | anyhow::ensure!( |
| 662 | !grouped.is_empty(), |
| 663 | "PR review plan covers 0 of {} file patches within {max_chars} characters per pass and {max_passes} pass(es); skipped: {}. No review was run or posted.", |
| 664 | view.changed_files, |
| 665 | format_skipped_files(&skipped) |
| 666 | ); |
| 667 | |
| 668 | let passes = grouped |
| 669 | .into_iter() |
| 670 | .enumerate() |
| 671 | .map(|(index, pieces)| { |
| 672 | let diff = pieces |
| 673 | .iter() |
| 674 | .map(|piece| -> &str { &piece.diff }) |
| 675 | .collect::<String>(); |
| 676 | let labels = pieces |
| 677 | .iter() |
| 678 | .map(|piece| piece.label.clone()) |
| 679 | .collect::<Vec<_>>(); |
| 680 | let manifest = PrReviewPassManifest { |
| 681 | number: index + 1, |
| 682 | diff_fingerprint: diff_fingerprint(&diff), |
| 683 | diff_chars: super::review_pr::model_diff(&diff).chars().count(), |
| 684 | file_count: pieces.len(), |
| 685 | files: labels, |
| 686 | }; |
| 687 | PrReviewPass { manifest, diff } |
| 688 | }) |
| 689 | .collect::<Vec<_>>(); |
| 690 | let manifest = PrReviewManifest { |
| 691 | base_sha: view.base_sha.clone(), |
| 692 | head_sha: view.head_sha.clone(), |
| 693 | diff_fingerprint: diff_fingerprint(diff), |
| 694 | diff_chars: super::review_pr::model_diff(diff).chars().count(), |
| 695 | file_count: view.changed_files, |
| 696 | binary_file_patches: diff |
| 697 | .lines() |
| 698 | .filter(|line| *line == "GIT binary patch" || line.starts_with("Binary files ")) |
| 699 | .count(), |
| 700 | binary_contents_semantically_inspected: false, |
| 701 | max_chars_per_pass: max_chars, |
| 702 | passes: passes.iter().map(|pass| pass.manifest.clone()).collect(), |
| 703 | skipped_files: skipped, |
| 704 | }; |
| 705 | Ok(PrReviewPlan { manifest, passes }) |
| 706 | } |
| 707 | |
| 708 | /// Keep bounded Git reads off the Engine/CLI async runtime. Both frontends |
| 709 | /// prepare the same immutable requests before resolving or billing a model. |
| 710 | pub async fn build_pr_review_prompts( |
| 711 | number: u32, |
| 712 | view: &super::review_pr::GhPullRequest, |
| 713 | plan: &PrReviewPlan, |
| 714 | workspace: &Path, |
| 715 | ) -> anyhow::Result<Vec<String>> { |
| 716 | let (view, plan, workspace) = (view.clone(), plan.clone(), workspace.to_path_buf()); |
| 717 | #[cfg(any(test, feature = "test-support"))] |
| 718 | let env_scope = crate::test_support::env_scope_ticket(); |
| 719 | Ok(tokio::task::spawn_blocking(move || { |
| 720 | #[cfg(any(test, feature = "test-support"))] |
| 721 | let _env_scope = crate::test_support::join_env_scope(env_scope); |
| 722 | plan.passes |
| 723 | .iter() |
| 724 | .map(|pass| build_pr_pass_prompt(number, &view, &plan, pass, &workspace)) |
| 725 | .collect() |
| 726 | }) |
| 727 | .await?) |
| 728 | } |
| 729 | |
| 730 | pub fn build_pr_pass_prompt( |
| 731 | number: u32, |
| 732 | view: &super::review_pr::GhPullRequest, |
| 733 | plan: &PrReviewPlan, |
| 734 | pass: &PrReviewPass, |
| 735 | workspace: &Path, |
| 736 | ) -> String { |
| 737 | let diff = super::review_pr::model_diff(&pass.diff); |
| 738 | let context = super::review_pr::source_context( |
| 739 | workspace, |
| 740 | &view.head_sha, |
| 741 | &pass.diff, |
| 742 | plan.manifest |
| 743 | .max_chars_per_pass |
| 744 | .saturating_sub(pass.manifest.diff_chars), |
| 745 | ); |
| 746 | // A degraded plan tells the model it is partial, so a pass summary can |
| 747 | // never honestly claim full coverage; the manifest below carries the |
| 748 | // same skip list for the record. |
| 749 | let scope = if plan.manifest.skipped_files.is_empty() { |
| 750 | "Review only defects introduced in this pass.".to_string() |
| 751 | } else { |
| 752 | format!( |
| 753 | "Review only defects introduced in this pass. This is a partial review (pass {} of {}): the gate did not read {}. Do not claim full coverage.", |
| 754 | pass.manifest.number, |
| 755 | plan.manifest.passes.len(), |
| 756 | format_skipped_files(&plan.manifest.skipped_files) |
| 757 | ) |
| 758 | }; |
| 759 | let task = format!( |
| 760 | "{scope} Use supplementary source to check surrounding guards and declarations. If the prompt omits relevant caller bodies and read-only tools are offered, inspect those callers with the tools. Anchor findings to the commentable diff and scope coverage claims to the pass manifest. Binary changes are represented by metadata. No build or tests have been run." |
| 761 | ); |
| 762 | json!({ |
| 763 | "task": task, |
| 764 | "untrusted_repository_data": true, |
| 765 | "pull_request": { "number": number, "title": view.title, "description": view.body }, |
| 766 | "manifest": plan.manifest, |
| 767 | "pass": pass.manifest, |
| 768 | "diff": diff, |
| 769 | "repository_context": context, |
| 770 | "context_limit": "Context is bounded supplementary excerpts from the exact head. Null means no source context could fit. Missing files or omitted lines are not evidence of a defect." |
| 771 | }).to_string() |
| 772 | } |
| 773 | |
| 774 | /// Exact immutable facts from the same Core source-context collector and budget projection. |
| 775 | pub fn capture_pr_pass_snapshot( |
| 776 | number: u32, |
| 777 | view: &super::review_pr::GhPullRequest, |
| 778 | plan: &PrReviewPlan, |
| 779 | pass: &PrReviewPass, |
| 780 | workspace: &Path, |
| 781 | ) -> Value { |
| 782 | let context = super::review_pr::source_context( |
| 783 | workspace, |
| 784 | &view.head_sha, |
| 785 | &pass.diff, |
| 786 | plan.manifest |
| 787 | .max_chars_per_pass |
| 788 | .saturating_sub(pass.manifest.diff_chars), |
| 789 | ); |
| 790 | json!({"number":number,"view":super::review_host::view_snapshot(view),"manifest":plan.manifest,"pass":pass.manifest,"diff":super::review_pr::model_diff(&pass.diff),"context":context,"sort_keys":super::review_host::sort_json_keys()}) |
| 791 | } |
| 792 | |
| 793 | #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] |
| 794 | pub struct ReviewReceiptPass { |
| 795 | pub number: usize, |
| 796 | pub response_content_sha256: String, |
| 797 | } |
| 798 | |
| 799 | #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] |
| 800 | pub struct ReviewReceiptCoverage { |
| 801 | pub manifest: PrReviewManifest, |
| 802 | pub completed_passes: Vec<ReviewReceiptPass>, |
| 803 | } |
| 804 | |
| 805 | pub struct PrReviewAccumulator { |
| 806 | manifest: PrReviewManifest, |
| 807 | outputs: Vec<ReviewOutput>, |
| 808 | raw_outputs: Vec<String>, |
| 809 | } |
| 810 | |
| 811 | impl PrReviewAccumulator { |
| 812 | pub fn new(plan: &PrReviewPlan) -> Self { |
| 813 | Self { |
| 814 | manifest: plan.manifest.clone(), |
| 815 | outputs: Vec::new(), |
| 816 | raw_outputs: Vec::new(), |
| 817 | } |
| 818 | } |
| 819 | |
| 820 | pub fn accept(&mut self, pass: &PrReviewPass, raw: String) -> anyhow::Result<()> { |
| 821 | let expected = self.outputs.len() + 1; |
| 822 | anyhow::ensure!( |
| 823 | pass.manifest.number == expected |
| 824 | && self.manifest.passes.get(expected - 1) == Some(&pass.manifest), |
| 825 | "Review pass arrived out of order or does not match the immutable manifest; expected pass {expected}" |
| 826 | ); |
| 827 | let output = ReviewOutput::from_structured_str(&raw).ok_or_else(|| { |
| 828 | anyhow::anyhow!( |
| 829 | "Review pass {expected}/{} did not return valid structured JSON; the partial review was not accepted or posted.", |
| 830 | self.manifest.passes.len() |
| 831 | ) |
| 832 | })?; |
| 833 | self.outputs.push(output); |
| 834 | self.raw_outputs.push(raw); |
| 835 | Ok(()) |
| 836 | } |
| 837 | |
| 838 | pub fn finish( |
| 839 | self, |
| 840 | complete_diff: &str, |
| 841 | ) -> anyhow::Result<(ReviewOutput, String, ReviewReceiptCoverage)> { |
| 842 | anyhow::ensure!( |
| 843 | self.outputs.len() == self.manifest.passes.len(), |
| 844 | "Only {}/{} review passes completed; the partial review was not accepted or posted.", |
| 845 | self.outputs.len(), |
| 846 | self.manifest.passes.len() |
| 847 | ); |
| 848 | anyhow::ensure!( |
| 849 | diff_fingerprint(complete_diff) == self.manifest.diff_fingerprint, |
| 850 | "Complete PR diff fingerprint changed before review aggregation" |
| 851 | ); |
| 852 | let mut issues = Vec::new(); |
| 853 | let mut suggestions = Vec::new(); |
| 854 | let mut summaries = Vec::new(); |
| 855 | let mut assessments = Vec::new(); |
| 856 | for (index, output) in self.outputs.into_iter().enumerate() { |
| 857 | if !output.summary.is_empty() { |
| 858 | summaries.push(format!("Pass {}: {}", index + 1, output.summary)); |
| 859 | } |
| 860 | if !output.overall_assessment.is_empty() { |
| 861 | assessments.push(format!("Pass {}: {}", index + 1, output.overall_assessment)); |
| 862 | } |
| 863 | issues.extend(output.issues); |
| 864 | suggestions.extend(output.suggestions); |
| 865 | } |
| 866 | let total = self.manifest.passes.len(); |
| 867 | let per_pass = if summaries.is_empty() { |
| 868 | String::new() |
| 869 | } else { |
| 870 | format!("\n\n{}", summaries.join("\n\n")) |
| 871 | }; |
| 872 | // A degraded plan must never claim complete coverage: the summary |
| 873 | // names every file the gate did not read. |
| 874 | let summary = if self.manifest.skipped_files.is_empty() { |
| 875 | format!( |
| 876 | "Complete review coverage: {total}/{total} passes, {} file patches, {}.{per_pass}", |
| 877 | self.manifest.file_count, self.manifest.diff_fingerprint, |
| 878 | ) |
| 879 | } else { |
| 880 | format!( |
| 881 | "Partial review coverage: {total} pass(es) completed; the gate did not read: {}. Diff: {} file patches, {}.{per_pass}", |
| 882 | format_skipped_files(&self.manifest.skipped_files), |
| 883 | self.manifest.file_count, |
| 884 | self.manifest.diff_fingerprint, |
| 885 | ) |
| 886 | }; |
| 887 | let mut output = ReviewOutput { |
| 888 | summary, |
| 889 | issues, |
| 890 | suggestions, |
| 891 | merge_risk: None, |
| 892 | verified: Vec::new(), |
| 893 | not_reviewed: Vec::new(), |
| 894 | overall_assessment: if assessments.is_empty() { |
| 895 | if self.manifest.skipped_files.is_empty() { |
| 896 | format!("All {total} review passes completed with structured output.") |
| 897 | } else { |
| 898 | format!( |
| 899 | "Partial review: {total} pass(es) completed with structured output; see the summary for files never read." |
| 900 | ) |
| 901 | } |
| 902 | } else { |
| 903 | assessments.join("\n") |
| 904 | }, |
| 905 | ..Default::default() |
| 906 | }; |
| 907 | output.note_binary_coverage(complete_diff); |
| 908 | let completed_passes = self |
| 909 | .raw_outputs |
| 910 | .iter() |
| 911 | .enumerate() |
| 912 | .map(|(index, raw)| ReviewReceiptPass { |
| 913 | number: index + 1, |
| 914 | response_content_sha256: format!("sha256:{}", sha256_hex(raw.as_bytes())), |
| 915 | }) |
| 916 | .collect(); |
| 917 | let content = self |
| 918 | .raw_outputs |
| 919 | .iter() |
| 920 | .enumerate() |
| 921 | .map(|(index, raw)| format!("PASS {}\n{raw}", index + 1)) |
| 922 | .collect::<Vec<_>>() |
| 923 | .join("\n\n"); |
| 924 | Ok(( |
| 925 | output, |
| 926 | content, |
| 927 | ReviewReceiptCoverage { |
| 928 | manifest: self.manifest, |
| 929 | completed_passes, |
| 930 | }, |
| 931 | )) |
| 932 | } |
| 933 | } |
| 934 | |
| 935 | /// Resolve a model-supplied review path to the post-image form diff hunks |
| 936 | /// are keyed by: trimmed, with any `./` prefix removed. `None` means the |
| 937 | /// finding has no position at all. |
| 938 | #[must_use] |
| 939 | pub fn normalize_review_path(path: Option<&str>) -> Option<String> { |
| 940 | let path = path?.trim().trim_start_matches("./"); |
| 941 | if path.is_empty() { |
| 942 | return None; |
| 943 | } |
| 944 | Some(path.to_string()) |
| 945 | } |
| 946 | |
| 947 | /// Where a suggestion can anchor in a diff, and whether its replacement may |
| 948 | /// be emitted as a one-click committable block. |
| 949 | /// |
| 950 | /// This is the single source of truth for "is this committable": the PR |
| 951 | /// inline-comment path and the review receipt both derive from it, so a |
| 952 | /// receipt can never claim a suggestion was committable while the posted |
| 953 | /// comment degraded it to prose (or the reverse). |
| 954 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 955 | pub enum SuggestionAnchor { |
| 956 | /// No path or no line at all: only the summary body can carry it. |
| 957 | NoPosition, |
| 958 | /// Path and line exist but no hunk contains the line — a model-estimated |
| 959 | /// position that missed the diff. |
| 960 | Unanchorable { path: String }, |
| 961 | /// Anchored to RIGHT-side `path:start..=end`. `committable` is true only |
| 962 | /// when the literal replacement passed every safety gate: non-empty, |
| 963 | /// within the span-size budget, an explicitly bounded (or single-line) |
| 964 | /// span, and fully covered by RIGHT-side hunk lines. |
| 965 | Anchored { |
| 966 | path: String, |
| 967 | start: u32, |
| 968 | end: u32, |
| 969 | committable: bool, |
| 970 | }, |
| 971 | } |
| 972 | |
| 973 | /// Resolve one suggestion against a diff's hunks. |
| 974 | #[must_use] |
| 975 | pub fn resolve_suggestion_anchor( |
| 976 | suggestion: &ReviewSuggestion, |
| 977 | hunks: &super::review_hunks::DiffHunks, |
| 978 | ) -> SuggestionAnchor { |
| 979 | let Some(path) = normalize_review_path(suggestion.path.as_deref()) else { |
| 980 | return SuggestionAnchor::NoPosition; |
| 981 | }; |
| 982 | let Some(end) = suggestion.end_line.or(suggestion.line) else { |
| 983 | return SuggestionAnchor::NoPosition; |
| 984 | }; |
| 985 | if !hunks.contains_line(&path, end) { |
| 986 | return SuggestionAnchor::Unanchorable { path }; |
| 987 | } |
| 988 | let start = suggestion.start_line.unwrap_or(end); |
| 989 | // A model that gives neither start_line nor end_line has told us nothing |
| 990 | // about how much code it means to replace. GitHub would happily *insert* |
| 991 | // a multi-line replacement at a single-line anchor, duplicating the lines |
| 992 | // the model meant to replace, so that shape is not committable. |
| 993 | let explicit_span = suggestion.start_line.is_some() || suggestion.end_line.is_some(); |
| 994 | let committable = suggestion |
| 995 | .replacement |
| 996 | .as_deref() |
| 997 | .is_some_and(|replacement| { |
| 998 | !replacement.trim().is_empty() |
| 999 | && start <= end |
| 1000 | && end.saturating_sub(start).saturating_add(1) <= MAX_COMMITTABLE_SUGGESTION_LINES |
| 1001 | && (explicit_span || start < end || !replacement.contains('\n')) |
| 1002 | && hunks.contains_span(&path, start, end) |
| 1003 | }); |
| 1004 | SuggestionAnchor::Anchored { |
| 1005 | path, |
| 1006 | start, |
| 1007 | end, |
| 1008 | committable, |
| 1009 | } |
| 1010 | } |
| 1011 | |
| 1012 | #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] |
| 1013 | pub struct ReviewReceipt { |
| 1014 | pub schema_version: u32, |
| 1015 | pub mode: String, |
| 1016 | pub generated_at: String, |
| 1017 | pub target: String, |
| 1018 | pub diff_fingerprint: String, |
| 1019 | pub diff_bytes: usize, |
| 1020 | pub diff_lines: usize, |
| 1021 | pub provider: String, |
| 1022 | pub model: String, |
| 1023 | pub checks_run: Vec<ReviewReceiptCheck>, |
| 1024 | pub findings: ReviewReceiptFindings, |
| 1025 | pub unresolved_risk: ReviewReceiptRisk, |
| 1026 | pub review_content_sha256: String, |
| 1027 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 1028 | pub coverage: Option<ReviewReceiptCoverage>, |
| 1029 | } |
| 1030 | |
| 1031 | #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] |
| 1032 | pub struct ReviewReceiptCheck { |
| 1033 | pub name: String, |
| 1034 | pub status: String, |
| 1035 | } |
| 1036 | |
| 1037 | #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] |
| 1038 | pub struct ReviewReceiptFindings { |
| 1039 | pub summary: String, |
| 1040 | pub issue_count: usize, |
| 1041 | pub suggestion_count: usize, |
| 1042 | pub highest_severity: String, |
| 1043 | pub issues: Vec<ReviewReceiptIssue>, |
| 1044 | /// What the suggestion pipeline would do with each suggestion against |
| 1045 | /// this diff. `#[serde(default)]` keeps receipts written before the |
| 1046 | /// field existed readable, so the schema version does not move. |
| 1047 | #[serde(default)] |
| 1048 | pub suggestions: ReviewReceiptSuggestions, |
| 1049 | } |
| 1050 | |
| 1051 | /// One suggestion emitted as a one-click committable block: where it |
| 1052 | /// anchored, nothing else. The replacement text is deliberately absent — |
| 1053 | /// a receipt is an audit record, never a second channel for model-written |
| 1054 | /// code. |
| 1055 | #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] |
| 1056 | pub struct ReviewReceiptSuggestion { |
| 1057 | pub path: String, |
| 1058 | pub start_line: u32, |
| 1059 | pub end_line: u32, |
| 1060 | } |
| 1061 | |
| 1062 | /// Receipt provenance for the suggestion pipeline. The three counters use |
| 1063 | /// the same [`SuggestionAnchor`] resolution as the posted inline comments, |
| 1064 | /// so the numbers a receipt records are exactly what the PR path would |
| 1065 | /// emit for the same diff. |
| 1066 | #[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)] |
| 1067 | pub struct ReviewReceiptSuggestions { |
| 1068 | /// Suggestions emitted as committable blocks (one entry each, below). |
| 1069 | pub committable_count: usize, |
| 1070 | /// Anchor spans of the committable suggestions: path + line range, no |
| 1071 | /// replacement text. |
| 1072 | pub committable: Vec<ReviewReceiptSuggestion>, |
| 1073 | /// Suggestions whose anchor was valid but whose replacement failed a |
| 1074 | /// safety gate, so they posted as prose instead. |
| 1075 | pub degraded_to_prose: usize, |
| 1076 | /// Suggestions whose line missed every hunk (or whose file is not in |
| 1077 | /// the diff), so nothing was posted inline. Suggestions with no |
| 1078 | /// position at all are not counted — they never had an anchor to lose. |
| 1079 | pub dropped_unanchorable: usize, |
| 1080 | } |
| 1081 | |
| 1082 | #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] |
| 1083 | pub struct ReviewReceiptIssue { |
| 1084 | pub severity: String, |
| 1085 | pub title: String, |
| 1086 | pub path: Option<String>, |
| 1087 | pub line: Option<u32>, |
| 1088 | } |
| 1089 | |
| 1090 | #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] |
| 1091 | pub struct ReviewReceiptRisk { |
| 1092 | pub unresolved: bool, |
| 1093 | pub level: String, |
| 1094 | pub summary: String, |
| 1095 | } |
| 1096 | |
| 1097 | #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] |
| 1098 | pub struct ReviewReceiptValidation { |
| 1099 | pub passed: bool, |
| 1100 | pub reason: String, |
| 1101 | pub diff_fingerprint: String, |
| 1102 | pub receipt_fingerprint: Option<String>, |
| 1103 | pub receipt_path: Option<PathBuf>, |
| 1104 | pub unresolved_risk: Option<ReviewReceiptRisk>, |
| 1105 | } |
| 1106 | |
| 1107 | /// Classify every suggestion in `output` against `diff` exactly as the PR |
| 1108 | /// inline-comment path would, producing the receipt's provenance counts. |
| 1109 | #[must_use] |
| 1110 | pub fn suggestion_provenance(output: &ReviewOutput, diff: &str) -> ReviewReceiptSuggestions { |
| 1111 | let hunks = super::review_hunks::DiffHunks::parse(diff); |
| 1112 | let mut suggestions = ReviewReceiptSuggestions::default(); |
| 1113 | for suggestion in &output.suggestions { |
| 1114 | match resolve_suggestion_anchor(suggestion, &hunks) { |
| 1115 | SuggestionAnchor::Anchored { |
| 1116 | path, |
| 1117 | start, |
| 1118 | end, |
| 1119 | committable: true, |
| 1120 | } => suggestions.committable.push(ReviewReceiptSuggestion { |
| 1121 | path, |
| 1122 | start_line: start, |
| 1123 | end_line: end, |
| 1124 | }), |
| 1125 | SuggestionAnchor::Anchored { |
| 1126 | committable: false, .. |
| 1127 | } => suggestions.degraded_to_prose += 1, |
| 1128 | SuggestionAnchor::Unanchorable { .. } => suggestions.dropped_unanchorable += 1, |
| 1129 | SuggestionAnchor::NoPosition => {} |
| 1130 | } |
| 1131 | } |
| 1132 | suggestions.committable_count = suggestions.committable.len(); |
| 1133 | suggestions |
| 1134 | } |
| 1135 | |
| 1136 | #[must_use] |
| 1137 | pub fn build_review_receipt( |
| 1138 | target: impl Into<String>, |
| 1139 | diff: &str, |
| 1140 | provider: impl Into<String>, |
| 1141 | model: impl Into<String>, |
| 1142 | output: &ReviewOutput, |
| 1143 | review_content: &str, |
| 1144 | checks_run: Vec<ReviewReceiptCheck>, |
| 1145 | ) -> ReviewReceipt { |
| 1146 | let highest_severity = highest_review_severity(output); |
| 1147 | let unresolved = !output.issues.is_empty(); |
| 1148 | let risk_level = if unresolved { |
| 1149 | highest_severity.clone() |
| 1150 | } else { |
| 1151 | "none".to_string() |
| 1152 | }; |
| 1153 | let risk_summary = if unresolved { |
| 1154 | format!( |
| 1155 | "{} unresolved review issue(s); highest severity: {highest_severity}", |
| 1156 | output.issues.len() |
| 1157 | ) |
| 1158 | } else { |
| 1159 | "No structured unresolved issues reported by review output.".to_string() |
| 1160 | }; |
| 1161 | |
| 1162 | ReviewReceipt { |
| 1163 | schema_version: REVIEW_RECEIPT_SCHEMA_VERSION, |
| 1164 | mode: "pre_push_review".to_string(), |
| 1165 | generated_at: Utc::now().to_rfc3339_opts(SecondsFormat::Secs, true), |
| 1166 | target: target.into(), |
| 1167 | diff_fingerprint: diff_fingerprint(diff), |
| 1168 | diff_bytes: diff.len(), |
| 1169 | diff_lines: diff.lines().count(), |
| 1170 | provider: provider.into(), |
| 1171 | model: model.into(), |
| 1172 | checks_run, |
| 1173 | findings: ReviewReceiptFindings { |
| 1174 | summary: output.summary.clone(), |
| 1175 | issue_count: output.issues.len(), |
| 1176 | suggestion_count: output.suggestions.len(), |
| 1177 | highest_severity: highest_severity.clone(), |
| 1178 | suggestions: suggestion_provenance(output, diff), |
| 1179 | issues: output |
| 1180 | .issues |
| 1181 | .iter() |
| 1182 | .map(|issue| ReviewReceiptIssue { |
| 1183 | severity: issue.severity.clone(), |
| 1184 | title: issue.title.clone(), |
| 1185 | path: issue.path.clone(), |
| 1186 | line: issue.line, |
| 1187 | }) |
| 1188 | .collect(), |
| 1189 | }, |
| 1190 | unresolved_risk: ReviewReceiptRisk { |
| 1191 | unresolved, |
| 1192 | level: risk_level, |
| 1193 | summary: risk_summary, |
| 1194 | }, |
| 1195 | review_content_sha256: sha256_hex(review_content.as_bytes()), |
| 1196 | coverage: None, |
| 1197 | } |
| 1198 | } |
| 1199 | |
| 1200 | pub fn attach_pr_review_coverage( |
| 1201 | receipt: &mut ReviewReceipt, |
| 1202 | coverage: ReviewReceiptCoverage, |
| 1203 | ) -> anyhow::Result<()> { |
| 1204 | anyhow::ensure!( |
| 1205 | receipt.diff_fingerprint == coverage.manifest.diff_fingerprint, |
| 1206 | "Review receipt and PR coverage manifest fingerprints differ" |
| 1207 | ); |
| 1208 | anyhow::ensure!( |
| 1209 | coverage.completed_passes.len() == coverage.manifest.passes.len() |
| 1210 | && coverage |
| 1211 | .completed_passes |
| 1212 | .iter() |
| 1213 | .enumerate() |
| 1214 | .all(|(index, pass)| pass.number == index + 1), |
| 1215 | "Review receipt does not cover every planned PR pass" |
| 1216 | ); |
| 1217 | receipt.schema_version = PR_COVERAGE_RECEIPT_SCHEMA_VERSION; |
| 1218 | receipt.coverage = Some(coverage); |
| 1219 | Ok(()) |
| 1220 | } |
| 1221 | |
| 1222 | pub fn write_review_receipt( |
| 1223 | receipt: &ReviewReceipt, |
| 1224 | path_override: Option<&Path>, |
| 1225 | ) -> anyhow::Result<PathBuf> { |
| 1226 | let path = if let Some(path) = path_override { |
| 1227 | if let Some(parent) = path.parent() { |
| 1228 | fs::create_dir_all(parent)?; |
| 1229 | } |
| 1230 | path.to_path_buf() |
| 1231 | } else { |
| 1232 | let dir = codewhale_config::ensure_state_dir("review-receipts")?; |
| 1233 | let digest = receipt |
| 1234 | .diff_fingerprint |
| 1235 | .strip_prefix("sha256:") |
| 1236 | .unwrap_or(receipt.diff_fingerprint.as_str()); |
| 1237 | let short = digest.chars().take(12).collect::<String>(); |
| 1238 | let stamp = Utc::now().format("%Y%m%dT%H%M%SZ"); |
| 1239 | dir.join(format!("{stamp}-{short}.json")) |
| 1240 | }; |
| 1241 | let encoded = serde_json::to_string_pretty(receipt)?; |
| 1242 | fs::write(&path, encoded)?; |
| 1243 | Ok(path) |
| 1244 | } |
| 1245 | |
| 1246 | const MAX_REVIEW_RECEIPT_BYTES: u64 = 4 * 1024 * 1024; |
| 1247 | |
| 1248 | pub fn read_review_receipt(path: &Path) -> anyhow::Result<ReviewReceipt> { |
| 1249 | use std::io::Read as _; |
| 1250 | let file = fs::File::open(path)?; |
| 1251 | let mut raw = Vec::new(); |
| 1252 | file.take(MAX_REVIEW_RECEIPT_BYTES + 1) |
| 1253 | .read_to_end(&mut raw)?; |
| 1254 | if raw.len() as u64 > MAX_REVIEW_RECEIPT_BYTES { |
| 1255 | anyhow::bail!( |
| 1256 | "review receipt '{}' exceeds the {} byte limit", |
| 1257 | path.display(), |
| 1258 | MAX_REVIEW_RECEIPT_BYTES |
| 1259 | ); |
| 1260 | } |
| 1261 | let text = String::from_utf8(raw)?; |
| 1262 | Ok(serde_json::from_str(&text)?) |
| 1263 | } |
| 1264 | |
| 1265 | pub fn latest_review_receipt_for_diff( |
| 1266 | diff: &str, |
| 1267 | ) -> anyhow::Result<Option<(PathBuf, ReviewReceipt)>> { |
| 1268 | let dir = codewhale_config::resolve_state_dir("review-receipts")?; |
| 1269 | if !dir.is_dir() { |
| 1270 | return Ok(None); |
| 1271 | } |
| 1272 | |
| 1273 | let expected = diff_fingerprint(diff); |
| 1274 | let mut matches = Vec::new(); |
| 1275 | for entry in fs::read_dir(dir)? { |
| 1276 | let Ok(entry) = entry else { |
| 1277 | continue; |
| 1278 | }; |
| 1279 | let path = entry.path(); |
| 1280 | if path.extension().and_then(|ext| ext.to_str()) != Some("json") { |
| 1281 | continue; |
| 1282 | } |
| 1283 | let Ok(receipt) = read_review_receipt(&path) else { |
| 1284 | continue; |
| 1285 | }; |
| 1286 | if receipt.diff_fingerprint != expected { |
| 1287 | continue; |
| 1288 | } |
| 1289 | let modified = entry.metadata().and_then(|meta| meta.modified()).ok(); |
| 1290 | matches.push((modified, path, receipt)); |
| 1291 | } |
| 1292 | matches.sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.cmp(&b.1))); |
| 1293 | Ok(matches.pop().map(|(_, path, receipt)| (path, receipt))) |
| 1294 | } |
| 1295 | |
| 1296 | #[must_use] |
| 1297 | pub fn validate_review_receipt_for_diff( |
| 1298 | diff: &str, |
| 1299 | receipt: &ReviewReceipt, |
| 1300 | receipt_path: Option<PathBuf>, |
| 1301 | ) -> ReviewReceiptValidation { |
| 1302 | let expected = diff_fingerprint(diff); |
| 1303 | let mut validation = ReviewReceiptValidation { |
| 1304 | passed: false, |
| 1305 | reason: String::new(), |
| 1306 | diff_fingerprint: expected.clone(), |
| 1307 | receipt_fingerprint: Some(receipt.diff_fingerprint.clone()), |
| 1308 | receipt_path, |
| 1309 | unresolved_risk: Some(receipt.unresolved_risk.clone()), |
| 1310 | }; |
| 1311 | |
| 1312 | if !matches!( |
| 1313 | (receipt.schema_version, receipt.coverage.is_some()), |
| 1314 | (REVIEW_RECEIPT_SCHEMA_VERSION, false) | (PR_COVERAGE_RECEIPT_SCHEMA_VERSION, true) |
| 1315 | ) { |
| 1316 | validation.reason = format!( |
| 1317 | "unsupported review receipt schema version {}", |
| 1318 | receipt.schema_version |
| 1319 | ); |
| 1320 | return validation; |
| 1321 | } |
| 1322 | if receipt.diff_fingerprint != expected { |
| 1323 | validation.reason = "current diff fingerprint does not match receipt".to_string(); |
| 1324 | return validation; |
| 1325 | } |
| 1326 | if let Some(coverage) = &receipt.coverage { |
| 1327 | if coverage.completed_passes.len() != coverage.manifest.passes.len() |
| 1328 | || coverage |
| 1329 | .completed_passes |
| 1330 | .iter() |
| 1331 | .enumerate() |
| 1332 | .any(|(index, pass)| { |
| 1333 | pass.number != index + 1 |
| 1334 | || !valid_sha256_fingerprint(&pass.response_content_sha256) |
| 1335 | }) |
| 1336 | { |
| 1337 | validation.reason = "review receipt has incomplete or unordered pass coverage".into(); |
| 1338 | return validation; |
| 1339 | } |
| 1340 | let view = super::review_pr::GhPullRequest { |
| 1341 | base_sha: coverage.manifest.base_sha.clone(), |
| 1342 | head_sha: coverage.manifest.head_sha.clone(), |
| 1343 | changed_files: coverage.manifest.file_count, |
| 1344 | ..Default::default() |
| 1345 | }; |
| 1346 | let Ok(plan) = plan_pr_review( |
| 1347 | diff, |
| 1348 | &view, |
| 1349 | coverage.manifest.max_chars_per_pass, |
| 1350 | coverage.manifest.passes.len(), |
| 1351 | ) else { |
| 1352 | validation.reason = "current diff cannot reproduce the receipt pass manifest".into(); |
| 1353 | return validation; |
| 1354 | }; |
| 1355 | if plan.manifest != coverage.manifest { |
| 1356 | validation.reason = "current diff pass manifest does not match receipt".into(); |
| 1357 | return validation; |
| 1358 | } |
| 1359 | // A partial review is real findings, but it must never read as a |
| 1360 | // gate pass: the check fails, naming what the gate did not read. |
| 1361 | if !coverage.manifest.skipped_files.is_empty() { |
| 1362 | validation.reason = format!( |
| 1363 | "review receipt covers a partial review; the gate did not read: {}", |
| 1364 | format_skipped_files(&coverage.manifest.skipped_files) |
| 1365 | ); |
| 1366 | return validation; |
| 1367 | } |
| 1368 | } |
| 1369 | if receipt.unresolved_risk.unresolved { |
| 1370 | validation.reason = receipt.unresolved_risk.summary.clone(); |
| 1371 | return validation; |
| 1372 | } |
| 1373 | if let Some(check) = receipt |
| 1374 | .checks_run |
| 1375 | .iter() |
| 1376 | .find(|check| !review_receipt_check_status_passes(&check.status)) |
| 1377 | { |
| 1378 | validation.reason = format!( |
| 1379 | "review receipt check '{}' did not pass: {}", |
| 1380 | check.name, check.status |
| 1381 | ); |
| 1382 | return validation; |
| 1383 | } |
| 1384 | |
| 1385 | validation.passed = true; |
| 1386 | validation.reason = "receipt matches current diff and has no unresolved risk".to_string(); |
| 1387 | validation |
| 1388 | } |
| 1389 | |
| 1390 | #[must_use] |
| 1391 | pub fn receipt_matches_pr_revision( |
| 1392 | receipt: &ReviewReceipt, |
| 1393 | view: &super::review_pr::GhPullRequest, |
| 1394 | ) -> bool { |
| 1395 | receipt.coverage.as_ref().is_none_or(|coverage| { |
| 1396 | coverage.manifest.base_sha == view.base_sha |
| 1397 | && coverage.manifest.head_sha == view.head_sha |
| 1398 | && coverage.manifest.file_count == view.changed_files |
| 1399 | }) |
| 1400 | } |
| 1401 | |
| 1402 | #[must_use] |
| 1403 | pub fn diff_fingerprint(diff: &str) -> String { |
| 1404 | format!("sha256:{}", sha256_hex(diff.as_bytes())) |
| 1405 | } |
| 1406 | |
| 1407 | fn parse_review_output_json(raw: &str) -> Option<ReviewOutput> { |
| 1408 | if let Ok(parsed) = serde_json::from_str::<ReviewOutput>(raw) { |
| 1409 | return Some(parsed); |
| 1410 | } |
| 1411 | |
| 1412 | let Value::String(inner) = serde_json::from_str::<Value>(raw).ok()? else { |
| 1413 | return None; |
| 1414 | }; |
| 1415 | if inner.trim().is_empty() || inner == raw { |
| 1416 | return None; |
| 1417 | } |
| 1418 | parse_review_output_json(&inner) |
| 1419 | } |
| 1420 | |
| 1421 | fn highest_review_severity(output: &ReviewOutput) -> String { |
| 1422 | let mut highest = "none"; |
| 1423 | for issue in &output.issues { |
| 1424 | let severity = issue.severity.as_str(); |
| 1425 | if severity_rank(severity) > severity_rank(highest) { |
| 1426 | highest = severity; |
| 1427 | } |
| 1428 | } |
| 1429 | highest.to_string() |
| 1430 | } |
| 1431 | |
| 1432 | fn severity_rank(severity: &str) -> u8 { |
| 1433 | super::review_core::review_severity_rank(severity) |
| 1434 | } |
| 1435 | |
| 1436 | fn review_receipt_check_status_passes(status: &str) -> bool { |
| 1437 | matches!( |
| 1438 | status.trim().to_ascii_lowercase().as_str(), |
| 1439 | "passed" | "pass" | "success" | "ok" |
| 1440 | ) |
| 1441 | } |
| 1442 | |
| 1443 | fn sha256_hex(bytes: &[u8]) -> String { |
| 1444 | codewhale_runtime::hashing::sha256_hex(bytes) |
| 1445 | } |
| 1446 | |
| 1447 | fn valid_sha256_fingerprint(value: &str) -> bool { |
| 1448 | value.strip_prefix("sha256:").is_some_and(|digest| { |
| 1449 | digest.len() == 64 && digest.bytes().all(|byte| byte.is_ascii_hexdigit()) |
| 1450 | }) |
| 1451 | } |
| 1452 | |
| 1453 | pub struct ReviewTool { |
| 1454 | client: Option<CodewhaleClient>, |
| 1455 | model: String, |
| 1456 | } |
| 1457 | |
| 1458 | impl ReviewTool { |
| 1459 | #[must_use] |
| 1460 | pub fn new(client: Option<CodewhaleClient>, model: String) -> Self { |
| 1461 | Self { client, model } |
| 1462 | } |
| 1463 | } |
| 1464 | |
| 1465 | #[async_trait] |
| 1466 | impl ToolSpec for ReviewTool { |
| 1467 | fn name(&self) -> &'static str { |
| 1468 | "review" |
| 1469 | } |
| 1470 | |
| 1471 | fn description(&self) -> &'static str { |
| 1472 | "Run a structured code review for a file, git diff, or GitHub pull request." |
| 1473 | } |
| 1474 | |
| 1475 | fn input_schema(&self) -> Value { |
| 1476 | json!({ |
| 1477 | "type": "object", |
| 1478 | "properties": { |
| 1479 | "target": { |
| 1480 | "type": "string", |
| 1481 | "description": "File path, PR URL, or the literal 'diff'/'staged' for git diff review." |
| 1482 | }, |
| 1483 | "kind": { |
| 1484 | "type": "string", |
| 1485 | "description": "Optional explicit target type: file, diff, or pr." |
| 1486 | }, |
| 1487 | "base": { |
| 1488 | "type": "string", |
| 1489 | "description": "Optional git base ref when using diff target (e.g. origin/main)." |
| 1490 | }, |
| 1491 | "staged": { |
| 1492 | "type": "boolean", |
| 1493 | "description": "Review staged changes when using diff target (default: false)." |
| 1494 | }, |
| 1495 | "max_chars": { |
| 1496 | "type": "integer", |
| 1497 | "description": "Maximum source characters per pass (default: 200000). Input is never truncated." |
| 1498 | }, |
| 1499 | "max_passes": { |
| 1500 | "type": "integer", |
| 1501 | "minimum": 1, |
| 1502 | "maximum": MAX_REVIEW_PASSES, |
| 1503 | "description": "Maximum complete PR review passes (default: 1, maximum: 64). Values above 1 explicitly authorize additional model requests for an oversized PR." |
| 1504 | } |
| 1505 | }, |
| 1506 | "required": ["target"] |
| 1507 | }) |
| 1508 | } |
| 1509 | |
| 1510 | fn capabilities(&self) -> Vec<ToolCapability> { |
| 1511 | vec![ |
| 1512 | ToolCapability::ReadOnly, |
| 1513 | ToolCapability::Network, |
| 1514 | ToolCapability::StartsWorkspaceProgram, |
| 1515 | ] |
| 1516 | } |
| 1517 | |
| 1518 | fn approval_requirement(&self) -> ApprovalRequirement { |
| 1519 | ApprovalRequirement::Auto |
| 1520 | } |
| 1521 | |
| 1522 | fn approval_requirement_for(&self, input: &Value) -> ApprovalRequirement { |
| 1523 | match optional_u64(input, "max_passes", 1) { |
| 1524 | Ok(1) => ApprovalRequirement::Auto, |
| 1525 | _ => ApprovalRequirement::Required, |
| 1526 | } |
| 1527 | } |
| 1528 | |
| 1529 | async fn execute(&self, input: Value, context: &ToolContext) -> Result<ToolResult, ToolError> { |
| 1530 | let Some(client) = self.client.clone() else { |
| 1531 | return Err(ToolError::not_available(REVIEW_CLIENT_UNAVAILABLE)); |
| 1532 | }; |
| 1533 | |
| 1534 | let target = required_str(&input, "target")?.trim(); |
| 1535 | if target.is_empty() { |
| 1536 | return Err(ToolError::invalid_input("target cannot be empty")); |
| 1537 | } |
| 1538 | |
| 1539 | let kind = optional_str(&input, "kind")?.map(|s| s.trim().to_ascii_lowercase()); |
| 1540 | let base = optional_str(&input, "base")?.map(|s| s.trim().to_string()); |
| 1541 | let staged = optional_bool(&input, "staged", false)?; |
| 1542 | let max_chars = |
| 1543 | usize::try_from(optional_u64(&input, "max_chars", DEFAULT_MAX_CHARS as u64)?) |
| 1544 | .unwrap_or(DEFAULT_MAX_CHARS) |
| 1545 | .clamp(1, MAX_MAX_CHARS); |
| 1546 | let max_passes = |
| 1547 | usize::try_from(optional_u64(&input, "max_passes", 1)?).unwrap_or(usize::MAX); |
| 1548 | if !(1..=MAX_REVIEW_PASSES).contains(&max_passes) { |
| 1549 | return Err(ToolError::invalid_input(format!( |
| 1550 | "max_passes must be from 1 to {MAX_REVIEW_PASSES}" |
| 1551 | ))); |
| 1552 | } |
| 1553 | |
| 1554 | let source = resolve_review_source( |
| 1555 | target, |
| 1556 | kind.as_deref(), |
| 1557 | staged, |
| 1558 | base.as_deref(), |
| 1559 | max_chars, |
| 1560 | context, |
| 1561 | ) |
| 1562 | .await?; |
| 1563 | if !matches!(&source, ReviewSource::PullRequest { .. }) && max_passes != 1 { |
| 1564 | return Err(ToolError::invalid_input( |
| 1565 | "max_passes applies only to pull request reviews", |
| 1566 | )); |
| 1567 | } |
| 1568 | let plan = match &source { |
| 1569 | ReviewSource::PullRequest { diff, view, .. } => Some( |
| 1570 | plan_pr_review(diff, view, max_chars, max_passes) |
| 1571 | .map_err(|error| ToolError::invalid_input(error.to_string()))?, |
| 1572 | ), |
| 1573 | _ => None, |
| 1574 | }; |
| 1575 | let prompts = if let Some(plan) = &plan { |
| 1576 | let ReviewSource::PullRequest { pr, view, .. } = &source else { |
| 1577 | unreachable!("PR plan has PR source") |
| 1578 | }; |
| 1579 | let number = pr |
| 1580 | .number |
| 1581 | .parse::<u32>() |
| 1582 | .map_err(|_| ToolError::invalid_input("Invalid pull request number"))?; |
| 1583 | super::review_host::pr_prompts(number, view, plan, context).await? |
| 1584 | } else { |
| 1585 | validate_review_source_size(&source, max_chars)?; |
| 1586 | vec![if context |
| 1587 | .features |
| 1588 | .enabled(codewhale_runtime::features::Feature::ReviewHost) |
| 1589 | { |
| 1590 | super::review_host::source_prompt(review_source_snapshot(&source), context).await? |
| 1591 | } else { |
| 1592 | build_review_prompt(&source) |
| 1593 | }] |
| 1594 | }; |
| 1595 | |
| 1596 | let route = client.effective_route_envelope(&self.model, chrono::Utc::now()); |
| 1597 | let review_diff = match &source { |
| 1598 | ReviewSource::PullRequest { diff, .. } => diff.clone(), |
| 1599 | ReviewSource::Diff { diff, .. } => diff.clone(), |
| 1600 | ReviewSource::File { .. } => String::new(), |
| 1601 | }; |
| 1602 | let required_head = match &source { |
| 1603 | ReviewSource::PullRequest { view, .. } => Some(view.head_sha.clone()), |
| 1604 | _ => None, |
| 1605 | }; |
| 1606 | let workspace = context.workspace.clone(); |
| 1607 | let tool_workspace = tokio::task::spawn_blocking(move || { |
| 1608 | super::review_core::repository_tool_workspace(&workspace, required_head.as_deref()) |
| 1609 | }) |
| 1610 | .await |
| 1611 | .map_err(|e| ToolError::execution_failed(format!("review workspace check failed: {e}")))?; |
| 1612 | let triage = super::review_triage::triage_review(&review_diff); |
| 1613 | let reserve_percent = |
| 1614 | crate::route_budget::review_visible_text_reserve_percent(&route.model); |
| 1615 | let budget = super::review_triage::budget_for( |
| 1616 | &triage, |
| 1617 | client.effective_max_output_tokens(&route.model), |
| 1618 | ); |
| 1619 | let allowance = budget.max_output_tokens; |
| 1620 | let reasoning_effort = |
| 1621 | (codewhale_models::model_reasoning_capability(&route.model) == Some(true)).then(|| { |
| 1622 | bounded_review_reasoning_effort( |
| 1623 | crate::reasoning_preference::ReasoningEffort::Max, |
| 1624 | reserve_percent, |
| 1625 | allowance, |
| 1626 | ) |
| 1627 | .normalize_for_route_identity( |
| 1628 | client.api_provider(), |
| 1629 | client.admitted_provider_identity().key.as_str(), |
| 1630 | client.base_url(), |
| 1631 | &route.model, |
| 1632 | ) |
| 1633 | .as_setting() |
| 1634 | .to_string() |
| 1635 | }); |
| 1636 | let mut usage = Usage::default(); |
| 1637 | let mut source_records = Vec::new(); |
| 1638 | let mut projection_notices = std::collections::BTreeSet::new(); |
| 1639 | let mut accumulator = plan.as_ref().map(PrReviewAccumulator::new); |
| 1640 | let mut single_output = None; |
| 1641 | let mut anchors = super::review_core::ReviewAnchorReport::default(); |
| 1642 | let mut tools_used: Vec<String> = Vec::new(); |
| 1643 | let mut steps = 0; |
| 1644 | let mut tool_calls = 0; |
| 1645 | let mut changed_lines = 0; |
| 1646 | let mut outcome = super::review_core::ReviewCoreOutcome::Completed; |
| 1647 | let mut stop = None; |
| 1648 | let mut spend_usd = None; |
| 1649 | for (index, prompt) in prompts.into_iter().enumerate() { |
| 1650 | let mut request = super::review_core::ReviewCoreRequest::new(&review_diff, prompt); |
| 1651 | request.accounting_origin = context.accounting_origin.clone(); |
| 1652 | request.workspace = tool_workspace.clone(); |
| 1653 | request.budget = budget.tool_budget(); |
| 1654 | request.max_output_tokens = Some(allowance); |
| 1655 | request.reasoning_effort = reasoning_effort.clone(); |
| 1656 | let result = |
| 1657 | match super::review_core::run_review_core(&client, &self.model, request).await { |
| 1658 | Ok(result) => result, |
| 1659 | Err(error) => { |
| 1660 | return Ok(review_error_with_usage( |
| 1661 | &route, |
| 1662 | &usage, |
| 1663 | &source_records, |
| 1664 | format!( |
| 1665 | "{}; no partial review was accepted.", |
| 1666 | request_failure_message( |
| 1667 | index + 1, |
| 1668 | plan.as_ref().map_or(1, |plan| plan.passes.len()), |
| 1669 | &error |
| 1670 | ) |
| 1671 | ), |
| 1672 | )); |
| 1673 | } |
| 1674 | }; |
| 1675 | projection_notices.extend( |
| 1676 | result |
| 1677 | .tool_projection_warnings |
| 1678 | .iter() |
| 1679 | .map(crate::core::events::render_tool_projection_warning), |
| 1680 | ); |
| 1681 | source_records.extend(result.source_records.iter().cloned()); |
| 1682 | add_review_usage(&mut usage, &result.usage); |
| 1683 | for tool in &result.tools_used { |
| 1684 | if !tools_used.iter().any(|seen| seen == tool) { |
| 1685 | tools_used.push(tool.clone()); |
| 1686 | } |
| 1687 | } |
| 1688 | anchors.claims += result.anchors.claims; |
| 1689 | anchors.anchored += result.anchors.anchored; |
| 1690 | anchors.unanchored += result.anchors.unanchored; |
| 1691 | steps += result.steps; |
| 1692 | tool_calls += result.tool_calls; |
| 1693 | changed_lines += result.coverage.changed_lines; |
| 1694 | outcome = result.outcome; |
| 1695 | stop = result.stop.clone().or(stop); |
| 1696 | spend_usd = result.spend_usd.or(spend_usd); |
| 1697 | if codewhale_models::is_incomplete_stop_reason(result.stop_reason.as_deref()) { |
| 1698 | return Ok(review_error_with_usage( |
| 1699 | &route, |
| 1700 | &usage, |
| 1701 | &source_records, |
| 1702 | format!( |
| 1703 | "Review pass {}/{} response incomplete: provider stop reason `{}`; the pass {}. The partial review was not accepted.", |
| 1704 | index + 1, |
| 1705 | plan.as_ref().map_or(1, |plan| plan.passes.len()), |
| 1706 | codewhale_models::stop_reason_detail(result.stop_reason.as_deref()), |
| 1707 | exhausted_pass_clause(&result.usage) |
| 1708 | ), |
| 1709 | )); |
| 1710 | } |
| 1711 | if result.outcome == super::review_core::ReviewCoreOutcome::LeakedToolCall { |
| 1712 | return Ok(review_error_with_usage( |
| 1713 | &route, |
| 1714 | &usage, |
| 1715 | &source_records, |
| 1716 | leaked_tool_call_message( |
| 1717 | index + 1, |
| 1718 | plan.as_ref().map_or(1, |plan| plan.passes.len()), |
| 1719 | ), |
| 1720 | )); |
| 1721 | } |
| 1722 | if let (Some(plan), Some(accumulator)) = (&plan, accumulator.as_mut()) { |
| 1723 | if let Err(error) = accumulator.accept(&plan.passes[index], result.raw) { |
| 1724 | return Ok(review_error_with_usage( |
| 1725 | &route, |
| 1726 | &usage, |
| 1727 | &source_records, |
| 1728 | error.to_string(), |
| 1729 | )); |
| 1730 | } |
| 1731 | } else { |
| 1732 | match accept_single_review(&result.raw) { |
| 1733 | Ok(_) => single_output = Some(result.output), |
| 1734 | Err(error) => { |
| 1735 | return Ok(review_error_with_usage( |
| 1736 | &route, |
| 1737 | &usage, |
| 1738 | &source_records, |
| 1739 | error, |
| 1740 | )); |
| 1741 | } |
| 1742 | } |
| 1743 | } |
| 1744 | } |
| 1745 | if let Err(error) = ensure_pr_source_current(&source, &context.workspace).await { |
| 1746 | return Ok(review_error_with_usage( |
| 1747 | &route, |
| 1748 | &usage, |
| 1749 | &source_records, |
| 1750 | error.to_string(), |
| 1751 | )); |
| 1752 | } |
| 1753 | let mut coverage = None; |
| 1754 | let output = if let (Some(accumulator), ReviewSource::PullRequest { diff, .. }) = |
| 1755 | (accumulator, &source) |
| 1756 | { |
| 1757 | let (output, _, completed) = match accumulator.finish(diff) { |
| 1758 | Ok(completed) => completed, |
| 1759 | Err(error) => { |
| 1760 | return Ok(review_error_with_usage( |
| 1761 | &route, |
| 1762 | &usage, |
| 1763 | &source_records, |
| 1764 | error.to_string(), |
| 1765 | )); |
| 1766 | } |
| 1767 | }; |
| 1768 | coverage = Some(completed); |
| 1769 | output |
| 1770 | } else { |
| 1771 | single_output.expect("one non-PR review response") |
| 1772 | }; |
| 1773 | let mut output = output; |
| 1774 | output.not_reviewed.extend(projection_notices); |
| 1775 | if let Some(note) = stop |
| 1776 | .as_ref() |
| 1777 | .map(|stop| super::review_triage::partial_review_note(stop, &triage, &budget)) |
| 1778 | { |
| 1779 | if !output.summary.is_empty() { |
| 1780 | output.summary.push_str("\n\n"); |
| 1781 | } |
| 1782 | output.summary.push_str(¬e); |
| 1783 | } |
| 1784 | let mut metadata = review_usage_metadata(&route, &usage, &source_records); |
| 1785 | metadata["review_anchors"] = json!(anchors); |
| 1786 | metadata["review_tools_used"] = json!(tools_used); |
| 1787 | metadata["review_repository_reads"] = json!(tool_workspace.is_some()); |
| 1788 | metadata["review_steps"] = json!(steps); |
| 1789 | metadata["review_tool_calls"] = json!(tool_calls); |
| 1790 | metadata["review_changed_lines"] = json!(changed_lines); |
| 1791 | metadata["review_triage"] = json!(triage); |
| 1792 | metadata["review_budget"] = json!(budget); |
| 1793 | metadata["review_stop"] = |
| 1794 | json!(stop.as_ref().map(super::review_triage::ReviewStop::as_str)); |
| 1795 | metadata["review_spend_usd"] = json!(spend_usd); |
| 1796 | metadata["review_outcome"] = json!(match outcome { |
| 1797 | super::review_core::ReviewCoreOutcome::Completed => "completed", |
| 1798 | super::review_core::ReviewCoreOutcome::NoFinalAnswer => "no_final_answer", |
| 1799 | super::review_core::ReviewCoreOutcome::StepBudgetExhausted => "step_budget_exhausted", |
| 1800 | super::review_core::ReviewCoreOutcome::LeakedToolCall => "leaked_tool_call", |
| 1801 | }); |
| 1802 | if let Some(plan) = &plan { |
| 1803 | metadata["review_passes"] = json!(plan.passes.len()); |
| 1804 | metadata["diff_fingerprint"] = json!(plan.manifest.diff_fingerprint.as_str()); |
| 1805 | metadata["review_coverage"] = match serde_json::to_value(coverage) { |
| 1806 | Ok(coverage) => coverage, |
| 1807 | Err(error) => { |
| 1808 | return Ok(review_error_with_usage( |
| 1809 | &route, |
| 1810 | &usage, |
| 1811 | &source_records, |
| 1812 | error.to_string(), |
| 1813 | )); |
| 1814 | } |
| 1815 | }; |
| 1816 | } |
| 1817 | let result = match ToolResult::json(&output) { |
| 1818 | Ok(result) => result, |
| 1819 | Err(error) => { |
| 1820 | return Ok(review_error_with_usage( |
| 1821 | &route, |
| 1822 | &usage, |
| 1823 | &source_records, |
| 1824 | error.to_string(), |
| 1825 | )); |
| 1826 | } |
| 1827 | }; |
| 1828 | Ok(result.with_metadata(metadata)) |
| 1829 | } |
| 1830 | } |
| 1831 | |
| 1832 | pub fn leaked_tool_call_message(pass: usize, passes: usize) -> String { |
| 1833 | format!( |
| 1834 | "Review pass {pass}/{passes} returned tool-call markup instead of a review: the model tried to call tools this pass did not offer. This is not a review result, and the response was not accepted or posted." |
| 1835 | ) |
| 1836 | } |
| 1837 | |
| 1838 | pub fn exhausted_pass_clause(usage: &Usage) -> String { |
| 1839 | let visible_tokens = usage |
| 1840 | .output_tokens |
| 1841 | .saturating_sub(usage.reasoning_tokens.unwrap_or(0)); |
| 1842 | if visible_tokens > 0 { |
| 1843 | format!( |
| 1844 | "was cut off before the review finished ({visible_tokens} visible tokens came back)" |
| 1845 | ) |
| 1846 | } else { |
| 1847 | "produced no review text".to_string() |
| 1848 | } |
| 1849 | } |
| 1850 | |
| 1851 | /// Accept one non-PR review reply (#6561 D03-m4). Prose that ignores the |
| 1852 | /// JSON contract is still a review (see [`ReviewOutput::parse`]), but an |
| 1853 | /// empty reply, or JSON that carries no summary, issue, suggestion or |
| 1854 | /// assessment (`{}`, an unrelated object), used to become an empty |
| 1855 | /// successful review that read as clean. |
| 1856 | fn accept_single_review(response_text: &str) -> Result<ReviewOutput, String> { |
| 1857 | let output = ReviewOutput::parse(response_text); |
| 1858 | if response_text.trim().is_empty() |
| 1859 | || (output.summary.is_empty() |
| 1860 | && output.issues.is_empty() |
| 1861 | && output.suggestions.is_empty() |
| 1862 | && output.overall_assessment.is_empty()) |
| 1863 | { |
| 1864 | return Err( |
| 1865 | "Review response carried no review content (empty, or JSON without summary, \ |
| 1866 | issues, suggestions or overall_assessment); no review was accepted." |
| 1867 | .to_string(), |
| 1868 | ); |
| 1869 | } |
| 1870 | Ok(output) |
| 1871 | } |
| 1872 | |
| 1873 | fn review_error_with_usage( |
| 1874 | route: &crate::cost_status::EffectiveRouteEnvelope, |
| 1875 | usage: &Usage, |
| 1876 | records: &[crate::cost_status::RuntimeUsageRecord], |
| 1877 | message: impl Into<String>, |
| 1878 | ) -> ToolResult { |
| 1879 | ToolResult::error(message.into()).with_metadata(review_usage_metadata(route, usage, records)) |
| 1880 | } |
| 1881 | |
| 1882 | fn review_usage_metadata( |
| 1883 | route: &crate::cost_status::EffectiveRouteEnvelope, |
| 1884 | usage: &Usage, |
| 1885 | records: &[crate::cost_status::RuntimeUsageRecord], |
| 1886 | ) -> Value { |
| 1887 | let mut metadata = json!({ |
| 1888 | "tool": "review", |
| 1889 | "input_tokens": usage.input_tokens, |
| 1890 | "output_tokens": usage.output_tokens, |
| 1891 | }); |
| 1892 | // Every billable class, from the one shared producer, so a child turn can be |
| 1893 | // priced with the same completeness as a parent turn (#4318). |
| 1894 | crate::cost_status::attach_child_usage_metadata(&mut metadata, route, usage); |
| 1895 | crate::cost_status::attach_child_usage_batch_metadata( |
| 1896 | &mut metadata, |
| 1897 | &crate::cost_status::RuntimeUsageBatch { |
| 1898 | records: records.to_vec(), |
| 1899 | ..Default::default() |
| 1900 | }, |
| 1901 | ); |
| 1902 | metadata |
| 1903 | } |
| 1904 | |
| 1905 | /// Describe a failed review request with its whole error chain. |
| 1906 | /// |
| 1907 | /// The client wraps the retry loop's `LlmError` in one outer context (the |
| 1908 | /// bare "Responses API request failed" / "Chat API request failed"), and |
| 1909 | /// `{error}` prints only that layer. The alternate format walks the chain, |
| 1910 | /// so the class the `LlmError` names (quota, auth, rate limit, upstream 5xx, |
| 1911 | /// network, timeout) and its sanitized provider body reach the log and the |
| 1912 | /// review workflow's non-run classifier. Both the agent-callable `ReviewTool` |
| 1913 | /// and the `codewhale review` CLI path go through here. |
| 1914 | pub fn request_failure_message(pass: usize, planned: usize, error: &anyhow::Error) -> String { |
| 1915 | format!("Review pass {pass}/{planned} request failed: {error:#}") |
| 1916 | } |
| 1917 | |
| 1918 | pub fn add_review_usage(total: &mut Usage, next: &Usage) { |
| 1919 | crate::core::turn::add_usage_to(total, next); |
| 1920 | } |
| 1921 | |
| 1922 | enum ReviewSource { |
| 1923 | File { |
| 1924 | display: String, |
| 1925 | content: String, |
| 1926 | }, |
| 1927 | Diff { |
| 1928 | label: String, |
| 1929 | diff: String, |
| 1930 | }, |
| 1931 | PullRequest { |
| 1932 | label: String, |
| 1933 | diff: String, |
| 1934 | pr: PullRequestRef, |
| 1935 | view: Box<super::review_pr::GhPullRequest>, |
| 1936 | }, |
| 1937 | } |
| 1938 | |
| 1939 | async fn resolve_review_source( |
| 1940 | target: &str, |
| 1941 | kind: Option<&str>, |
| 1942 | staged: bool, |
| 1943 | base: Option<&str>, |
| 1944 | max_chars: usize, |
| 1945 | context: &ToolContext, |
| 1946 | ) -> Result<ReviewSource, ToolError> { |
| 1947 | if let Some(kind) = kind { |
| 1948 | return match kind { |
| 1949 | "file" => resolve_file_target_async(target, max_chars, context).await, |
| 1950 | "diff" => { |
| 1951 | let diff = resolve_diff_target(context.workspace.as_path(), staged, base).await?; |
| 1952 | Ok(ReviewSource::Diff { |
| 1953 | label: "git diff".to_string(), |
| 1954 | diff, |
| 1955 | }) |
| 1956 | } |
| 1957 | "pr" | "pull" | "pull_request" => { |
| 1958 | let pr = parse_pr_url(target) |
| 1959 | .ok_or_else(|| ToolError::invalid_input("Invalid pull request URL"))?; |
| 1960 | gh_pr_source(pr, &context.workspace).await |
| 1961 | } |
| 1962 | other => Err(ToolError::invalid_input(format!( |
| 1963 | "Unknown review kind '{other}'" |
| 1964 | ))), |
| 1965 | }; |
| 1966 | } |
| 1967 | |
| 1968 | if let Some(pr) = parse_pr_url(target) { |
| 1969 | return gh_pr_source(pr, &context.workspace).await; |
| 1970 | } |
| 1971 | |
| 1972 | if let Some(staged_override) = diff_mode_from_target(target) { |
| 1973 | let staged = staged || staged_override; |
| 1974 | let diff = resolve_diff_target(context.workspace.as_path(), staged, base).await?; |
| 1975 | return Ok(ReviewSource::Diff { |
| 1976 | label: if staged { |
| 1977 | "git diff --cached" |
| 1978 | } else { |
| 1979 | "git diff" |
| 1980 | } |
| 1981 | .to_string(), |
| 1982 | diff, |
| 1983 | }); |
| 1984 | } |
| 1985 | |
| 1986 | resolve_file_target_async(target, max_chars, context).await |
| 1987 | } |
| 1988 | |
| 1989 | async fn resolve_file_target_async( |
| 1990 | target: &str, |
| 1991 | max_chars: usize, |
| 1992 | context: &ToolContext, |
| 1993 | ) -> Result<ReviewSource, ToolError> { |
| 1994 | let target = target.to_string(); |
| 1995 | let context = context.clone(); |
| 1996 | tokio::task::spawn_blocking(move || resolve_file_target(&target, max_chars, &context)) |
| 1997 | .await |
| 1998 | .map_err(|e| ToolError::execution_failed(format!("review file reader failed: {e}")))? |
| 1999 | } |
| 2000 | |
| 2001 | fn resolve_file_target( |
| 2002 | target: &str, |
| 2003 | max_chars: usize, |
| 2004 | context: &ToolContext, |
| 2005 | ) -> Result<ReviewSource, ToolError> { |
| 2006 | use std::io::Read as _; |
| 2007 | |
| 2008 | let plan = crate::tools::file::resolve_read_open_plan_sync(context, target, "review", false)?; |
| 2009 | let path = plan.file_path.clone(); |
| 2010 | let (file, fd_path) = |
| 2011 | match crate::tools::file::open_verified_read_handle(&plan, true, true, false) { |
| 2012 | Ok(Some(opened)) => opened, |
| 2013 | Ok(None) => { |
| 2014 | return Err(ToolError::invalid_input(format!( |
| 2015 | "Target is not a file: {}", |
| 2016 | path.display() |
| 2017 | ))); |
| 2018 | } |
| 2019 | Err(ToolError::ExecutionFailed { message, .. }) |
| 2020 | if message.contains("path is a directory") => |
| 2021 | { |
| 2022 | return Err(ToolError::invalid_input(format!( |
| 2023 | "Target is not a file: {}", |
| 2024 | path.display() |
| 2025 | ))); |
| 2026 | } |
| 2027 | Err(error) => return Err(error), |
| 2028 | }; |
| 2029 | let metadata = file.metadata().map_err(|e| { |
| 2030 | ToolError::execution_failed(format!("Failed to read file {}: {e}", path.display())) |
| 2031 | })?; |
| 2032 | if !metadata.is_file() { |
| 2033 | return Err(ToolError::invalid_input(format!( |
| 2034 | "Target is not a file: {}", |
| 2035 | path.display() |
| 2036 | ))); |
| 2037 | } |
| 2038 | let max_bytes = (max_chars as u64).saturating_mul(4); |
| 2039 | let len = metadata.len(); |
| 2040 | if len > max_bytes { |
| 2041 | return Err(ToolError::invalid_input(format!( |
| 2042 | "File {} is {len} bytes, exceeding max_chars={max_chars}; no source was truncated and no review was run", |
| 2043 | path.display() |
| 2044 | ))); |
| 2045 | } |
| 2046 | let mut bytes = Vec::new(); |
| 2047 | file.take(max_bytes.saturating_add(1)) |
| 2048 | .read_to_end(&mut bytes) |
| 2049 | .map_err(|e| { |
| 2050 | ToolError::execution_failed(format!("Failed to read file {}: {e}", path.display())) |
| 2051 | })?; |
| 2052 | if bytes.len() as u64 > max_bytes { |
| 2053 | return Err(ToolError::invalid_input(format!( |
| 2054 | "File {} exceeds max_chars={max_chars}; no source was truncated and no review was run", |
| 2055 | path.display() |
| 2056 | ))); |
| 2057 | } |
| 2058 | let content = String::from_utf8(bytes).map_err(|e| { |
| 2059 | ToolError::execution_failed(format!("Failed to read file {}: {e}", path.display())) |
| 2060 | })?; |
| 2061 | let workspace_canonical = |
| 2062 | fs::canonicalize(&context.workspace).unwrap_or_else(|_| context.workspace.clone()); |
| 2063 | let display = fd_path |
| 2064 | .strip_prefix(&workspace_canonical) |
| 2065 | .or_else(|_| path.strip_prefix(&context.workspace)) |
| 2066 | .unwrap_or(&path) |
| 2067 | .to_string_lossy() |
| 2068 | .to_string(); |
| 2069 | Ok(ReviewSource::File { display, content }) |
| 2070 | } |
| 2071 | |
| 2072 | async fn resolve_diff_target( |
| 2073 | workspace: &Path, |
| 2074 | staged: bool, |
| 2075 | base: Option<&str>, |
| 2076 | ) -> Result<String, ToolError> { |
| 2077 | let base = base.map(str::trim).filter(|base| !base.is_empty()); |
| 2078 | let base_commit = if let Some(base) = base { |
| 2079 | Some(super::git::resolve_commit_ref(workspace, base).await?) |
| 2080 | } else { |
| 2081 | None |
| 2082 | }; |
| 2083 | |
| 2084 | let mut args = vec!["diff".to_string()]; |
| 2085 | args.extend(codewhale_dependencies::Git::REVIEW_DIFF_ARGS.map(String::from)); |
| 2086 | if staged { |
| 2087 | args.push("--cached".to_string()); |
| 2088 | if let Some(base_commit) = base_commit { |
| 2089 | // `git diff --cached <base>...HEAD` is invalid because the index |
| 2090 | // is already one side of this diff. Preserve triple-dot semantics |
| 2091 | // by resolving the merge base first, then compare that tree with |
| 2092 | // the index (committed branch work plus the staged snapshot). |
| 2093 | let output = run_review_git( |
| 2094 | workspace, |
| 2095 | vec!["merge-base".to_string(), base_commit, "HEAD".to_string()], |
| 2096 | "resolve staged review merge base", |
| 2097 | ) |
| 2098 | .await?; |
| 2099 | if !output.status.success() { |
| 2100 | let stderr = String::from_utf8_lossy(&output.stderr); |
| 2101 | return Err(ToolError::execution_failed(format!( |
| 2102 | "git merge-base failed: {}", |
| 2103 | stderr.trim() |
| 2104 | ))); |
| 2105 | } |
| 2106 | let merge_base = String::from_utf8_lossy(&output.stdout).trim().to_string(); |
| 2107 | if merge_base.is_empty() || !merge_base.bytes().all(|byte| byte.is_ascii_hexdigit()) { |
| 2108 | return Err(ToolError::execution_failed( |
| 2109 | "git merge-base returned an invalid commit id", |
| 2110 | )); |
| 2111 | } |
| 2112 | args.push(merge_base); |
| 2113 | } |
| 2114 | } else if let Some(base_commit) = base_commit { |
| 2115 | args.push(format!("{base_commit}...HEAD")); |
| 2116 | } |
| 2117 | args.push("--".to_string()); |
| 2118 | |
| 2119 | let output = run_review_git(workspace, args, "generate review diff").await?; |
| 2120 | if !output.status.success() { |
| 2121 | let stderr = String::from_utf8_lossy(&output.stderr); |
| 2122 | return Err(ToolError::execution_failed(format!( |
| 2123 | "git diff failed: {}", |
| 2124 | stderr.trim() |
| 2125 | ))); |
| 2126 | } |
| 2127 | let diff = String::from_utf8_lossy(&output.stdout).to_string(); |
| 2128 | if diff.trim().is_empty() { |
| 2129 | return Err(ToolError::invalid_input("No diff to review")); |
| 2130 | } |
| 2131 | Ok(diff) |
| 2132 | } |
| 2133 | |
| 2134 | async fn run_review_git( |
| 2135 | workspace: &Path, |
| 2136 | args: Vec<String>, |
| 2137 | operation: &str, |
| 2138 | ) -> Result<std::process::Output, ToolError> { |
| 2139 | super::git::run_git_command_async(workspace.to_path_buf(), args) |
| 2140 | .await |
| 2141 | .map_err(|error| match error { |
| 2142 | ToolError::ExecutionFailed { message, metadata } => ToolError::ExecutionFailed { |
| 2143 | message: format!("Failed to {operation}: {message}"), |
| 2144 | metadata, |
| 2145 | }, |
| 2146 | other => other, |
| 2147 | }) |
| 2148 | } |
| 2149 | |
| 2150 | async fn gh_pr_source(pr: PullRequestRef, workspace: &Path) -> Result<ReviewSource, ToolError> { |
| 2151 | let workspace = workspace.to_path_buf(); |
| 2152 | tokio::task::spawn_blocking(move || { |
| 2153 | let number = pr |
| 2154 | .number |
| 2155 | .parse::<u32>() |
| 2156 | .map_err(|_| ToolError::invalid_input("Invalid pull request number"))?; |
| 2157 | let repo = format!("{}/{}", pr.owner, pr.repo); |
| 2158 | let view = super::review_pr::fetch_view(number, Some(&repo), &workspace) |
| 2159 | .map_err(|error| ToolError::execution_failed(format!("{error:#}")))?; |
| 2160 | let diff = super::review_pr::fetch_diff(number, Some(&repo), &workspace, &view) |
| 2161 | .map_err(|error| ToolError::execution_failed(format!("{error:#}")))?; |
| 2162 | Ok(ReviewSource::PullRequest { |
| 2163 | label: pr.label(), |
| 2164 | diff, |
| 2165 | pr, |
| 2166 | view: Box::new(view), |
| 2167 | }) |
| 2168 | }) |
| 2169 | .await |
| 2170 | .map_err(|error| ToolError::execution_failed(format!("PR input task failed: {error}")))? |
| 2171 | } |
| 2172 | |
| 2173 | async fn ensure_pr_source_current( |
| 2174 | source: &ReviewSource, |
| 2175 | workspace: &Path, |
| 2176 | ) -> Result<(), ToolError> { |
| 2177 | if let ReviewSource::PullRequest { pr, view, .. } = source { |
| 2178 | let pr = pr.clone(); |
| 2179 | let view = view.clone(); |
| 2180 | let workspace = workspace.to_path_buf(); |
| 2181 | tokio::task::spawn_blocking(move || { |
| 2182 | let number = pr |
| 2183 | .number |
| 2184 | .parse::<u32>() |
| 2185 | .map_err(|_| ToolError::invalid_input("Invalid pull request number"))?; |
| 2186 | super::review_pr::ensure_current( |
| 2187 | number, |
| 2188 | Some(&format!("{}/{}", pr.owner, pr.repo)), |
| 2189 | &workspace, |
| 2190 | &view, |
| 2191 | ) |
| 2192 | .map_err(|error| ToolError::execution_failed(format!("{error:#}"))) |
| 2193 | }) |
| 2194 | .await |
| 2195 | .map_err(|error| { |
| 2196 | ToolError::execution_failed(format!("PR revision check failed: {error}")) |
| 2197 | })??; |
| 2198 | } |
| 2199 | Ok(()) |
| 2200 | } |
| 2201 | |
| 2202 | /// Refuse the complete numbered source before either formatter/provider path. |
| 2203 | fn validate_review_source_size(source: &ReviewSource, max_chars: usize) -> Result<(), ToolError> { |
| 2204 | let chars = match source { |
| 2205 | ReviewSource::File { content, .. } => { |
| 2206 | let mut count = 0usize; |
| 2207 | for (index, line) in content.lines().enumerate() { |
| 2208 | if index > 0 { |
| 2209 | count = count.saturating_add(1); |
| 2210 | } |
| 2211 | let digits = (index + 1).ilog10() as usize + 1; |
| 2212 | count = count |
| 2213 | .saturating_add(digits.max(4) + 3) |
| 2214 | .saturating_add(line.chars().count()); |
| 2215 | } |
| 2216 | count |
| 2217 | } |
| 2218 | ReviewSource::Diff { diff, .. } => diff.chars().count(), |
| 2219 | ReviewSource::PullRequest { .. } => return Ok(()), // Core pass planner owns PR bounds. |
| 2220 | }; |
| 2221 | if chars > max_chars { |
| 2222 | return Err(ToolError::invalid_input(format!( |
| 2223 | "Complete review source has {chars} characters, exceeding max_chars={max_chars}; no source was truncated and no review was run" |
| 2224 | ))); |
| 2225 | } |
| 2226 | Ok(()) |
| 2227 | } |
| 2228 | fn review_source_snapshot(source: &ReviewSource) -> Value { |
| 2229 | match source { |
| 2230 | ReviewSource::File { display, content } => { |
| 2231 | json!({"kind":"file","display":display,"content":content}) |
| 2232 | } |
| 2233 | ReviewSource::Diff { label, diff } => json!({"kind":"diff","label":label,"diff":diff}), |
| 2234 | ReviewSource::PullRequest { |
| 2235 | label, diff, view, .. |
| 2236 | } => { |
| 2237 | json!({"kind":"pr","label":label,"diff":super::review_pr::model_diff(diff),"head_sha":view.head_sha,"base_sha":view.base_sha}) |
| 2238 | } |
| 2239 | } |
| 2240 | } |
| 2241 | |
| 2242 | fn build_review_prompt(source: &ReviewSource) -> String { |
| 2243 | match source { |
| 2244 | ReviewSource::File { |
| 2245 | display, content, .. |
| 2246 | } => { |
| 2247 | let numbered = format_with_line_numbers(content); |
| 2248 | format!( |
| 2249 | "Review the following file and provide feedback.\n\ |
| 2250 | Path: {display}\n\n{numbered}\n\nEnd of file." |
| 2251 | ) |
| 2252 | } |
| 2253 | ReviewSource::Diff { label, diff } => { |
| 2254 | format!("Review the following {label} and provide feedback.\n\n{diff}\n\nEnd of diff.") |
| 2255 | } |
| 2256 | ReviewSource::PullRequest { |
| 2257 | label, diff, view, .. |
| 2258 | } => { |
| 2259 | let diff = super::review_pr::model_diff(diff); |
| 2260 | format!( |
| 2261 | "Review the complete pull request diff ({label}) at head {} and base {}. Binary changes are represented by metadata; their contents are not semantically inspected. Exact binary object IDs remain in the review evidence.\n\n{diff}\n\nEnd of diff.", |
| 2262 | view.head_sha, view.base_sha, |
| 2263 | ) |
| 2264 | } |
| 2265 | } |
| 2266 | } |
| 2267 | |
| 2268 | fn format_with_line_numbers(content: &str) -> String { |
| 2269 | content |
| 2270 | .lines() |
| 2271 | .enumerate() |
| 2272 | .map(|(idx, line)| format!("{:>4} | {}", idx + 1, line)) |
| 2273 | .collect::<Vec<_>>() |
| 2274 | .join("\n") |
| 2275 | } |
| 2276 | |
| 2277 | fn normalize_optional(value: Option<String>) -> Option<String> { |
| 2278 | value |
| 2279 | .map(|v| v.trim().to_string()) |
| 2280 | .filter(|v| !v.is_empty()) |
| 2281 | } |
| 2282 | |
| 2283 | fn normalize_claim_kind(value: &str) -> String { |
| 2284 | match value.trim().to_ascii_lowercase().as_str() { |
| 2285 | "intent" | "intent_mismatch" | "unannounced" => "intent", |
| 2286 | "contract" | "dependent" | "impact" => "contract", |
| 2287 | "defect" | "bug" | "" => "defect", |
| 2288 | other if other.starts_with("intent") => "intent", |
| 2289 | other if other.starts_with("contract") || other.starts_with("depend") => "contract", |
| 2290 | _ => "defect", |
| 2291 | } |
| 2292 | .to_string() |
| 2293 | } |
| 2294 | |
| 2295 | fn normalize_evidence_tier(value: &str) -> String { |
| 2296 | let lower = value.trim().to_ascii_lowercase(); |
| 2297 | if lower.starts_with("repro") || lower.starts_with("verif") { |
| 2298 | "reproduced".to_string() |
| 2299 | } else if lower.starts_with("trace") || lower.starts_with("proven") { |
| 2300 | "traced".to_string() |
| 2301 | } else { |
| 2302 | "suspected".to_string() |
| 2303 | } |
| 2304 | } |
| 2305 | |
| 2306 | fn normalize_severity(value: &str) -> String { |
| 2307 | super::review_core::normalize_review_severity(value) |
| 2308 | } |
| 2309 | |
| 2310 | fn extract_json_block(raw: &str) -> Option<&str> { |
| 2311 | let start = raw.find('{')?; |
| 2312 | let end = raw.rfind('}')?; |
| 2313 | if end <= start { |
| 2314 | None |
| 2315 | } else { |
| 2316 | Some(&raw[start..=end]) |
| 2317 | } |
| 2318 | } |
| 2319 | |
| 2320 | fn diff_mode_from_target(target: &str) -> Option<bool> { |
| 2321 | match target.trim().to_ascii_lowercase().as_str() { |
| 2322 | "diff" | "git diff" | "changes" | "working tree" | "working-tree" => Some(false), |
| 2323 | "staged" | "cached" | "git diff --cached" | "git diff --staged" => Some(true), |
| 2324 | _ => None, |
| 2325 | } |
| 2326 | } |
| 2327 | |
| 2328 | #[derive(Debug, Clone)] |
| 2329 | struct PullRequestRef { |
| 2330 | owner: String, |
| 2331 | repo: String, |
| 2332 | number: String, |
| 2333 | } |
| 2334 | |
| 2335 | impl PullRequestRef { |
| 2336 | fn label(&self) -> String { |
| 2337 | format!("{}/{}#{}", self.owner, self.repo, self.number) |
| 2338 | } |
| 2339 | } |
| 2340 | |
| 2341 | fn parse_pr_url(url: &str) -> Option<PullRequestRef> { |
| 2342 | let trimmed = url.trim().trim_end_matches('/'); |
| 2343 | if !trimmed.starts_with("http") { |
| 2344 | return None; |
| 2345 | } |
| 2346 | let parts: Vec<&str> = trimmed.split('/').collect(); |
| 2347 | let pull_idx = parts.iter().position(|part| *part == "pull")?; |
| 2348 | if pull_idx < 2 || pull_idx + 1 >= parts.len() { |
| 2349 | return None; |
| 2350 | } |
| 2351 | let owner = parts.get(pull_idx.saturating_sub(2))?; |
| 2352 | let repo = parts.get(pull_idx.saturating_sub(1))?; |
| 2353 | let number = parts.get(pull_idx + 1)?; |
| 2354 | if owner.is_empty() || repo.is_empty() || number.is_empty() { |
| 2355 | return None; |
| 2356 | } |
| 2357 | Some(PullRequestRef { |
| 2358 | owner: (*owner).to_string(), |
| 2359 | repo: (*repo).to_string(), |
| 2360 | number: (*number).to_string(), |
| 2361 | }) |
| 2362 | } |
| 2363 | |
| 2364 | #[cfg(test)] |
| 2365 | mod tests { |
| 2366 | use super::*; |
| 2367 | |
| 2368 | #[test] |
| 2369 | fn request_failure_message_keeps_the_provider_failure_beneath_the_context() { |
| 2370 | let error = anyhow::Error::new(crate::llm_client::LlmError::ServerError { |
| 2371 | status: 503, |
| 2372 | message: "upstream unavailable".into(), |
| 2373 | }) |
| 2374 | .context("Responses API request failed"); |
| 2375 | let message = request_failure_message(1, 1, &error); |
| 2376 | assert_eq!( |
| 2377 | message, |
| 2378 | "Review pass 1/1 request failed: Responses API request failed: Server error (503): upstream unavailable" |
| 2379 | ); |
| 2380 | } |
| 2381 | |
| 2382 | #[test] |
| 2383 | fn complete_numbered_review_source_refuses_instead_of_truncating() { |
| 2384 | for content in ["", "漢字🐋e\u{301}\r\nlast\r", "\n", "x\n"] { |
| 2385 | let source = ReviewSource::File { |
| 2386 | display: "x".into(), |
| 2387 | content: content.into(), |
| 2388 | }; |
| 2389 | let numbered = format_with_line_numbers(content); |
| 2390 | let chars = numbered.chars().count(); |
| 2391 | assert!(validate_review_source_size(&source, chars).is_ok()); |
| 2392 | if chars > 0 { |
| 2393 | assert!(matches!( |
| 2394 | validate_review_source_size(&source, chars - 1), |
| 2395 | Err(ToolError::InvalidInput { .. }) |
| 2396 | )); |
| 2397 | } |
| 2398 | assert!(build_review_prompt(&source).contains(&numbered)); |
| 2399 | } |
| 2400 | let source = ReviewSource::Diff { |
| 2401 | label: "working diff".into(), |
| 2402 | diff: "漢字🐋END".into(), |
| 2403 | }; |
| 2404 | assert!(validate_review_source_size(&source, 6).is_ok()); |
| 2405 | assert!(validate_review_source_size(&source, 5).is_err()); |
| 2406 | assert!(build_review_prompt(&source).contains("漢字🐋END")); |
| 2407 | } |
| 2408 | |
| 2409 | #[tokio::test(flavor = "current_thread")] |
| 2410 | async fn actual_review_tool_refuses_complete_source_before_provider_on_both_backends() { |
| 2411 | let _home = crate::test_support::SealedHome::new(); |
| 2412 | let root = tempfile::tempdir().unwrap(); |
| 2413 | std::fs::write( |
| 2414 | root.path().join("source.rs"), |
| 2415 | "unreviewed tail must not disappear", |
| 2416 | ) |
| 2417 | .unwrap(); |
| 2418 | let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); |
| 2419 | listener.set_nonblocking(true).unwrap(); |
| 2420 | let base = format!("http://{}/v1", listener.local_addr().unwrap()); |
| 2421 | let client = CodewhaleClient::new(&{ |
| 2422 | let __cw_config_init_0_0 = Some("moonshot".into()); |
| 2423 | let __cw_config_init_0_1 = Some(codewhale_runtime::config::ProvidersConfig { |
| 2424 | moonshot: codewhale_runtime::config::ProviderConfig { |
| 2425 | api_key: Some("local-fixture-key".into()), |
| 2426 | base_url: Some(base), |
| 2427 | model: Some("kimi-k2.5".into()), |
| 2428 | ..Default::default() |
| 2429 | }, |
| 2430 | ..Default::default() |
| 2431 | }); |
| 2432 | let mut __cw_config_init_0_value: codewhale_runtime::config::Config = |
| 2433 | Default::default(); |
| 2434 | __cw_config_init_0_value.provider = __cw_config_init_0_0; |
| 2435 | __cw_config_init_0_value.providers = __cw_config_init_0_1; |
| 2436 | __cw_config_init_0_value |
| 2437 | }) |
| 2438 | .unwrap(); |
| 2439 | let tool = ReviewTool::new(Some(client), "kimi-k2.5".into()); |
| 2440 | for host in [false, true] { |
| 2441 | let mut features = codewhale_runtime::features::Features::with_defaults(); |
| 2442 | if host { |
| 2443 | features.enable(codewhale_runtime::features::Feature::ReviewHost); |
| 2444 | } |
| 2445 | let context = ToolContext::new(root.path()).with_features(features); |
| 2446 | let error = tokio::time::timeout( |
| 2447 | std::time::Duration::from_secs(1), |
| 2448 | tool.execute( |
| 2449 | json!({"target":"source.rs","kind":"file","max_chars":8}), |
| 2450 | &context, |
| 2451 | ), |
| 2452 | ) |
| 2453 | .await |
| 2454 | .unwrap() |
| 2455 | .unwrap_err(); |
| 2456 | assert!(matches!(error, ToolError::InvalidInput { .. }), "{error}"); |
| 2457 | assert!(error.to_string().contains("no source was truncated")); |
| 2458 | assert_eq!( |
| 2459 | listener.accept().unwrap_err().kind(), |
| 2460 | std::io::ErrorKind::WouldBlock, |
| 2461 | "provider must not be called" |
| 2462 | ); |
| 2463 | } |
| 2464 | } |
| 2465 | |
| 2466 | #[test] |
| 2467 | fn resolve_file_target_rejects_oversized_file_against_caller_max_chars() { |
| 2468 | let root = tempfile::tempdir().unwrap(); |
| 2469 | let payload = "a".repeat(20_000); |
| 2470 | std::fs::write(root.path().join("big.txt"), &payload).unwrap(); |
| 2471 | let context = ToolContext::new(root.path()); |
| 2472 | |
| 2473 | let err = resolve_file_target("big.txt", 1_000, &context) |
| 2474 | .err() |
| 2475 | .expect("file exceeding caller max_chars * 4 must be rejected before full read"); |
| 2476 | assert!(matches!(err, ToolError::InvalidInput { .. }), "{err}"); |
| 2477 | let msg = err.to_string(); |
| 2478 | assert!(msg.contains("20000 bytes"), "{msg}"); |
| 2479 | assert!(msg.contains("no source was truncated"), "{msg}"); |
| 2480 | |
| 2481 | let ok = resolve_file_target("big.txt", 25_000, &context) |
| 2482 | .expect("file within caller max_chars succeeds"); |
| 2483 | match ok { |
| 2484 | ReviewSource::File { display, content } => { |
| 2485 | assert!(display.ends_with("big.txt"), "{display}"); |
| 2486 | assert_eq!(content.len(), 20_000); |
| 2487 | } |
| 2488 | _ => panic!("expected ReviewSource::File"), |
| 2489 | } |
| 2490 | } |
| 2491 | |
| 2492 | #[test] |
| 2493 | fn resolve_file_target_rejects_directory_read_only_root_and_outside_hardlink() { |
| 2494 | let workspace = tempfile::tempdir().expect("workspace"); |
| 2495 | let ro_root = tempfile::tempdir().expect("read-only root"); |
| 2496 | let subdir = workspace.path().join("subdir"); |
| 2497 | std::fs::create_dir_all(&subdir).expect("mkdir subdir"); |
| 2498 | let ro_file = ro_root.path().join("ro.rs"); |
| 2499 | std::fs::write(&ro_file, "fn ro() {}\n").expect("write ro"); |
| 2500 | |
| 2501 | let ro_canon = ro_root.path().canonicalize().expect("canon ro"); |
| 2502 | let ctx = ToolContext::new(workspace.path()).with_read_only_roots(vec![ro_canon]); |
| 2503 | |
| 2504 | let dir_err = resolve_file_target("subdir", 1_000, &ctx) |
| 2505 | .err() |
| 2506 | .expect("directory must be rejected as non-file"); |
| 2507 | assert!( |
| 2508 | matches!(dir_err, ToolError::InvalidInput { .. }), |
| 2509 | "{dir_err:?}" |
| 2510 | ); |
| 2511 | assert!( |
| 2512 | dir_err.to_string().contains("Target is not a file:"), |
| 2513 | "{dir_err}" |
| 2514 | ); |
| 2515 | |
| 2516 | let ro_err = resolve_file_target(&ro_file.to_string_lossy(), 1_000, &ctx) |
| 2517 | .err() |
| 2518 | .expect("review must not read from read_only_roots"); |
| 2519 | assert!(matches!(ro_err, ToolError::PathEscape { .. }), "{ro_err:?}"); |
| 2520 | |
| 2521 | #[cfg(unix)] |
| 2522 | { |
| 2523 | let outside = tempfile::tempdir().expect("outside"); |
| 2524 | let original = outside.path().join("orig.rs"); |
| 2525 | let linked = outside.path().join("alias.rs"); |
| 2526 | std::fs::write(&original, "fn secret() {}\n").expect("write orig"); |
| 2527 | std::fs::hard_link(&original, &linked).expect("hardlink"); |
| 2528 | let trusted_ctx = ToolContext::new(workspace.path()).with_trust_mode(true); |
| 2529 | let link_err = resolve_file_target(&linked.to_string_lossy(), 1_000, &trusted_ctx) |
| 2530 | .err() |
| 2531 | .expect("outside hardlink must be refused by verified-handle reader"); |
| 2532 | assert!( |
| 2533 | matches!(link_err, ToolError::PermissionDenied { .. }), |
| 2534 | "{link_err:?}" |
| 2535 | ); |
| 2536 | } |
| 2537 | } |
| 2538 | |
| 2539 | fn pr_view(files: usize) -> super::super::review_pr::GhPullRequest { |
| 2540 | super::super::review_pr::GhPullRequest { |
| 2541 | title: "Batch fixture".into(), |
| 2542 | body: "Review every pass".into(), |
| 2543 | base: "main".into(), |
| 2544 | head: "feature".into(), |
| 2545 | url: "https://github.com/example/repo/pull/1".into(), |
| 2546 | base_sha: "a".repeat(40), |
| 2547 | head_sha: "b".repeat(40), |
| 2548 | changed_files: files, |
| 2549 | additions: files, |
| 2550 | deletions: 0, |
| 2551 | } |
| 2552 | } |
| 2553 | |
| 2554 | fn pr_patch(name: &str, content: &str) -> String { |
| 2555 | format!( |
| 2556 | "diff --git a/{name} b/{name}\nnew file mode 100644\n--- /dev/null\n+++ b/{name}\n@@ -0,0 +1 @@\n+{content}\n" |
| 2557 | ) |
| 2558 | } |
| 2559 | |
| 2560 | fn pr_multi_hunk_patch(name: &str, contents: &[&str]) -> String { |
| 2561 | let mut patch = format!( |
| 2562 | "diff --git a/{name} b/{name}\nindex {}..{} 100644\n--- a/{name}\n+++ b/{name}\n", |
| 2563 | "1".repeat(40), |
| 2564 | "2".repeat(40) |
| 2565 | ); |
| 2566 | for (index, content) in contents.iter().enumerate() { |
| 2567 | patch.push_str(&format!( |
| 2568 | "@@ -{0},1 +{0},1 @@\n-old{0}\n+{content}\n", |
| 2569 | index + 1 |
| 2570 | )); |
| 2571 | } |
| 2572 | patch |
| 2573 | } |
| 2574 | |
| 2575 | fn clean_pass(summary: &str) -> String { |
| 2576 | json!({ |
| 2577 | "summary": summary, |
| 2578 | "issues": [], |
| 2579 | "suggestions": [], |
| 2580 | "overall_assessment": "No issue in this pass" |
| 2581 | }) |
| 2582 | .to_string() |
| 2583 | } |
| 2584 | |
| 2585 | #[test] |
| 2586 | fn pr_batch_plan_degrades_to_first_pass_and_names_skipped_files() { |
| 2587 | let patches = [ |
| 2588 | pr_patch("a.txt", "alpha"), |
| 2589 | pr_patch("b.txt", "🐋"), |
| 2590 | pr_patch("c.txt", "charlie"), |
| 2591 | ]; |
| 2592 | let diff = patches.concat(); |
| 2593 | let max_chars = patches |
| 2594 | .iter() |
| 2595 | .map(|patch| patch.chars().count()) |
| 2596 | .max() |
| 2597 | .unwrap(); |
| 2598 | // One pass of budget: the first file is reviewed, the rest are |
| 2599 | // skipped in diff order and named — never silently dropped. |
| 2600 | let degraded = plan_pr_review(&diff, &pr_view(3), max_chars, 1).unwrap(); |
| 2601 | assert_eq!(degraded.passes.len(), 1); |
| 2602 | assert_eq!(degraded.passes[0].diff, patches[0]); |
| 2603 | assert_eq!(degraded.manifest.passes[0].files, ["a/a.txt b/a.txt"]); |
| 2604 | assert_eq!(degraded.manifest.skipped_files.len(), 2); |
| 2605 | assert_eq!(degraded.manifest.skipped_files[0].file, "a/b.txt b/b.txt"); |
| 2606 | assert_eq!(degraded.manifest.skipped_files[1].file, "a/c.txt b/c.txt"); |
| 2607 | assert!( |
| 2608 | degraded |
| 2609 | .manifest |
| 2610 | .skipped_files |
| 2611 | .iter() |
| 2612 | .all(|skip| skip.reason == SKIP_REASON_BEYOND_MAX_PASSES) |
| 2613 | ); |
| 2614 | |
| 2615 | let plan = plan_pr_review(&diff, &pr_view(3), max_chars, 3).unwrap(); |
| 2616 | assert_eq!(plan.passes.len(), 3); |
| 2617 | assert!(plan.manifest.skipped_files.is_empty()); |
| 2618 | assert_eq!( |
| 2619 | plan.passes |
| 2620 | .iter() |
| 2621 | .map(|pass| pass.diff.as_str()) |
| 2622 | .collect::<String>(), |
| 2623 | diff |
| 2624 | ); |
| 2625 | assert_eq!(plan.manifest.diff_chars, diff.chars().count()); |
| 2626 | assert_eq!(plan.manifest.passes[1].files, ["a/b.txt b/b.txt"]); |
| 2627 | assert!(plan.passes[1].diff.contains("🐋")); |
| 2628 | } |
| 2629 | |
| 2630 | #[test] |
| 2631 | fn pr_batch_plan_rejects_one_file_overflow_before_any_pass() { |
| 2632 | let diff = pr_patch("large.txt", &"x".repeat(200)); |
| 2633 | let error = plan_pr_review(&diff, &pr_view(1), 100, MAX_REVIEW_PASSES).unwrap_err(); |
| 2634 | let message = error.to_string(); |
| 2635 | assert!(message.contains("covers 0 of 1 file patches"), "{message}"); |
| 2636 | assert!(message.contains("large.txt"), "{message}"); |
| 2637 | assert!(message.contains(SKIP_REASON_HUNK_EXCEEDS_PASS), "{message}"); |
| 2638 | assert!(message.contains("No review was run or posted"), "{message}"); |
| 2639 | } |
| 2640 | |
| 2641 | #[test] |
| 2642 | fn pr_batch_plan_skips_oversized_file_and_reviews_the_rest() { |
| 2643 | let ok = pr_patch("ok.txt", "fine"); |
| 2644 | let big = pr_multi_hunk_patch("big.txt", &["fine", &"x".repeat(500)]); |
| 2645 | let diff = format!("{ok}{big}"); |
| 2646 | let max_chars = ok.chars().count(); |
| 2647 | let plan = plan_pr_review(&diff, &pr_view(2), max_chars, MAX_REVIEW_PASSES).unwrap(); |
| 2648 | assert_eq!(plan.passes.len(), 1); |
| 2649 | assert_eq!(plan.passes[0].diff, ok); |
| 2650 | assert_eq!(plan.manifest.skipped_files.len(), 1); |
| 2651 | assert_eq!(plan.manifest.skipped_files[0].file, "a/big.txt b/big.txt"); |
| 2652 | assert_eq!( |
| 2653 | plan.manifest.skipped_files[0].reason, |
| 2654 | SKIP_REASON_HUNK_EXCEEDS_PASS |
| 2655 | ); |
| 2656 | assert!(plan.manifest.skipped_files[0].chars > max_chars); |
| 2657 | } |
| 2658 | |
| 2659 | #[test] |
| 2660 | fn pr_batch_plan_splits_oversized_file_only_at_complete_hunk_boundaries() { |
| 2661 | let contents = ["alpha", "bravo", "charlie", "delta"]; |
| 2662 | let patch = pr_multi_hunk_patch("big.txt", &contents); |
| 2663 | let (header, hunks) = pr_file_hunks(&patch); |
| 2664 | assert_eq!(hunks.len(), 4); |
| 2665 | assert!(hunks.iter().all(|hunk| hunk.starts_with("@@ "))); |
| 2666 | assert_eq!(format!("{header}{}", hunks.concat()), patch); |
| 2667 | |
| 2668 | // A file that fits is never split. |
| 2669 | let whole = plan_pr_review(&patch, &pr_view(1), patch.chars().count(), 1).unwrap(); |
| 2670 | assert_eq!(whole.passes.len(), 1); |
| 2671 | assert_eq!(whole.passes[0].diff, patch); |
| 2672 | assert_eq!(whole.manifest.passes[0].files, ["a/big.txt b/big.txt"]); |
| 2673 | |
| 2674 | // Header plus the largest hunk fits, so header plus any two hunks does |
| 2675 | // not: exactly one hunk per part, four parts, four passes. |
| 2676 | let max_chars = |
| 2677 | header.chars().count() + hunks.iter().map(|hunk| hunk.chars().count()).max().unwrap(); |
| 2678 | // Three passes of budget for four parts: the first three parts are |
| 2679 | // reviewed and the last part is skipped by name. |
| 2680 | let degraded = plan_pr_review(&patch, &pr_view(1), max_chars, 3).unwrap(); |
| 2681 | assert_eq!(degraded.passes.len(), 3); |
| 2682 | assert_eq!(degraded.manifest.skipped_files.len(), 1); |
| 2683 | assert_eq!( |
| 2684 | degraded.manifest.skipped_files[0].file, |
| 2685 | "a/big.txt b/big.txt (part 4/4)" |
| 2686 | ); |
| 2687 | assert_eq!( |
| 2688 | degraded.manifest.skipped_files[0].reason, |
| 2689 | SKIP_REASON_BEYOND_MAX_PASSES |
| 2690 | ); |
| 2691 | |
| 2692 | let plan = plan_pr_review(&patch, &pr_view(1), max_chars, 4).unwrap(); |
| 2693 | assert_eq!(plan.passes.len(), 4); |
| 2694 | assert_eq!(plan.manifest.file_count, 1); |
| 2695 | let mut rebuilt = String::new(); |
| 2696 | for (index, pass) in plan.passes.iter().enumerate() { |
| 2697 | assert!(pass.diff.starts_with(header)); |
| 2698 | assert!(pass.diff.contains(&format!("+{}", contents[index]))); |
| 2699 | assert_eq!(pass.manifest.diff_chars, pass.diff.chars().count()); |
| 2700 | assert!(pass.manifest.diff_chars <= max_chars); |
| 2701 | assert_eq!( |
| 2702 | pass.manifest.files, |
| 2703 | [format!("a/big.txt b/big.txt (part {}/4)", index + 1)] |
| 2704 | ); |
| 2705 | assert_eq!(pass.manifest.file_count, 1); |
| 2706 | if index == 0 { |
| 2707 | rebuilt.push_str(&pass.diff); |
| 2708 | } else { |
| 2709 | rebuilt.push_str( |
| 2710 | pass.diff |
| 2711 | .strip_prefix(header) |
| 2712 | .expect("continuation part replays the full file header"), |
| 2713 | ); |
| 2714 | } |
| 2715 | } |
| 2716 | assert_eq!(rebuilt, patch); |
| 2717 | } |
| 2718 | |
| 2719 | #[test] |
| 2720 | fn pr_batch_plan_refuses_when_one_hunk_with_header_cannot_fit() { |
| 2721 | let patch = pr_multi_hunk_patch("mixed.txt", &["ok", &"x".repeat(500)]); |
| 2722 | let (header, hunks) = pr_file_hunks(&patch); |
| 2723 | // The small hunk fits with the header; the large one does not, so the |
| 2724 | // file cannot be split and the plan must fail before any pass. |
| 2725 | let max_chars = header.chars().count() + hunks[0].chars().count(); |
| 2726 | let error = plan_pr_review(&patch, &pr_view(1), max_chars, MAX_REVIEW_PASSES).unwrap_err(); |
| 2727 | let message = error.to_string(); |
| 2728 | assert!(message.contains("mixed.txt"), "{message}"); |
| 2729 | assert!(message.contains("covers 0 of 1 file patches"), "{message}"); |
| 2730 | assert!(message.contains(SKIP_REASON_HUNK_EXCEEDS_PASS), "{message}"); |
| 2731 | assert!(message.contains("No review was run or posted"), "{message}"); |
| 2732 | } |
| 2733 | |
| 2734 | #[test] |
| 2735 | fn pr_batch_plan_never_splits_a_binary_patch_for_its_omitted_payload() { |
| 2736 | let patch = format!( |
| 2737 | "diff --git a/blob.bin b/blob.bin\nindex {}..{} 100644\nGIT binary patch\nliteral 8\n{}\n", |
| 2738 | "1".repeat(40), |
| 2739 | "2".repeat(40), |
| 2740 | "z".repeat(10_000) |
| 2741 | ); |
| 2742 | let model_chars = super::super::review_pr::model_diff(&patch).chars().count(); |
| 2743 | assert!(model_chars < patch.chars().count()); |
| 2744 | let plan = plan_pr_review(&patch, &pr_view(1), model_chars, 1).unwrap(); |
| 2745 | assert_eq!(plan.passes.len(), 1); |
| 2746 | assert_eq!(plan.passes[0].diff, patch); |
| 2747 | assert_eq!(plan.manifest.passes[0].files, ["a/blob.bin b/blob.bin"]); |
| 2748 | assert_eq!(plan.manifest.binary_file_patches, 1); |
| 2749 | } |
| 2750 | |
| 2751 | #[test] |
| 2752 | fn pr_batch_plan_counts_distinct_files_when_a_split_shares_the_plan() { |
| 2753 | let hunk_content = "x".repeat(200); |
| 2754 | let big = pr_multi_hunk_patch( |
| 2755 | "big.txt", |
| 2756 | &[ |
| 2757 | hunk_content.as_str(), |
| 2758 | hunk_content.as_str(), |
| 2759 | hunk_content.as_str(), |
| 2760 | ], |
| 2761 | ); |
| 2762 | let small = pr_patch("small.txt", "tiny"); |
| 2763 | let diff = format!("{big}{small}"); |
| 2764 | let (header, hunks) = pr_file_hunks(&big); |
| 2765 | let hunk_chars = hunks[0].chars().count(); |
| 2766 | let header_chars = header.chars().count(); |
| 2767 | // Two parts for big.txt (header + two hunks, header + one hunk), then |
| 2768 | // small.txt packed after the second part. |
| 2769 | let max_chars = header_chars + 2 * hunk_chars + small.chars().count(); |
| 2770 | assert!(big.chars().count() > max_chars); |
| 2771 | let plan = plan_pr_review(&diff, &pr_view(2), max_chars, 2).unwrap(); |
| 2772 | assert_eq!(plan.passes.len(), 2); |
| 2773 | assert_eq!(plan.manifest.file_count, 2); |
| 2774 | assert_eq!( |
| 2775 | plan.manifest.passes[0].files, |
| 2776 | ["a/big.txt b/big.txt (part 1/2)"] |
| 2777 | ); |
| 2778 | assert_eq!(plan.manifest.passes[0].file_count, 1); |
| 2779 | assert_eq!( |
| 2780 | plan.manifest.passes[1].files, |
| 2781 | [ |
| 2782 | "a/big.txt b/big.txt (part 2/2)".to_string(), |
| 2783 | "a/small.txt b/small.txt".to_string() |
| 2784 | ] |
| 2785 | ); |
| 2786 | assert_eq!(plan.manifest.passes[1].file_count, 2); |
| 2787 | // The second pass holds big.txt's continuation (header replayed), |
| 2788 | // then small.txt whole; stripping the one repeated header rebuilds |
| 2789 | // the original diff byte-for-byte. |
| 2790 | let mut rebuilt = plan.passes[0].diff.clone(); |
| 2791 | rebuilt.push_str( |
| 2792 | plan.passes[1] |
| 2793 | .diff |
| 2794 | .strip_prefix(header) |
| 2795 | .expect("continuation part replays the full file header"), |
| 2796 | ); |
| 2797 | assert_eq!(rebuilt, diff); |
| 2798 | } |
| 2799 | |
| 2800 | #[test] |
| 2801 | fn pr_batch_accumulator_rejects_missing_malformed_and_unordered_middle_passes() { |
| 2802 | let patches = [ |
| 2803 | pr_patch("a.txt", "alpha"), |
| 2804 | pr_patch("b.txt", "bravo"), |
| 2805 | pr_patch("c.txt", "charlie"), |
| 2806 | ]; |
| 2807 | let diff = patches.concat(); |
| 2808 | let max_chars = patches |
| 2809 | .iter() |
| 2810 | .map(|patch| patch.chars().count()) |
| 2811 | .max() |
| 2812 | .unwrap(); |
| 2813 | let plan = plan_pr_review(&diff, &pr_view(3), max_chars, 3).unwrap(); |
| 2814 | |
| 2815 | let mut missing = PrReviewAccumulator::new(&plan); |
| 2816 | missing |
| 2817 | .accept(&plan.passes[0], clean_pass("first")) |
| 2818 | .unwrap(); |
| 2819 | assert!( |
| 2820 | missing |
| 2821 | .finish(&diff) |
| 2822 | .unwrap_err() |
| 2823 | .to_string() |
| 2824 | .contains("Only 1/3") |
| 2825 | ); |
| 2826 | |
| 2827 | let mut malformed = PrReviewAccumulator::new(&plan); |
| 2828 | malformed |
| 2829 | .accept(&plan.passes[0], clean_pass("first")) |
| 2830 | .unwrap(); |
| 2831 | assert!( |
| 2832 | malformed |
| 2833 | .accept(&plan.passes[1], "not JSON".into()) |
| 2834 | .is_err() |
| 2835 | ); |
| 2836 | assert!(malformed.accept(&plan.passes[1], "{}".into()).is_err()); |
| 2837 | assert!( |
| 2838 | malformed |
| 2839 | .finish(&diff) |
| 2840 | .unwrap_err() |
| 2841 | .to_string() |
| 2842 | .contains("Only 1/3") |
| 2843 | ); |
| 2844 | |
| 2845 | let mut unordered = PrReviewAccumulator::new(&plan); |
| 2846 | assert!( |
| 2847 | unordered |
| 2848 | .accept(&plan.passes[1], clean_pass("second")) |
| 2849 | .is_err() |
| 2850 | ); |
| 2851 | } |
| 2852 | |
| 2853 | #[test] |
| 2854 | fn pr_batch_aggregate_binds_complete_diff_counts_coverage_and_revision() { |
| 2855 | let first = pr_patch("a.txt", "alpha"); |
| 2856 | let second = pr_patch("b.txt", "bravo"); |
| 2857 | let diff = format!("{first}{second}"); |
| 2858 | let max_chars = first.chars().count().max(second.chars().count()); |
| 2859 | let view = pr_view(2); |
| 2860 | let plan = plan_pr_review(&diff, &view, max_chars, 2).unwrap(); |
| 2861 | let mut accumulator = PrReviewAccumulator::new(&plan); |
| 2862 | accumulator |
| 2863 | .accept( |
| 2864 | &plan.passes[0], |
| 2865 | json!({ |
| 2866 | "summary": "first", |
| 2867 | "issues": [{"severity":"warning","title":"A","description":"a","path":"a.txt","line":1}], |
| 2868 | "suggestions": [], |
| 2869 | "overall_assessment": "first assessment" |
| 2870 | }) |
| 2871 | .to_string(), |
| 2872 | ) |
| 2873 | .unwrap(); |
| 2874 | accumulator |
| 2875 | .accept( |
| 2876 | &plan.passes[1], |
| 2877 | json!({ |
| 2878 | "summary": "second", |
| 2879 | "issues": [{"severity":"error","title":"B","description":"b","path":"b.txt","line":1}], |
| 2880 | "suggestions": [{"path":"b.txt","line":1,"suggestion":"fix"}], |
| 2881 | "overall_assessment": "second assessment" |
| 2882 | }) |
| 2883 | .to_string(), |
| 2884 | ) |
| 2885 | .unwrap(); |
| 2886 | let (output, content, coverage) = accumulator.finish(&diff).unwrap(); |
| 2887 | assert_eq!(output.issues.len(), 2); |
| 2888 | assert_eq!(output.suggestions.len(), 1); |
| 2889 | assert!(output.summary.contains("2/2 passes, 2 file patches")); |
| 2890 | assert_eq!(coverage.completed_passes.len(), 2); |
| 2891 | |
| 2892 | let mut receipt = build_review_receipt( |
| 2893 | "pr:1", |
| 2894 | &diff, |
| 2895 | "fixture", |
| 2896 | "fixture-model", |
| 2897 | &output, |
| 2898 | &content, |
| 2899 | Vec::new(), |
| 2900 | ); |
| 2901 | attach_pr_review_coverage(&mut receipt, coverage).unwrap(); |
| 2902 | assert_eq!(receipt.schema_version, PR_COVERAGE_RECEIPT_SCHEMA_VERSION); |
| 2903 | assert_eq!(receipt.findings.issue_count, 2); |
| 2904 | assert_eq!(receipt.findings.suggestion_count, 1); |
| 2905 | let unresolved = validate_review_receipt_for_diff(&diff, &receipt, None); |
| 2906 | assert!(!unresolved.passed); |
| 2907 | assert!(unresolved.reason.contains("unresolved review issue")); |
| 2908 | |
| 2909 | let mut clean_accumulator = PrReviewAccumulator::new(&plan); |
| 2910 | for (index, pass) in plan.passes.iter().enumerate() { |
| 2911 | clean_accumulator |
| 2912 | .accept(pass, clean_pass(&format!("clean pass {}", index + 1))) |
| 2913 | .unwrap(); |
| 2914 | } |
| 2915 | let (clean_output, clean_content, clean_coverage) = |
| 2916 | clean_accumulator.finish(&diff).unwrap(); |
| 2917 | let mut receipt = build_review_receipt( |
| 2918 | "pr:1", |
| 2919 | &diff, |
| 2920 | "fixture", |
| 2921 | "fixture-model", |
| 2922 | &clean_output, |
| 2923 | &clean_content, |
| 2924 | Vec::new(), |
| 2925 | ); |
| 2926 | attach_pr_review_coverage(&mut receipt, clean_coverage).unwrap(); |
| 2927 | assert!(validate_review_receipt_for_diff(&diff, &receipt, None).passed); |
| 2928 | let mut missing = receipt.clone(); |
| 2929 | missing |
| 2930 | .coverage |
| 2931 | .as_mut() |
| 2932 | .unwrap() |
| 2933 | .completed_passes |
| 2934 | .remove(0); |
| 2935 | assert!(!validate_review_receipt_for_diff(&diff, &missing, None).passed); |
| 2936 | let mut tampered = receipt.clone(); |
| 2937 | tampered |
| 2938 | .coverage |
| 2939 | .as_mut() |
| 2940 | .unwrap() |
| 2941 | .manifest |
| 2942 | .passes |
| 2943 | .swap(0, 1); |
| 2944 | assert!(!validate_review_receipt_for_diff(&diff, &tampered, None).passed); |
| 2945 | let mut drifted = view.clone(); |
| 2946 | drifted.head_sha = "c".repeat(40); |
| 2947 | assert!(!receipt_matches_pr_revision(&receipt, &drifted)); |
| 2948 | assert!( |
| 2949 | PrReviewAccumulator::new(&plan) |
| 2950 | .finish(&(diff.clone() + "drift")) |
| 2951 | .is_err() |
| 2952 | ); |
| 2953 | } |
| 2954 | |
| 2955 | #[test] |
| 2956 | fn pr_batch_aggregate_reports_partial_coverage_and_receipt_check_names_skips() { |
| 2957 | let first = pr_patch("a.txt", "alpha"); |
| 2958 | let second = pr_patch("b.txt", "bravo"); |
| 2959 | let diff = format!("{first}{second}"); |
| 2960 | let max_chars = first.chars().count().max(second.chars().count()); |
| 2961 | let plan = plan_pr_review(&diff, &pr_view(2), max_chars, 1).unwrap(); |
| 2962 | assert_eq!(plan.passes.len(), 1); |
| 2963 | assert_eq!(plan.manifest.skipped_files.len(), 1); |
| 2964 | let mut accumulator = PrReviewAccumulator::new(&plan); |
| 2965 | accumulator |
| 2966 | .accept( |
| 2967 | &plan.passes[0], |
| 2968 | json!({ |
| 2969 | "summary": "first", |
| 2970 | "issues": [], |
| 2971 | "suggestions": [], |
| 2972 | "overall_assessment": "" |
| 2973 | }) |
| 2974 | .to_string(), |
| 2975 | ) |
| 2976 | .unwrap(); |
| 2977 | let (output, content, coverage) = accumulator.finish(&diff).unwrap(); |
| 2978 | assert!( |
| 2979 | output.summary.contains("Partial review coverage"), |
| 2980 | "{}", |
| 2981 | output.summary |
| 2982 | ); |
| 2983 | assert!( |
| 2984 | output.summary.contains("a/b.txt b/b.txt"), |
| 2985 | "{}", |
| 2986 | output.summary |
| 2987 | ); |
| 2988 | assert!( |
| 2989 | !output.summary.contains("Complete review coverage"), |
| 2990 | "{}", |
| 2991 | output.summary |
| 2992 | ); |
| 2993 | assert!( |
| 2994 | output.overall_assessment.contains("Partial review"), |
| 2995 | "{}", |
| 2996 | output.overall_assessment |
| 2997 | ); |
| 2998 | let mut receipt = build_review_receipt( |
| 2999 | "pr:1", |
| 3000 | &diff, |
| 3001 | "fixture", |
| 3002 | "fixture-model", |
| 3003 | &output, |
| 3004 | &content, |
| 3005 | Vec::new(), |
| 3006 | ); |
| 3007 | attach_pr_review_coverage(&mut receipt, coverage).unwrap(); |
| 3008 | let validation = validate_review_receipt_for_diff(&diff, &receipt, None); |
| 3009 | assert!(!validation.passed); |
| 3010 | assert!( |
| 3011 | validation.reason.contains("partial review"), |
| 3012 | "{}", |
| 3013 | validation.reason |
| 3014 | ); |
| 3015 | assert!( |
| 3016 | validation.reason.contains("a/b.txt b/b.txt"), |
| 3017 | "{}", |
| 3018 | validation.reason |
| 3019 | ); |
| 3020 | } |
| 3021 | |
| 3022 | #[test] |
| 3023 | fn pr_pass_prompt_marks_degraded_plans_partial_for_the_model() { |
| 3024 | let first = pr_patch("a.txt", "alpha"); |
| 3025 | let second = pr_patch("b.txt", "bravo"); |
| 3026 | let diff = format!("{first}{second}"); |
| 3027 | let max_chars = first.chars().count().max(second.chars().count()); |
| 3028 | let view = pr_view(2); |
| 3029 | let workspace = tempfile::tempdir().unwrap(); |
| 3030 | let degraded = plan_pr_review(&diff, &view, max_chars, 1).unwrap(); |
| 3031 | let prompt = |
| 3032 | build_pr_pass_prompt(1, &view, °raded, °raded.passes[0], workspace.path()); |
| 3033 | let task = serde_json::from_str::<serde_json::Value>(&prompt).unwrap()["task"] |
| 3034 | .as_str() |
| 3035 | .unwrap() |
| 3036 | .to_string(); |
| 3037 | assert!(task.contains("partial review"), "{task}"); |
| 3038 | assert!(task.contains("pass 1 of 1"), "{task}"); |
| 3039 | assert!(task.contains("a/b.txt b/b.txt"), "{task}"); |
| 3040 | let complete = plan_pr_review(&diff, &view, max_chars, 2).unwrap(); |
| 3041 | let prompt = |
| 3042 | build_pr_pass_prompt(1, &view, &complete, &complete.passes[0], workspace.path()); |
| 3043 | let task = serde_json::from_str::<serde_json::Value>(&prompt).unwrap()["task"] |
| 3044 | .as_str() |
| 3045 | .unwrap() |
| 3046 | .to_string(); |
| 3047 | assert!(!task.contains("partial review"), "{task}"); |
| 3048 | } |
| 3049 | |
| 3050 | #[test] |
| 3051 | fn review_usage_aggregates_every_billable_counter() { |
| 3052 | let mut total = Usage::default(); |
| 3053 | let mut first = Usage { |
| 3054 | input_tokens: 10, |
| 3055 | output_tokens: 3, |
| 3056 | prompt_cache_hit_tokens: Some(2), |
| 3057 | reasoning_tokens: Some(4), |
| 3058 | input_audio_tokens: Some(3), |
| 3059 | output_audio_tokens: Some(1), |
| 3060 | ..Default::default() |
| 3061 | }; |
| 3062 | first.server_tool_use = Some(codewhale_models::ServerToolUsage { |
| 3063 | code_execution_requests: Some(1), |
| 3064 | tool_search_requests: None, |
| 3065 | ..Default::default() |
| 3066 | }); |
| 3067 | let second = Usage { |
| 3068 | input_tokens: 20, |
| 3069 | output_tokens: 5, |
| 3070 | prompt_cache_hit_tokens: Some(7), |
| 3071 | reasoning_tokens: Some(6), |
| 3072 | input_audio_tokens: Some(4), |
| 3073 | output_audio_tokens: Some(1), |
| 3074 | server_tool_use: Some(codewhale_models::ServerToolUsage { |
| 3075 | code_execution_requests: Some(2), |
| 3076 | tool_search_requests: Some(3), |
| 3077 | ..Default::default() |
| 3078 | }), |
| 3079 | ..Default::default() |
| 3080 | }; |
| 3081 | add_review_usage(&mut total, &first); |
| 3082 | add_review_usage(&mut total, &second); |
| 3083 | assert_eq!(total.input_tokens, 30); |
| 3084 | assert_eq!(total.output_tokens, 8); |
| 3085 | assert_eq!(total.prompt_cache_hit_tokens, Some(9)); |
| 3086 | assert_eq!(total.reasoning_tokens, Some(10)); |
| 3087 | assert_eq!(total.input_audio_tokens, Some(7)); |
| 3088 | assert_eq!(total.output_audio_tokens, Some(2)); |
| 3089 | assert_eq!(total.request_usages, vec![first, second]); |
| 3090 | assert_eq!( |
| 3091 | total.server_tool_use.unwrap().code_execution_requests, |
| 3092 | Some(3) |
| 3093 | ); |
| 3094 | } |
| 3095 | |
| 3096 | #[test] |
| 3097 | fn additional_review_passes_require_human_approval() { |
| 3098 | let tool = ReviewTool::new(None, "unused".to_string()); |
| 3099 | assert_eq!( |
| 3100 | tool.approval_requirement_for(&json!({"target":"diff"})), |
| 3101 | ApprovalRequirement::Auto |
| 3102 | ); |
| 3103 | assert_eq!( |
| 3104 | tool.approval_requirement_for( |
| 3105 | &json!({"target":"https://github.com/a/b/pull/1","max_passes":2}) |
| 3106 | ), |
| 3107 | ApprovalRequirement::Required |
| 3108 | ); |
| 3109 | assert_eq!( |
| 3110 | tool.approval_requirement_for(&json!({"target":"diff","max_passes":"invalid"})), |
| 3111 | ApprovalRequirement::Required |
| 3112 | ); |
| 3113 | } |
| 3114 | |
| 3115 | #[test] |
| 3116 | fn malformed_second_pass_and_drift_return_all_prior_usage_without_coverage() { |
| 3117 | let first = pr_patch("a.txt", "alpha"); |
| 3118 | let second = pr_patch("b.txt", "bravo"); |
| 3119 | let diff = format!("{first}{second}"); |
| 3120 | let plan = plan_pr_review( |
| 3121 | &diff, |
| 3122 | &pr_view(2), |
| 3123 | first.chars().count().max(second.chars().count()), |
| 3124 | 2, |
| 3125 | ) |
| 3126 | .unwrap(); |
| 3127 | let route = crate::cost_status::EffectiveRouteEnvelope::capture( |
| 3128 | None, |
| 3129 | codewhale_config::ProviderKind::Custom, |
| 3130 | "test", |
| 3131 | "test-model", |
| 3132 | None, |
| 3133 | chrono::Utc::now(), |
| 3134 | ); |
| 3135 | let mut usage = Usage::default(); |
| 3136 | for input_tokens in [11, 13] { |
| 3137 | add_review_usage( |
| 3138 | &mut usage, |
| 3139 | &Usage { |
| 3140 | input_tokens, |
| 3141 | output_tokens: 2, |
| 3142 | ..Default::default() |
| 3143 | }, |
| 3144 | ); |
| 3145 | } |
| 3146 | |
| 3147 | let mut malformed = PrReviewAccumulator::new(&plan); |
| 3148 | malformed |
| 3149 | .accept(&plan.passes[0], clean_pass("first")) |
| 3150 | .unwrap(); |
| 3151 | let error = malformed.accept(&plan.passes[1], "{}".into()).unwrap_err(); |
| 3152 | let result = review_error_with_usage(&route, &usage, &[], error.to_string()); |
| 3153 | assert!(!result.success); |
| 3154 | let metadata = result.metadata.unwrap(); |
| 3155 | assert_eq!(metadata["input_tokens"], 24); |
| 3156 | assert_eq!(metadata["output_tokens"], 4); |
| 3157 | assert_eq!( |
| 3158 | crate::cost_status::child_usage_from_metadata(&metadata), |
| 3159 | Some(usage.clone()) |
| 3160 | ); |
| 3161 | assert_eq!(usage.request_usages.len(), 2); |
| 3162 | assert!(metadata.get("review_coverage").is_none()); |
| 3163 | |
| 3164 | let mut drift = PrReviewAccumulator::new(&plan); |
| 3165 | drift.accept(&plan.passes[0], clean_pass("first")).unwrap(); |
| 3166 | drift.accept(&plan.passes[1], clean_pass("second")).unwrap(); |
| 3167 | let error = drift.finish(&(diff + "drift")).unwrap_err(); |
| 3168 | let result = review_error_with_usage(&route, &usage, &[], error.to_string()); |
| 3169 | assert!(!result.success); |
| 3170 | assert_eq!(result.metadata.unwrap()["input_tokens"], 24); |
| 3171 | } |
| 3172 | |
| 3173 | #[tokio::test] |
| 3174 | async fn missing_review_client_uses_codewhale_provider_neutral_language() { |
| 3175 | let tool = ReviewTool::new(None, "unused".to_string()); |
| 3176 | let context = ToolContext::new(PathBuf::from(".")); |
| 3177 | |
| 3178 | let error = tool |
| 3179 | .execute(json!({}), &context) |
| 3180 | .await |
| 3181 | .expect_err("review requires a configured model client") |
| 3182 | .to_string(); |
| 3183 | |
| 3184 | assert_eq!( |
| 3185 | error, |
| 3186 | "Failed to locate tool: Review tool requires an active Codewhale model client" |
| 3187 | ); |
| 3188 | assert!(!error.contains("DeepSeek")); |
| 3189 | } |
| 3190 | |
| 3191 | fn fixture_git(workspace: &Path, args: &[&str]) -> std::process::Output { |
| 3192 | let mut command = codewhale_dependencies::Git::command().expect("git test dependency"); |
| 3193 | let output = command |
| 3194 | .args(args) |
| 3195 | .current_dir(workspace) |
| 3196 | .output() |
| 3197 | .expect("run git fixture command"); |
| 3198 | assert!( |
| 3199 | output.status.success(), |
| 3200 | "git {} failed: {}", |
| 3201 | args.join(" "), |
| 3202 | String::from_utf8_lossy(&output.stderr) |
| 3203 | ); |
| 3204 | output |
| 3205 | } |
| 3206 | |
| 3207 | #[tokio::test] |
| 3208 | async fn staged_diff_with_base_compares_merge_base_to_index() { |
| 3209 | let repo = tempfile::TempDir::new().expect("temp git repository"); |
| 3210 | fixture_git(repo.path(), &["init"]); |
| 3211 | fixture_git(repo.path(), &["config", "user.name", "Codewhale Test"]); |
| 3212 | fixture_git( |
| 3213 | repo.path(), |
| 3214 | &["config", "user.email", "codewhale-test@example.invalid"], |
| 3215 | ); |
| 3216 | |
| 3217 | let tracked = repo.path().join("tracked.txt"); |
| 3218 | fs::write(&tracked, "base\n").expect("write base fixture"); |
| 3219 | fixture_git(repo.path(), &["add", "tracked.txt"]); |
| 3220 | fixture_git(repo.path(), &["commit", "-m", "base"]); |
| 3221 | let base = |
| 3222 | String::from_utf8_lossy(&fixture_git(repo.path(), &["rev-parse", "HEAD"]).stdout) |
| 3223 | .trim() |
| 3224 | .to_string(); |
| 3225 | |
| 3226 | fs::write(&tracked, "base\ncommitted\n").expect("write committed fixture"); |
| 3227 | fixture_git(repo.path(), &["add", "tracked.txt"]); |
| 3228 | fixture_git(repo.path(), &["commit", "-m", "branch change"]); |
| 3229 | fs::write(&tracked, "base\ncommitted\nstaged\n").expect("write staged fixture"); |
| 3230 | fixture_git(repo.path(), &["add", "tracked.txt"]); |
| 3231 | fs::write(&tracked, "base\ncommitted\nstaged\nunstaged\n").expect("write unstaged fixture"); |
| 3232 | |
| 3233 | let diff = resolve_diff_target(repo.path(), true, Some(&base)) |
| 3234 | .await |
| 3235 | .expect("staged review diff from base"); |
| 3236 | assert!(diff.contains("+committed"), "{diff}"); |
| 3237 | assert!(diff.contains("+staged"), "{diff}"); |
| 3238 | assert!(!diff.contains("unstaged"), "{diff}"); |
| 3239 | } |
| 3240 | |
| 3241 | #[test] |
| 3242 | fn binary_coverage_limit_is_part_of_the_returned_review_summary() { |
| 3243 | let mut review = ReviewOutput::parse(r#"{"summary":"Review findings"}"#); |
| 3244 | review.note_binary_coverage("diff --git a/image b/image\nGIT binary patch\nliteral 4\n"); |
| 3245 | assert!(review.summary.contains("not semantically inspected")); |
| 3246 | let mut metadata_review = ReviewOutput::parse(r#"{"summary":"Review findings"}"#); |
| 3247 | metadata_review.note_binary_coverage( |
| 3248 | "diff --git a/image b/image\nBinary files a/image and b/image differ\n", |
| 3249 | ); |
| 3250 | assert!( |
| 3251 | metadata_review |
| 3252 | .summary |
| 3253 | .contains("not semantically inspected") |
| 3254 | ); |
| 3255 | let mut text_review = ReviewOutput::parse(r#"{"summary":"Text review"}"#); |
| 3256 | text_review.note_binary_coverage("diff --git a/a b/a\n@@ -0,0 +1 @@\n+text\n"); |
| 3257 | assert_eq!(text_review.summary, "Text review"); |
| 3258 | } |
| 3259 | |
| 3260 | #[test] |
| 3261 | fn parses_pr_url() { |
| 3262 | let pr = |
| 3263 | parse_pr_url("https://github.com/deepseek-ai/deepseek-cli/pull/123").expect("parse pr"); |
| 3264 | assert_eq!(pr.owner, "deepseek-ai"); |
| 3265 | assert_eq!(pr.repo, "deepseek-cli"); |
| 3266 | assert_eq!(pr.number, "123"); |
| 3267 | } |
| 3268 | |
| 3269 | #[test] |
| 3270 | fn ignores_non_pr_url() { |
| 3271 | assert!(parse_pr_url("https://github.com/deepseek-ai/deepseek-cli").is_none()); |
| 3272 | assert!(parse_pr_url("not-a-url").is_none()); |
| 3273 | } |
| 3274 | |
| 3275 | #[test] |
| 3276 | fn extracts_json_block() { |
| 3277 | let raw = "prefix {\"summary\":\"ok\"} suffix"; |
| 3278 | let block = extract_json_block(raw).expect("block"); |
| 3279 | assert!(block.contains("\"summary\"")); |
| 3280 | } |
| 3281 | |
| 3282 | #[test] |
| 3283 | fn review_output_parses_structured_json() { |
| 3284 | let raw = r#"{ |
| 3285 | "summary": " Looks good overall ", |
| 3286 | "issues": [{ |
| 3287 | "severity": "high", |
| 3288 | "title": " Missing test ", |
| 3289 | "description": " Add coverage ", |
| 3290 | "path": " src/lib.rs ", |
| 3291 | "line": 42 |
| 3292 | }], |
| 3293 | "suggestions": [{ |
| 3294 | "path": "", |
| 3295 | "line": 7, |
| 3296 | "suggestion": " Keep the helper small " |
| 3297 | }], |
| 3298 | "overall_assessment": " Safe after test " |
| 3299 | }"#; |
| 3300 | |
| 3301 | let output = ReviewOutput::parse(raw); |
| 3302 | |
| 3303 | assert_eq!(output.summary, "Looks good overall"); |
| 3304 | assert_eq!(output.issues.len(), 1); |
| 3305 | assert_eq!(output.issues[0].severity, "blocker"); |
| 3306 | assert_eq!(output.issues[0].title, "Missing test"); |
| 3307 | assert_eq!(output.issues[0].path.as_deref(), Some("src/lib.rs")); |
| 3308 | assert_eq!(output.issues[0].line, Some(42)); |
| 3309 | assert_eq!(output.suggestions.len(), 1); |
| 3310 | assert_eq!(output.suggestions[0].path, None); |
| 3311 | assert_eq!(output.suggestions[0].line, Some(7)); |
| 3312 | assert_eq!(output.suggestions[0].suggestion, "Keep the helper small"); |
| 3313 | assert_eq!(output.overall_assessment, "Safe after test"); |
| 3314 | } |
| 3315 | |
| 3316 | #[test] |
| 3317 | fn review_output_parses_double_encoded_json_string() { |
| 3318 | let inner = serde_json::json!({ |
| 3319 | "summary": "structured", |
| 3320 | "issues": [{ |
| 3321 | "severity": "warning", |
| 3322 | "title": "Risk", |
| 3323 | "description": "The parser should not fall back to a raw JSON string.", |
| 3324 | "path": "src/main.rs", |
| 3325 | "line": 3 |
| 3326 | }], |
| 3327 | "suggestions": [], |
| 3328 | "overall_assessment": "usable" |
| 3329 | }) |
| 3330 | .to_string(); |
| 3331 | let double_encoded = serde_json::to_string(&inner).expect("encode string"); |
| 3332 | |
| 3333 | let output = ReviewOutput::parse(&double_encoded); |
| 3334 | |
| 3335 | assert_eq!(output.summary, "structured"); |
| 3336 | assert_eq!(output.issues.len(), 1); |
| 3337 | assert_eq!(output.issues[0].severity, "concern"); |
| 3338 | assert_eq!(output.issues[0].path.as_deref(), Some("src/main.rs")); |
| 3339 | assert_eq!(output.overall_assessment, "usable"); |
| 3340 | } |
| 3341 | |
| 3342 | #[test] |
| 3343 | fn single_review_refuses_blank_or_contractless_replies() { |
| 3344 | for raw in ["", " \n", "{}", r#"{"verdict":"ok"}"#, "```json\n{}\n```"] { |
| 3345 | assert!( |
| 3346 | accept_single_review(raw).is_err(), |
| 3347 | "{raw:?} must not become a clean review" |
| 3348 | ); |
| 3349 | } |
| 3350 | let prose = accept_single_review("Looks good; no findings.").expect("prose review"); |
| 3351 | assert_eq!(prose.summary, "Looks good; no findings."); |
| 3352 | let structured = accept_single_review( |
| 3353 | r#"{"summary":"One risk","issues":[],"suggestions":[],"overall_assessment":"ok"}"#, |
| 3354 | ) |
| 3355 | .expect("structured review"); |
| 3356 | assert_eq!(structured.summary, "One risk"); |
| 3357 | } |
| 3358 | |
| 3359 | #[test] |
| 3360 | fn review_output_fallback_keeps_summary() { |
| 3361 | let output = ReviewOutput::parse("Not JSON"); |
| 3362 | assert!(!output.summary.is_empty()); |
| 3363 | assert!(output.issues.is_empty()); |
| 3364 | } |
| 3365 | |
| 3366 | #[test] |
| 3367 | fn review_usage_metadata_reports_child_tokens_for_cost_accrual() { |
| 3368 | let route = crate::cost_status::EffectiveRouteEnvelope::capture( |
| 3369 | None, |
| 3370 | codewhale_config::ProviderKind::Deepseek, |
| 3371 | "deepseek", |
| 3372 | "deepseek-v4-flash", |
| 3373 | Some("https://api.deepseek.com/v1"), |
| 3374 | chrono::DateTime::<chrono::Utc>::from_timestamp(0, 0).expect("epoch"), |
| 3375 | ); |
| 3376 | let metadata = review_usage_metadata( |
| 3377 | &route, |
| 3378 | &Usage { |
| 3379 | input_tokens: 123, |
| 3380 | output_tokens: 45, |
| 3381 | prompt_cache_hit_tokens: Some(100), |
| 3382 | prompt_cache_miss_tokens: Some(23), |
| 3383 | reasoning_tokens: Some(7), |
| 3384 | ..Default::default() |
| 3385 | }, |
| 3386 | &[], |
| 3387 | ); |
| 3388 | |
| 3389 | assert_eq!(metadata["tool"], "review"); |
| 3390 | assert_eq!(metadata["child_model"], "deepseek-v4-flash"); |
| 3391 | assert_eq!(metadata["child_input_tokens"], 123); |
| 3392 | assert_eq!(metadata["child_output_tokens"], 45); |
| 3393 | assert_eq!(metadata["child_prompt_cache_hit_tokens"], 100); |
| 3394 | assert_eq!(metadata["child_prompt_cache_miss_tokens"], 23); |
| 3395 | assert_eq!(metadata["child_reasoning_tokens"], 7); |
| 3396 | } |
| 3397 | |
| 3398 | #[test] |
| 3399 | fn pre_push_diff_review_receipt_includes_fingerprint_and_risk() { |
| 3400 | let diff = "diff --git a/src/lib.rs b/src/lib.rs\n+let risky = true;\n"; |
| 3401 | let output = ReviewOutput { |
| 3402 | summary: "Found one issue".to_string(), |
| 3403 | issues: vec![ReviewIssue { |
| 3404 | severity: "concern".to_string(), |
| 3405 | title: "Missing test".to_string(), |
| 3406 | description: "Add coverage".to_string(), |
| 3407 | path: Some("src/lib.rs".to_string()), |
| 3408 | line: Some(12), |
| 3409 | ..Default::default() |
| 3410 | }], |
| 3411 | suggestions: vec![ReviewSuggestion { |
| 3412 | path: Some("src/lib.rs".to_string()), |
| 3413 | line: Some(12), |
| 3414 | start_line: None, |
| 3415 | end_line: None, |
| 3416 | suggestion: "Add a regression test".to_string(), |
| 3417 | replacement: None, |
| 3418 | }], |
| 3419 | overall_assessment: "Needs a test".to_string(), |
| 3420 | ..Default::default() |
| 3421 | }; |
| 3422 | |
| 3423 | let receipt = build_review_receipt( |
| 3424 | "working-tree", |
| 3425 | diff, |
| 3426 | "deepseek", |
| 3427 | "deepseek-v4-pro", |
| 3428 | &output, |
| 3429 | "review body", |
| 3430 | vec![ReviewReceiptCheck { |
| 3431 | name: "cargo test -p codewhale-tui".to_string(), |
| 3432 | status: "passed".to_string(), |
| 3433 | }], |
| 3434 | ); |
| 3435 | |
| 3436 | assert_eq!(receipt.schema_version, REVIEW_RECEIPT_SCHEMA_VERSION); |
| 3437 | assert_eq!(receipt.mode, "pre_push_review"); |
| 3438 | assert_eq!(receipt.target, "working-tree"); |
| 3439 | assert_eq!(receipt.diff_fingerprint, diff_fingerprint(diff)); |
| 3440 | assert_eq!(receipt.diff_lines, 2); |
| 3441 | assert_eq!(receipt.provider, "deepseek"); |
| 3442 | assert_eq!(receipt.model, "deepseek-v4-pro"); |
| 3443 | assert_eq!(receipt.checks_run.len(), 1); |
| 3444 | assert_eq!(receipt.findings.issue_count, 1); |
| 3445 | assert_eq!(receipt.findings.suggestion_count, 1); |
| 3446 | assert_eq!(receipt.findings.highest_severity, "concern"); |
| 3447 | assert!(receipt.unresolved_risk.unresolved); |
| 3448 | assert_eq!(receipt.unresolved_risk.level, "concern"); |
| 3449 | assert_eq!( |
| 3450 | receipt.review_content_sha256, |
| 3451 | sha256_hex("review body".as_bytes()) |
| 3452 | ); |
| 3453 | } |
| 3454 | |
| 3455 | #[test] |
| 3456 | fn review_receipt_records_committable_suggestion_provenance() { |
| 3457 | // Built from a slice, not one string literal: a `\` continuation |
| 3458 | // strips the leading space that marks a context line. |
| 3459 | let diff = [ |
| 3460 | "diff --git a/src/lib.rs b/src/lib.rs", |
| 3461 | "--- a/src/lib.rs", |
| 3462 | "+++ b/src/lib.rs", |
| 3463 | "@@ -10,2 +10,3 @@ fn head() {", |
| 3464 | " let a = 1;", |
| 3465 | "+let b = a.unwrap();", |
| 3466 | " let c = 2;", |
| 3467 | "", |
| 3468 | ] |
| 3469 | .join("\n"); |
| 3470 | let output = ReviewOutput { |
| 3471 | summary: "One fix, one judgement call, one miss".to_string(), |
| 3472 | issues: Vec::new(), |
| 3473 | suggestions: vec![ |
| 3474 | // Valid anchor, explicit in-hunk span, literal replacement: |
| 3475 | // the only shape that may become a committable block. |
| 3476 | ReviewSuggestion { |
| 3477 | path: Some("src/lib.rs".to_string()), |
| 3478 | line: Some(12), |
| 3479 | start_line: Some(11), |
| 3480 | end_line: Some(12), |
| 3481 | suggestion: "Use the checked variant".to_string(), |
| 3482 | replacement: Some("let b = a.unwrap_or_default();\nlet c = 2;".to_string()), |
| 3483 | }, |
| 3484 | // Valid anchor, no literal replacement: degrades to prose. |
| 3485 | ReviewSuggestion { |
| 3486 | path: Some("src/lib.rs".to_string()), |
| 3487 | line: Some(11), |
| 3488 | start_line: None, |
| 3489 | end_line: None, |
| 3490 | suggestion: "Add a test".to_string(), |
| 3491 | replacement: None, |
| 3492 | }, |
| 3493 | // Line 25 sits between hunks: unanchorable. |
| 3494 | ReviewSuggestion { |
| 3495 | path: Some("src/lib.rs".to_string()), |
| 3496 | line: Some(25), |
| 3497 | start_line: None, |
| 3498 | end_line: None, |
| 3499 | suggestion: "Wrong line".to_string(), |
| 3500 | replacement: Some("x = 1;".to_string()), |
| 3501 | }, |
| 3502 | // No position at all: summary-body only, counted nowhere here. |
| 3503 | ReviewSuggestion { |
| 3504 | path: None, |
| 3505 | line: None, |
| 3506 | start_line: None, |
| 3507 | end_line: None, |
| 3508 | suggestion: "Consider renaming".to_string(), |
| 3509 | replacement: None, |
| 3510 | }, |
| 3511 | ], |
| 3512 | overall_assessment: "Fix the unwrap".to_string(), |
| 3513 | ..Default::default() |
| 3514 | }; |
| 3515 | |
| 3516 | let receipt = build_review_receipt( |
| 3517 | "working-tree", |
| 3518 | &diff, |
| 3519 | "deepseek", |
| 3520 | "deepseek-v4-pro", |
| 3521 | &output, |
| 3522 | "review body", |
| 3523 | Vec::new(), |
| 3524 | ); |
| 3525 | |
| 3526 | let provenance = &receipt.findings.suggestions; |
| 3527 | assert_eq!(provenance.committable_count, 1); |
| 3528 | assert_eq!( |
| 3529 | provenance.committable, |
| 3530 | vec![ReviewReceiptSuggestion { |
| 3531 | path: "src/lib.rs".to_string(), |
| 3532 | start_line: 11, |
| 3533 | end_line: 12, |
| 3534 | }] |
| 3535 | ); |
| 3536 | assert_eq!(provenance.degraded_to_prose, 1); |
| 3537 | assert_eq!(provenance.dropped_unanchorable, 1); |
| 3538 | assert_eq!(receipt.findings.suggestion_count, 4); |
| 3539 | |
| 3540 | // Provenance records anchors, never code: the replacement text must |
| 3541 | // not leak into the receipt. |
| 3542 | let serialized = serde_json::to_string(&receipt).expect("serialize receipt"); |
| 3543 | assert!(!serialized.contains("unwrap_or_default"), "{serialized}"); |
| 3544 | assert!(!serialized.contains("x = 1;"), "{serialized}"); |
| 3545 | } |
| 3546 | |
| 3547 | #[test] |
| 3548 | fn review_receipt_without_suggestion_provenance_still_decodes() { |
| 3549 | // Receipts written before the provenance field existed are schema v1; |
| 3550 | // the field is additive and serde-defaulted, so they must keep |
| 3551 | // decoding and the schema version must not move. |
| 3552 | let output = ReviewOutput::parse("Looks good"); |
| 3553 | let receipt = build_review_receipt( |
| 3554 | "working-tree", |
| 3555 | "diff --git a/a b/a\n", |
| 3556 | "deepseek", |
| 3557 | "deepseek-v4-flash", |
| 3558 | &output, |
| 3559 | "Looks good", |
| 3560 | Vec::new(), |
| 3561 | ); |
| 3562 | let mut value = serde_json::to_value(&receipt).expect("serialize"); |
| 3563 | value |
| 3564 | .get_mut("findings") |
| 3565 | .expect("findings") |
| 3566 | .as_object_mut() |
| 3567 | .expect("findings object") |
| 3568 | .remove("suggestions"); |
| 3569 | let legacy: ReviewReceipt = serde_json::from_value(value).expect("legacy receipt decodes"); |
| 3570 | assert_eq!(legacy.schema_version, REVIEW_RECEIPT_SCHEMA_VERSION); |
| 3571 | assert_eq!( |
| 3572 | legacy.findings.suggestions, |
| 3573 | ReviewReceiptSuggestions::default() |
| 3574 | ); |
| 3575 | } |
| 3576 | |
| 3577 | #[test] |
| 3578 | fn write_review_receipt_accepts_override_path() { |
| 3579 | let dir = tempfile::tempdir().expect("tempdir"); |
| 3580 | let path = dir.path().join("nested").join("receipt.json"); |
| 3581 | let output = ReviewOutput::parse("Looks good"); |
| 3582 | let receipt = build_review_receipt( |
| 3583 | "staged", |
| 3584 | "diff --git a/a b/a\n", |
| 3585 | "deepseek", |
| 3586 | "deepseek-v4-flash", |
| 3587 | &output, |
| 3588 | "Looks good", |
| 3589 | Vec::new(), |
| 3590 | ); |
| 3591 | |
| 3592 | let written = write_review_receipt(&receipt, Some(&path)).expect("write receipt"); |
| 3593 | |
| 3594 | assert_eq!(written, path); |
| 3595 | let raw = fs::read_to_string(&written).expect("read receipt"); |
| 3596 | let decoded: ReviewReceipt = serde_json::from_str(&raw).expect("decode receipt"); |
| 3597 | assert_eq!(decoded.diff_fingerprint, receipt.diff_fingerprint); |
| 3598 | assert_eq!(decoded.unresolved_risk.level, "none"); |
| 3599 | } |
| 3600 | |
| 3601 | #[test] |
| 3602 | fn review_receipt_validation_passes_matching_clean_receipt() { |
| 3603 | let diff = "diff --git a/a b/a\n+ok\n"; |
| 3604 | let output = ReviewOutput::parse("Looks good"); |
| 3605 | let receipt = build_review_receipt( |
| 3606 | "working-tree", |
| 3607 | diff, |
| 3608 | "deepseek", |
| 3609 | "deepseek-v4-flash", |
| 3610 | &output, |
| 3611 | "Looks good", |
| 3612 | vec![ReviewReceiptCheck { |
| 3613 | name: "cargo test".to_string(), |
| 3614 | status: "passed".to_string(), |
| 3615 | }], |
| 3616 | ); |
| 3617 | |
| 3618 | let validation = validate_review_receipt_for_diff(diff, &receipt, None); |
| 3619 | |
| 3620 | assert!(validation.passed); |
| 3621 | assert_eq!(validation.diff_fingerprint, diff_fingerprint(diff)); |
| 3622 | assert_eq!( |
| 3623 | validation.reason, |
| 3624 | "receipt matches current diff and has no unresolved risk" |
| 3625 | ); |
| 3626 | } |
| 3627 | |
| 3628 | #[test] |
| 3629 | fn review_receipt_validation_rejects_changed_diff() { |
| 3630 | let output = ReviewOutput::parse("Looks good"); |
| 3631 | let receipt = build_review_receipt( |
| 3632 | "working-tree", |
| 3633 | "diff --git a/a b/a\n+old\n", |
| 3634 | "deepseek", |
| 3635 | "deepseek-v4-flash", |
| 3636 | &output, |
| 3637 | "Looks good", |
| 3638 | Vec::new(), |
| 3639 | ); |
| 3640 | |
| 3641 | let validation = |
| 3642 | validate_review_receipt_for_diff("diff --git a/a b/a\n+new\n", &receipt, None); |
| 3643 | |
| 3644 | assert!(!validation.passed); |
| 3645 | assert_eq!( |
| 3646 | validation.reason, |
| 3647 | "current diff fingerprint does not match receipt" |
| 3648 | ); |
| 3649 | } |
| 3650 | |
| 3651 | #[test] |
| 3652 | fn review_receipt_validation_rejects_unresolved_risk() { |
| 3653 | let diff = "diff --git a/a b/a\n+risk\n"; |
| 3654 | let output = ReviewOutput { |
| 3655 | summary: "Risk found".to_string(), |
| 3656 | issues: vec![ReviewIssue { |
| 3657 | severity: "blocker".to_string(), |
| 3658 | title: "Unsafe change".to_string(), |
| 3659 | description: "Needs work".to_string(), |
| 3660 | path: Some("a".to_string()), |
| 3661 | line: Some(1), |
| 3662 | ..Default::default() |
| 3663 | }], |
| 3664 | suggestions: Vec::new(), |
| 3665 | overall_assessment: String::new(), |
| 3666 | ..Default::default() |
| 3667 | }; |
| 3668 | let receipt = build_review_receipt( |
| 3669 | "working-tree", |
| 3670 | diff, |
| 3671 | "deepseek", |
| 3672 | "deepseek-v4-flash", |
| 3673 | &output, |
| 3674 | "Risk found", |
| 3675 | Vec::new(), |
| 3676 | ); |
| 3677 | |
| 3678 | let validation = validate_review_receipt_for_diff(diff, &receipt, None); |
| 3679 | |
| 3680 | assert!(!validation.passed); |
| 3681 | assert_eq!( |
| 3682 | validation.unresolved_risk.as_ref().unwrap().level, |
| 3683 | "blocker" |
| 3684 | ); |
| 3685 | assert!(validation.reason.contains("unresolved review issue")); |
| 3686 | } |
| 3687 | |
| 3688 | #[test] |
| 3689 | fn review_receipt_validation_rejects_failed_check() { |
| 3690 | let diff = "diff --git a/a b/a\n+ok\n"; |
| 3691 | let output = ReviewOutput::parse("Looks good"); |
| 3692 | let receipt = build_review_receipt( |
| 3693 | "working-tree", |
| 3694 | diff, |
| 3695 | "deepseek", |
| 3696 | "deepseek-v4-flash", |
| 3697 | &output, |
| 3698 | "Looks good", |
| 3699 | vec![ReviewReceiptCheck { |
| 3700 | name: "cargo test".to_string(), |
| 3701 | status: "failed".to_string(), |
| 3702 | }], |
| 3703 | ); |
| 3704 | |
| 3705 | let validation = validate_review_receipt_for_diff(diff, &receipt, None); |
| 3706 | |
| 3707 | assert!(!validation.passed); |
| 3708 | assert!( |
| 3709 | validation |
| 3710 | .reason |
| 3711 | .contains("review receipt check 'cargo test' did not pass") |
| 3712 | ); |
| 3713 | } |
| 3714 | |
| 3715 | #[test] |
| 3716 | fn review_receipt_validation_rejects_attached_not_run_check() { |
| 3717 | let diff = "diff --git a/a b/a\n+ok\n"; |
| 3718 | let output = ReviewOutput::parse("Looks good"); |
| 3719 | let receipt = build_review_receipt( |
| 3720 | "working-tree", |
| 3721 | diff, |
| 3722 | "deepseek", |
| 3723 | "deepseek-v4-flash", |
| 3724 | &output, |
| 3725 | "Looks good", |
| 3726 | vec![ReviewReceiptCheck { |
| 3727 | name: "cargo test".to_string(), |
| 3728 | status: "not_run".to_string(), |
| 3729 | }], |
| 3730 | ); |
| 3731 | |
| 3732 | let validation = validate_review_receipt_for_diff(diff, &receipt, None); |
| 3733 | |
| 3734 | assert!(!validation.passed); |
| 3735 | assert!( |
| 3736 | validation |
| 3737 | .reason |
| 3738 | .contains("review receipt check 'cargo test' did not pass: not_run") |
| 3739 | ); |
| 3740 | } |
| 3741 | |
| 3742 | #[test] |
| 3743 | fn bounded_review_effort_caps_reasoning_by_visible_text_reserve() { |
| 3744 | use crate::reasoning_preference::ReasoningEffort; |
| 3745 | |
| 3746 | // Half the allowance must survive as text: reasoning capped to Low. |
| 3747 | assert_eq!( |
| 3748 | bounded_review_reasoning_effort(ReasoningEffort::Max, 50, 65_536), |
| 3749 | ReasoningEffort::Low |
| 3750 | ); |
| 3751 | // A quarter reserved: capped to Medium. |
| 3752 | assert_eq!( |
| 3753 | bounded_review_reasoning_effort(ReasoningEffort::Max, 25, 65_536), |
| 3754 | ReasoningEffort::Medium |
| 3755 | ); |
| 3756 | // Nothing reserved (non-reasoning model): request untouched. |
| 3757 | assert_eq!( |
| 3758 | bounded_review_reasoning_effort(ReasoningEffort::Max, 0, 65_536), |
| 3759 | ReasoningEffort::Max |
| 3760 | ); |
| 3761 | // The cap never raises a lower request. |
| 3762 | assert_eq!( |
| 3763 | bounded_review_reasoning_effort(ReasoningEffort::Low, 50, 65_536), |
| 3764 | ReasoningEffort::Low |
| 3765 | ); |
| 3766 | assert_eq!( |
| 3767 | bounded_review_reasoning_effort(ReasoningEffort::Off, 50, 65_536), |
| 3768 | ReasoningEffort::Off |
| 3769 | ); |
| 3770 | // Unresolved Auto must not survive as unbounded either. |
| 3771 | assert_eq!( |
| 3772 | bounded_review_reasoning_effort(ReasoningEffort::Auto, 50, 65_536), |
| 3773 | ReasoningEffort::Low |
| 3774 | ); |
| 3775 | } |
| 3776 | |
| 3777 | #[test] |
| 3778 | fn read_review_receipt_refuses_oversized_file() { |
| 3779 | let dir = tempfile::tempdir().expect("tempdir"); |
| 3780 | let path = dir.path().join("oversized.json"); |
| 3781 | let payload = vec![b' '; (MAX_REVIEW_RECEIPT_BYTES as usize) + 16]; |
| 3782 | fs::write(&path, payload).expect("write oversized receipt"); |
| 3783 | let error = read_review_receipt(&path).expect_err("oversized receipt must fail"); |
| 3784 | assert!( |
| 3785 | error.to_string().contains("exceeds the"), |
| 3786 | "unexpected error: {error}" |
| 3787 | ); |
| 3788 | } |
| 3789 | } |
| 3790 |