返回 CodeWhale
review_triage.rs
根目录 / crates / engine / src / tools / review_triage.rs
1 use serde::{Deserialize, Serialize};
2
3 use super::review_core::ReviewToolBudget;
4
5 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
6 #[serde(rename_all = "lowercase")]
7 pub enum ReviewRisk {
8 Low,
9 Medium,
10 High,
11 }
12
13 impl ReviewRisk {
14 #[must_use]
15 pub fn as_str(self) -> &'static str {
16 match self {
17 Self::Low => "low",
18 Self::Medium => "medium",
19 Self::High => "high",
20 }
21 }
22 }
23
24 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
25 pub struct ReviewTriage {
26 pub risk: ReviewRisk,
27 /// Why this tier was chosen, in the reader's words. Every entry names the
28 /// signal that raised it, so a receipt can be audited later.
29 pub reasons: Vec<String>,
30 pub changed_files: usize,
31 pub changed_lines: usize,
32 pub touches_tests: bool,
33 }
34
35 #[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
36 pub struct ReviewBudget {
37 pub risk: ReviewRisk,
38 pub max_steps: u32,
39 pub max_tool_calls: u32,
40 pub max_output_tokens: u32,
41 /// `Some(0.0)` means a cap was requested but no price is known, which makes
42 /// it unenforceable; that is reported rather than treated as unlimited.
43 pub money_cap_usd: Option<f64>,
44 pub money_limit_supported: bool,
45 }
46
47 const HIGH_RISK_PATH: &[(&str, &str)] = &[
48 ("auth", "authentication or authorization code"),
49 ("billing", "billing or payment code"),
50 ("payment", "billing or payment code"),
51 ("stripe", "billing or payment code"),
52 ("migration", "a database migration"),
53 ("crypto", "cryptography or key handling"),
54 ("secret", "secret handling"),
55 ("permission", "permission or policy code"),
56 ("policy", "permission or policy code"),
57 ("sandbox", "a sandbox or isolation boundary"),
58 ("concurren", "concurrency or locking"),
59 ("lock", "concurrency or locking"),
60 ("delete", "a deletion or destructive path"),
61 ("schema", "a persisted schema"),
62 ];
63
64 const MEDIUM_RISK_PATH: &[(&str, &str)] = &[
65 ("api", "a public or internal API surface"),
66 ("route", "a request route"),
67 ("server", "server behaviour"),
68 ("config", "configuration"),
69 ("db", "database access"),
70 ("store", "persistence"),
71 ("proto", "a protocol definition"),
72 ("contract", "a published contract"),
73 ];
74
75 const TEST_PATH: &[&str] = &[
76 "/test/",
77 "/tests/",
78 "_test.",
79 ".test.",
80 "/spec/",
81 "/__tests__/",
82 ];
83
84 fn path_is_test(path: &str) -> bool {
85 let lower = path.to_ascii_lowercase();
86 TEST_PATH.iter().any(|marker| lower.contains(marker))
87 }
88
89 /// Triage reads only the diff's paths and size. It is deliberately cheap: no
90 /// model call, no repository walk, and no claim about whether the change is
91 /// correct. It exists to decide how much review to buy, so it must be
92 /// explainable from the diff alone.
93 #[must_use]
94 pub fn triage_review(diff: &str) -> ReviewTriage {
95 let mut paths: Vec<String> = Vec::new();
96 let mut added = 0usize;
97 let mut removed = 0usize;
98 for line in diff.lines() {
99 let header = line
100 .strip_prefix("+++ ")
101 .map(|rest| rest.trim().trim_start_matches("b/"))
102 .or_else(|| {
103 line.strip_prefix("--- ")
104 .map(|rest| rest.trim().trim_start_matches("a/"))
105 });
106 if let Some(path) = header {
107 if path != "/dev/null" && !paths.iter().any(|seen| seen == path) {
108 paths.push(path.to_string());
109 }
110 continue;
111 }
112 if line.starts_with("+++") || line.starts_with("---") {
113 continue;
114 }
115 if line.starts_with('+') {
116 added += 1;
117 } else if line.starts_with('-') {
118 removed += 1;
119 }
120 }
121 let changed_files = paths.len();
122 let changed_lines = added + removed;
123 let touches_tests = paths.iter().any(|path| path_is_test(path));
124 let mut reasons = Vec::new();
125 let mut high = false;
126 let mut medium = false;
127 for (marker, reason) in HIGH_RISK_PATH {
128 if paths
129 .iter()
130 .any(|path| path.to_ascii_lowercase().contains(marker))
131 {
132 high = true;
133 if !reasons.iter().any(|seen| seen == reason) {
134 reasons.push((*reason).to_string());
135 }
136 }
137 }
138 for (marker, reason) in MEDIUM_RISK_PATH {
139 if paths
140 .iter()
141 .any(|path| path.to_ascii_lowercase().contains(marker))
142 {
143 medium = true;
144 if !reasons.iter().any(|seen| seen == reason) {
145 reasons.push((*reason).to_string());
146 }
147 }
148 }
149 if changed_lines >= 400 || changed_files > 20 {
150 high = true;
151 reasons.push(format!(
152 "a large change ({changed_files} files, {changed_lines} changed lines)"
153 ));
154 } else if changed_lines >= 80 || changed_files > 6 {
155 medium = true;
156 reasons.push(format!(
157 "a medium-size change ({changed_files} files, {changed_lines} changed lines)"
158 ));
159 }
160 let risk = if high {
161 ReviewRisk::High
162 } else if medium {
163 ReviewRisk::Medium
164 } else {
165 ReviewRisk::Low
166 };
167 if reasons.is_empty() {
168 reasons.push(format!(
169 "a small change ({changed_files} files, {changed_lines} changed lines) with no sensitive path"
170 ));
171 }
172 if touches_tests {
173 reasons.push("the change includes tests".to_string());
174 }
175 ReviewTriage {
176 risk,
177 reasons,
178 changed_files,
179 changed_lines,
180 touches_tests,
181 }
182 }
183
184 pub const REASONING_ROUTE_MIN_OUTPUT_TOKENS: u32 = 8_192;
185
186 /// The budget a tier buys. Low risk still gets a real review of the diff, just
187 /// without repository tools; high risk gets dependent tracing and room to
188 /// reproduce. Output is never tiered: every review may use the route's whole
189 /// output limit, so spend is bounded by skipping steps, not by truncation.
190 #[must_use]
191 pub fn budget_for(triage: &ReviewTriage, route_output_limit: u32) -> ReviewBudget {
192 let (max_steps, max_tool_calls) = match triage.risk {
193 ReviewRisk::Low => (1, 0),
194 ReviewRisk::Medium => (4, 6),
195 ReviewRisk::High => (6, 12),
196 };
197 ReviewBudget {
198 risk: triage.risk,
199 max_steps,
200 max_tool_calls,
201 max_output_tokens: route_output_limit,
202 money_cap_usd: None,
203 money_limit_supported: false,
204 }
205 }
206
207 impl ReviewBudget {
208 #[must_use]
209 pub fn tool_budget(self) -> ReviewToolBudget {
210 ReviewToolBudget {
211 max_steps: self.max_steps,
212 max_tool_calls: self.max_tool_calls,
213 max_tool_result_chars: 40_000,
214 }
215 }
216
217 /// Attach a per-review money cap. A cap without a price is not enforceable,
218 /// and saying so is the point: `money_limit_supported` stays false until a
219 /// rate is supplied, so a caller can never report a cap it did not apply.
220 #[must_use]
221 pub fn with_money_cap(mut self, cap_usd: Option<f64>, rates: Option<(f64, f64)>) -> Self {
222 let Some(cap) = cap_usd.filter(|cap| *cap > 0.0 && cap.is_finite()) else {
223 return self;
224 };
225 self.money_cap_usd = Some(cap);
226 self.money_limit_supported = rates.is_some_and(|(input, output)| {
227 input.is_finite() && output.is_finite() && input >= 0.0 && output >= 0.0
228 });
229 self
230 }
231 }
232
233 #[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
234 pub struct SpendRates {
235 pub input_usd_per_million: f64,
236 pub output_usd_per_million: f64,
237 }
238
239 impl SpendRates {
240 #[must_use]
241 pub fn cost_usd(self, usage: &codewhale_models::Usage) -> f64 {
242 let input = u64::from(usage.input_tokens)
243 + u64::from(usage.prompt_cache_hit_tokens.unwrap_or(0))
244 + u64::from(usage.prompt_cache_write_tokens.unwrap_or(0));
245 let output = u64::from(usage.output_tokens);
246 (input as f64 / 1_000_000.0) * self.input_usd_per_million
247 + (output as f64 / 1_000_000.0) * self.output_usd_per_million
248 }
249 }
250
251 /// Why a review stopped early. A stop is always reported with what was and was
252 /// not covered; it is never a silent truncation.
253 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
254 #[serde(rename_all = "snake_case")]
255 pub enum ReviewStop {
256 MoneyCap,
257 StepBudget,
258 ToolBudget,
259 OutputLimit,
260 ModelFailure,
261 }
262
263 impl ReviewStop {
264 #[must_use]
265 pub fn as_str(&self) -> &'static str {
266 match self {
267 Self::MoneyCap => "money_cap",
268 Self::StepBudget => "step_budget",
269 Self::ToolBudget => "tool_budget",
270 Self::OutputLimit => "output_limit",
271 Self::ModelFailure => "model_failure",
272 }
273 }
274 }
275
276 #[must_use]
277 pub fn partial_review_note(
278 stop: &ReviewStop,
279 triage: &ReviewTriage,
280 budget: &ReviewBudget,
281 ) -> String {
282 let what = match stop {
283 ReviewStop::MoneyCap => format!(
284 "the per-review money cap of ${:.4} was reached",
285 budget.money_cap_usd.unwrap_or(0.0)
286 ),
287 ReviewStop::StepBudget => format!(
288 "the {} model step(s) for a {} risk change were used",
289 budget.max_steps,
290 triage.risk.as_str()
291 ),
292 ReviewStop::ToolBudget => format!(
293 "the {} tool call(s) for a {} risk change were used",
294 budget.max_tool_calls,
295 triage.risk.as_str()
296 ),
297 ReviewStop::OutputLimit => "the model exhausted its output allowance".to_string(),
298 ReviewStop::ModelFailure => "the model call failed".to_string(),
299 };
300 format!(
301 "This is a named partial review: {what}. Findings below were produced before the stop; files and dependents the reviewer did not reach were not reviewed, and their absence is not evidence that they are correct."
302 )
303 }
304
305 #[cfg(test)]
306 mod tests {
307 use super::*;
308
309 fn diff_for(paths: &[&str]) -> String {
310 let mut out = String::new();
311 for path in paths {
312 out.push_str(&format!(
313 "diff --git a/{path} b/{path}\n--- a/{path}\n+++ b/{path}\n@@ -1,1 +1,2 @@\n context\n+added\n"
314 ));
315 }
316 out
317 }
318
319 #[test]
320 fn a_docs_change_is_low_risk_and_buys_no_tools() {
321 let triage = triage_review(
322 "diff --git a/docs/README.md b/docs/README.md\n--- a/docs/README.md\n+++ b/docs/README.md\n@@ -1 +1 @@\n-old\n+new\n",
323 );
324 assert_eq!(triage.risk, ReviewRisk::Low);
325 let budget = budget_for(&triage, 65_536);
326 assert_eq!(budget.max_tool_calls, 0);
327 assert_eq!(budget.max_steps, 1);
328 assert!(!budget.money_limit_supported);
329 }
330
331 #[test]
332 fn a_billing_migration_is_high_risk_and_buys_repository_tools() {
333 let triage = triage_review(&diff_for(&["services/billing/stripe-migration.sql"]));
334 assert_eq!(triage.risk, ReviewRisk::High);
335 assert!(
336 triage
337 .reasons
338 .iter()
339 .any(|reason| reason.contains("billing"))
340 );
341 assert!(
342 triage
343 .reasons
344 .iter()
345 .any(|reason| reason.contains("migration"))
346 );
347 let budget = budget_for(&triage, 65_536);
348 assert!(budget.max_tool_calls >= 12);
349 assert!(budget.max_steps >= 6);
350 }
351
352 #[test]
353 fn size_and_sensitive_paths_raise_the_tier_independently() {
354 let wide = diff_for(
355 &(0..25)
356 .map(|index| format!("src/part{index}.rs"))
357 .collect::<Vec<_>>()
358 .iter()
359 .map(String::as_str)
360 .collect::<Vec<_>>(),
361 );
362 assert_eq!(triage_review(&wide).risk, ReviewRisk::High);
363 let tall: String = format!(
364 "diff --git a/src/lib.rs b/src/lib.rs\n--- a/src/lib.rs\n+++ b/src/lib.rs\n@@ -1,1 +1,401 @@\n context\n{}",
365 "+line\n".repeat(400)
366 );
367 assert_eq!(triage_review(&tall).risk, ReviewRisk::High);
368 assert_eq!(
369 triage_review(&diff_for(&["src/tools/shell.rs"])).risk,
370 ReviewRisk::Low
371 );
372 }
373
374 #[test]
375 fn a_money_cap_without_a_price_is_reported_as_unsupported() {
376 let triage = triage_review(&diff_for(&["src/auth.rs"]));
377 let without_rates = budget_for(&triage, 65_536).with_money_cap(Some(0.25), None);
378 assert_eq!(without_rates.money_cap_usd, Some(0.25));
379 assert!(!without_rates.money_limit_supported);
380 let with_rates = budget_for(&triage, 65_536).with_money_cap(Some(0.25), Some((0.15, 0.60)));
381 assert!(with_rates.money_limit_supported);
382 let no_cap = budget_for(&triage, 65_536).with_money_cap(None, Some((0.15, 0.60)));
383 assert_eq!(no_cap.money_cap_usd, None);
384 assert!(!no_cap.money_limit_supported);
385 }
386
387 #[test]
388 fn cost_uses_every_billable_counter() {
389 let usage = codewhale_models::Usage {
390 input_tokens: 1_000_000,
391 output_tokens: 1_000_000,
392 prompt_cache_hit_tokens: Some(1_000_000),
393 ..Default::default()
394 };
395 let cost = SpendRates {
396 input_usd_per_million: 0.15,
397 output_usd_per_million: 0.60,
398 }
399 .cost_usd(&usage);
400 assert!((cost - (0.30 + 0.60)).abs() < 1e-9, "got {cost}");
401 }
402
403 #[test]
404 fn a_partial_review_names_the_stop_and_the_limit() {
405 let triage = triage_review(&diff_for(&["src/auth.rs"]));
406 let budget = budget_for(&triage, 65_536).with_money_cap(Some(0.25), Some((0.15, 0.60)));
407 let note = partial_review_note(&ReviewStop::MoneyCap, &triage, &budget);
408 assert!(note.contains("named partial review"));
409 assert!(note.contains("0.2500"));
410 assert!(note.contains("not evidence that they are correct"));
411 }
412 }
413
413 lines RUST