1use std::collections::BTreeMap;
9
10use anyhow::{Result, bail};
11use serde::{Deserialize, Serialize};
12
13#[derive(Debug, Clone, Serialize, Deserialize)]
15pub struct Ranking {
16 pub ranking: Vec<String>,
18 #[serde(default)]
20 pub reasons: BTreeMap<String, String>,
21 #[serde(default)]
23 pub confidence: Option<u8>,
24}
25
26impl Ranking {
27 pub fn top(&self) -> Option<&str> {
29 self.ranking.first().map(String::as_str)
30 }
31
32 pub fn validate(&self, labels: &[char]) -> Result<()> {
35 let mut got: Vec<char> = self
36 .ranking
37 .iter()
38 .filter_map(|s| s.trim().chars().next())
39 .map(|c| c.to_ascii_uppercase())
40 .collect();
41 got.sort_unstable();
42 got.dedup();
43 let mut want: Vec<char> = labels.to_vec();
44 want.sort_unstable();
45 if got != want {
46 bail!(
47 "ranking {:?} is not a permutation of the candidate labels {:?}",
48 self.ranking,
49 labels
50 );
51 }
52 Ok(())
53 }
54
55 pub fn normalized(&self) -> Vec<char> {
57 self.ranking
58 .iter()
59 .filter_map(|s| s.trim().chars().next())
60 .map(|c| c.to_ascii_uppercase())
61 .collect()
62 }
63}
64
65#[derive(Debug, Clone, Serialize, Deserialize)]
67pub struct FinalVote {
68 pub vote: String,
70 #[serde(default)]
72 pub reason: String,
73}
74
75impl FinalVote {
76 pub fn label(&self) -> Option<char> {
78 self.vote
79 .trim()
80 .chars()
81 .next()
82 .map(|c| c.to_ascii_uppercase())
83 }
84}
85
86#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
88#[serde(rename_all = "lowercase")]
89pub enum Severity {
90 Nit,
92 Minor,
94 Major,
96 Blocker,
98}
99
100impl Severity {
101 pub fn blocks(self) -> bool {
103 matches!(self, Self::Major | Self::Blocker)
104 }
105}
106
107#[derive(Debug, Clone, Serialize, Deserialize)]
109pub struct Finding {
110 #[serde(default)]
113 pub id: String,
114 pub severity: Severity,
116 #[serde(default)]
118 pub file: Option<String>,
119 #[serde(default)]
121 pub line: Option<u32>,
122 pub title: String,
124 #[serde(default)]
126 pub detail: String,
127}
128
129#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
138#[serde(rename_all = "snake_case")]
139pub enum ReviewVote {
140 Approve,
142 ApproveWithFindings,
144 Reject,
146}
147
148impl ReviewVote {
149 pub fn label(self) -> &'static str {
152 match self {
153 Self::Approve => "approve",
154 Self::ApproveWithFindings => "approve with findings",
155 Self::Reject => "reject",
156 }
157 }
158
159 pub fn worst(votes: impl IntoIterator<Item = Self>) -> Option<Self> {
165 votes.into_iter().max()
166 }
167}
168
169#[derive(Debug, Clone, Serialize, Deserialize)]
171pub struct Review {
172 #[serde(default)]
174 pub findings: Vec<Finding>,
175 #[serde(default)]
177 pub summary: String,
178 pub vote: ReviewVote,
182}
183
184#[derive(Debug, Clone, Serialize, Deserialize)]
188pub struct ReviewRevote {
189 pub vote: ReviewVote,
191 #[serde(default)]
193 pub reason: String,
194}
195
196#[derive(Debug, Clone, Serialize, Deserialize)]
198pub struct FixReport {
199 #[serde(default)]
201 pub addressed: Vec<String>,
202 #[serde(default)]
204 pub rejected: Vec<Rejection>,
205 #[serde(default)]
207 pub notes: String,
208}
209
210#[derive(Debug, Clone, Serialize, Deserialize)]
212pub struct Rejection {
213 pub id: String,
215 #[serde(default)]
217 pub why: String,
218}
219
220#[derive(Debug, Clone, Serialize, Deserialize)]
222pub struct Position {
223 #[serde(default)]
225 pub tentative: Option<String>,
226}
227
228#[derive(Debug, Clone, Serialize, Deserialize)]
236pub struct Proposal {
237 pub approach: String,
239 pub key_tradeoff: String,
241 #[serde(default)]
243 pub risks: Vec<String>,
244 #[serde(default)]
246 pub touches: Vec<String>,
247 pub why_not_naive: String,
250}
251
252impl Proposal {
253 pub fn validate(&self) -> Result<()> {
257 for (field, value) in [
258 ("approach", &self.approach),
259 ("key_tradeoff", &self.key_tradeoff),
260 ("why_not_naive", &self.why_not_naive),
261 ] {
262 if value.trim().is_empty() {
263 bail!("`{field}` is empty");
264 }
265 }
266 Ok(())
267 }
268}
269
270pub fn extract_json<T: serde::de::DeserializeOwned>(text: &str) -> Result<T> {
276 let bytes = text.as_bytes();
277 let mut spans: Vec<(usize, usize)> = Vec::new();
278 let mut i = 0usize;
279 while i < bytes.len() {
280 if bytes[i] != b'{' {
281 i += 1;
282 continue;
283 }
284 let mut depth = 0usize;
285 let mut in_str = false;
286 let mut escaped = false;
287 let mut j = i;
288 while j < bytes.len() {
289 let c = bytes[j];
290 if in_str {
291 if escaped {
292 escaped = false;
293 } else if c == b'\\' {
294 escaped = true;
295 } else if c == b'"' {
296 in_str = false;
297 }
298 } else {
299 match c {
300 b'"' => in_str = true,
301 b'{' => depth += 1,
302 b'}' => {
303 depth -= 1;
304 if depth == 0 {
305 spans.push((i, j + 1));
306 break;
307 }
308 }
309 _ => {}
310 }
311 }
312 j += 1;
313 }
314 i = if depth == 0 && j < bytes.len() {
317 j + 1
318 } else {
319 i + 1
320 };
321 }
322
323 let mut last_err = None;
324 for (start, end) in spans.iter().rev() {
325 match serde_json::from_str::<T>(&text[*start..*end]) {
326 Ok(v) => return Ok(v),
327 Err(e) => last_err = Some(e),
328 }
329 }
330 match last_err {
331 Some(e) => bail!("no JSON object in the reply matched the expected shape: {e}"),
332 None => bail!("the reply contained no JSON object"),
333 }
334}
335
336pub fn section(text: &str, heading: &str) -> Option<String> {
340 let want = heading.to_ascii_lowercase();
341 let mut out: Option<String> = None;
342 for line in text.lines() {
343 let trimmed = line.trim();
344 if let Some(rest) = trimmed.strip_prefix("##") {
345 let name = rest.trim_start_matches('#').trim().to_ascii_lowercase();
346 if name == want {
347 out = Some(String::new());
348 continue;
349 }
350 if out.is_some() {
351 break;
352 }
353 continue;
354 }
355 if let Some(buf) = out.as_mut() {
356 buf.push_str(line);
357 buf.push('\n');
358 }
359 }
360 out.map(|s| s.trim().to_owned()).filter(|s| !s.is_empty())
361}
362
363#[cfg(test)]
364mod tests {
365 use super::*;
366
367 #[test]
368 fn fenced_block_is_found() {
369 let text = "Here is my verdict.\n\n```json\n{\"ranking\":[\"B\",\"A\"]}\n```\n";
370 let r: Ranking = extract_json(text).unwrap();
371 assert_eq!(r.top(), Some("B"));
372 }
373
374 #[test]
375 fn last_matching_object_wins_over_an_earlier_example() {
376 let text = concat!(
377 "The format is {\"ranking\":[\"X\"]} for illustration.\n",
378 "```json\n{\"ranking\":[\"C\",\"A\",\"B\"],\"confidence\":4}\n```\n",
379 "Happy to elaborate.\n"
380 );
381 let r: Ranking = extract_json(text).unwrap();
382 assert_eq!(r.normalized(), ['C', 'A', 'B']);
383 assert_eq!(r.confidence, Some(4));
384 }
385
386 #[test]
387 fn braces_inside_strings_do_not_close_the_object() {
388 let text = r#"{"ranking":["A"],"reasons":{"A":"uses format!(\"{}\", x) safely}"}}"#;
389 let r: Ranking = extract_json(text).unwrap();
390 assert_eq!(r.top(), Some("A"));
391 assert!(r.reasons["A"].contains("format!"));
392 }
393
394 #[test]
395 fn objects_of_the_wrong_shape_are_skipped() {
396 let text = concat!(
397 "```json\n{\"ranking\":[\"A\",\"B\"]}\n```\n",
398 "and some telemetry: {\"tokens\":123}\n"
399 );
400 let r: Ranking = extract_json(text).unwrap();
401 assert_eq!(r.normalized(), ['A', 'B']);
402 }
403
404 #[test]
405 fn no_json_is_an_error_not_a_default() {
406 let err = extract_json::<Ranking>("I decline to produce JSON.").unwrap_err();
407 assert!(err.to_string().contains("no JSON object"));
408 }
409
410 #[test]
411 fn truncated_object_does_not_hang() {
412 let err = extract_json::<Ranking>("{\"ranking\": [\"A\"").unwrap_err();
413 assert!(err.to_string().contains("no JSON object"));
414 }
415
416 #[test]
417 fn ranking_validation_rejects_a_non_permutation() {
418 let r = Ranking {
419 ranking: vec!["A".to_owned(), "A".to_owned()],
420 reasons: BTreeMap::new(),
421 confidence: None,
422 };
423 assert!(r.validate(&['A', 'B', 'C']).is_err());
424
425 let r = Ranking {
426 ranking: vec!["c".to_owned(), "B".to_owned(), "A".to_owned()],
427 reasons: BTreeMap::new(),
428 confidence: None,
429 };
430 r.validate(&['A', 'B', 'C']).expect("case is normalised");
431 assert_eq!(r.normalized(), ['C', 'B', 'A']);
432 }
433
434 #[test]
435 fn final_vote_label_is_normalised() {
436 let v: FinalVote = extract_json(r#"{"vote":" b ","reason":"tests"}"#).unwrap();
437 assert_eq!(v.label(), Some('B'));
438 }
439
440 #[test]
441 fn severity_blocking_is_major_and_up() {
442 assert!(Severity::Blocker.blocks());
443 assert!(Severity::Major.blocks());
444 assert!(!Severity::Minor.blocks());
445 assert!(!Severity::Nit.blocks());
446 assert!(Severity::Blocker > Severity::Nit);
447 }
448
449 #[test]
450 fn review_parses_with_optional_fields_missing() {
451 let r: Review = extract_json(
452 r#"{"vote":"reject","findings":[{"severity":"blocker","title":"panics on empty input"}]}"#,
453 )
454 .unwrap();
455 assert_eq!(r.findings.len(), 1);
456 assert!(r.findings[0].file.is_none());
457 assert_eq!(r.findings[0].id, "");
458 assert_eq!(r.vote, ReviewVote::Reject);
459 }
460
461 #[test]
462 fn review_without_a_vote_is_rejected_rather_than_defaulted() {
463 let err = extract_json::<Review>(r#"{"findings":[]}"#).unwrap_err();
464 assert!(err.to_string().contains("no JSON object"), "{err}");
465 }
466
467 #[test]
468 fn review_vote_worst_is_the_most_cautious() {
469 assert_eq!(
470 ReviewVote::worst([ReviewVote::Approve, ReviewVote::Reject, ReviewVote::Approve]),
471 Some(ReviewVote::Reject)
472 );
473 assert_eq!(
474 ReviewVote::worst([ReviewVote::Approve, ReviewVote::ApproveWithFindings]),
475 Some(ReviewVote::ApproveWithFindings)
476 );
477 assert_eq!(ReviewVote::worst(Vec::<ReviewVote>::new()), None);
478 }
479
480 #[test]
481 fn review_revote_parses_the_reconsideration_shape() {
482 let r: ReviewRevote =
483 extract_json(r#"{"vote":"approve","reason":"the other findings do not hold"}"#)
484 .unwrap();
485 assert_eq!(r.vote, ReviewVote::Approve);
486 assert_eq!(r.reason, "the other findings do not hold");
487 }
488
489 #[test]
490 fn fix_report_parses_rejections() {
491 let f: FixReport = extract_json(
492 r#"{"addressed":["R1-1-1"],"rejected":[{"id":"R1-2-1","why":"not reachable"}]}"#,
493 )
494 .unwrap();
495 assert_eq!(f.addressed, ["R1-1-1"]);
496 assert_eq!(f.rejected[0].id, "R1-2-1");
497 }
498
499 #[test]
500 fn proposal_parses_with_optional_fields_missing() {
501 let p: Proposal = extract_json(
502 r#"{"approach":"do X","key_tradeoff":"simpler now, slower later","why_not_naive":"the naive version corrupts state under a retry"}"#,
503 )
504 .unwrap();
505 assert!(p.risks.is_empty());
506 assert!(p.touches.is_empty());
507 p.validate()
508 .expect("a proposal with only required fields is valid");
509 }
510
511 #[test]
512 fn proposal_validation_rejects_an_empty_required_field() {
513 let p = Proposal {
514 approach: String::new(),
515 key_tradeoff: "t".to_owned(),
516 risks: Vec::new(),
517 touches: Vec::new(),
518 why_not_naive: "w".to_owned(),
519 };
520 let err = p.validate().unwrap_err();
521 assert!(err.to_string().contains("approach"));
522 }
523
524 #[test]
525 fn sections_are_sliced_by_heading() {
526 let text = "## SUMMARY\nchanged the retry loop.\nadded a test.\n\n## NOTES\nignore me\n";
527 assert_eq!(
528 section(text, "summary").unwrap(),
529 "changed the retry loop.\nadded a test."
530 );
531 assert_eq!(section(text, "notes").unwrap(), "ignore me");
532 assert!(section(text, "missing").is_none());
533 }
534}