1use std::collections::BTreeMap;
11use std::fmt;
12
13use serde::de::{self, Deserializer, Visitor};
14use serde::{Deserialize, Serialize, Serializer};
15
16fn norm_token(text: &str) -> String {
17 text.trim()
18 .to_lowercase()
19 .chars()
20 .filter(|c| c.is_ascii_alphanumeric())
21 .collect()
22}
23
24macro_rules! string_enum {
25 (
26 $(#[$meta:meta])*
27 pub enum $name:ident {
28 $( $(#[$vmeta:meta])* $variant:ident = $canonical:literal $( | $alias:literal )* ),+ $(,)?
29 }
30 ) => {
31 $(#[$meta])*
32 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
33 pub enum $name { $( $(#[$vmeta])* $variant ),+ }
34
35 impl $name {
36 pub fn as_str(self) -> &'static str {
37 match self { $( $name::$variant => $canonical ),+ }
38 }
39
40 pub fn parse_lenient(text: &str) -> Option<Self> {
43 let got = norm_token(text);
44 $(
45 if got == norm_token($canonical) $( || got == norm_token($alias) )* {
46 return Some($name::$variant);
47 }
48 )+
49 None
50 }
51
52 pub fn valid_values() -> String {
53 [$( $canonical ),+].join(", ")
54 }
55 }
56
57 impl fmt::Display for $name {
58 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
59 f.write_str(self.as_str())
60 }
61 }
62
63 impl Serialize for $name {
64 fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
65 s.serialize_str(self.as_str())
66 }
67 }
68
69 impl<'de> Deserialize<'de> for $name {
70 fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
71 let raw = String::deserialize(d)?;
72 $name::parse_lenient(&raw).ok_or_else(|| {
73 de::Error::custom(format!(
74 "{} is not one of: {}",
75 raw,
76 $name::valid_values()
77 ))
78 })
79 }
80 }
81 };
82}
83
84string_enum! {
85 pub enum Complexity {
87 S = "s" | "small" | "sm" | "xs" | "trivial",
88 M = "m" | "medium" | "med" | "moderate",
89 L = "l" | "large" | "lg" | "xl" | "big" | "huge",
90 }
91}
92
93string_enum! {
94 pub enum Risk {
96 Low = "low" | "l" | "minimal" | "none",
97 Med = "med" | "medium" | "m" | "moderate",
98 High = "high" | "h" | "severe" | "critical",
99 }
100}
101
102string_enum! {
103 pub enum Severity {
108 Blocking = "blocking" | "block" | "major" | "critical",
109 NonBlocking = "non-blocking" | "nonblocking" | "non_blocking" | "minor" | "suggestion",
110 Nit = "nit" | "nitpick" | "style" | "trivial",
111 }
112}
113
114string_enum! {
115 pub enum Verdict {
116 Approve = "approve" | "approved" | "lgtm",
117 ChangesRequested = "changes_requested" | "changes-requested" | "request_changes" | "reject",
118 }
119}
120
121string_enum! {
122 pub enum NextAction {
123 Merge = "merge" | "approve" | "ship",
124 FixMyself = "fix_myself" | "fix-myself" | "fix" | "self_fix",
125 HandBack = "hand_back" | "hand-back" | "handback" | "return",
126 }
127}
128
129string_enum! {
130 pub enum Action {
134 Fixed = "fixed" | "fix" | "accepted" | "done",
135 Refuted = "refuted" | "refute" | "rejected" | "disagree" | "wontfix",
136 FiledIssue = "filed_issue" | "filed-issue" | "filed" | "deferred" | "out_of_scope",
137 }
138}
139
140string_enum! {
141 pub enum Status {
143 Pending = "pending",
144 Abandoned = "abandoned",
145 Approved = "approved",
146 Merged = "merged",
147 Escalated = "escalated",
148 Error = "error",
149 Reviewed = "reviewed",
151 Clean = "clean",
153 }
154}
155
156impl Complexity {
157 pub fn rank(self) -> u8 {
158 match self {
159 Complexity::S => 0,
160 Complexity::M => 1,
161 Complexity::L => 2,
162 }
163 }
164}
165
166impl Severity {
167 pub fn rank(self) -> u8 {
171 match self {
172 Severity::Nit => 0,
173 Severity::NonBlocking => 1,
174 Severity::Blocking => 2,
175 }
176 }
177
178 pub fn graver(self, other: Self) -> Self {
185 if self.rank() >= other.rank() {
186 self
187 } else {
188 other
189 }
190 }
191}
192
193impl Risk {
194 pub fn rank(self) -> u8 {
195 match self {
196 Risk::Low => 0,
197 Risk::Med => 1,
198 Risk::High => 2,
199 }
200 }
201}
202
203pub fn de_i64<'de, D: Deserializer<'de>>(d: D) -> Result<i64, D::Error> {
210 struct V;
211 impl<'de> Visitor<'de> for V {
212 type Value = i64;
213 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
214 f.write_str("an issue number")
215 }
216 fn visit_i64<E: de::Error>(self, v: i64) -> Result<i64, E> {
217 Ok(v)
218 }
219 fn visit_u64<E: de::Error>(self, v: u64) -> Result<i64, E> {
220 Ok(v as i64)
221 }
222 fn visit_f64<E: de::Error>(self, v: f64) -> Result<i64, E> {
223 Ok(v as i64)
224 }
225 fn visit_str<E: de::Error>(self, v: &str) -> Result<i64, E> {
226 v.trim()
227 .trim_start_matches('#')
228 .parse()
229 .map_err(|_| E::custom(format!("{v} is not a number")))
230 }
231 }
232 d.deserialize_any(V)
233}
234
235fn de_i64_vec<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<i64>, D::Error> {
236 #[derive(Deserialize)]
237 struct One(#[serde(deserialize_with = "de_i64")] i64);
238 let raw = Option::<Vec<One>>::deserialize(d)?;
239 Ok(raw
240 .unwrap_or_default()
241 .into_iter()
242 .map(|One(n)| n)
243 .collect())
244}
245
246pub fn de_bool<'de, D: Deserializer<'de>>(d: D) -> Result<bool, D::Error> {
248 struct V;
249 impl<'de> Visitor<'de> for V {
250 type Value = bool;
251 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
252 f.write_str("a boolean")
253 }
254 fn visit_bool<E: de::Error>(self, v: bool) -> Result<bool, E> {
255 Ok(v)
256 }
257 fn visit_i64<E: de::Error>(self, v: i64) -> Result<bool, E> {
258 Ok(v != 0)
259 }
260 fn visit_u64<E: de::Error>(self, v: u64) -> Result<bool, E> {
261 Ok(v != 0)
262 }
263 fn visit_str<E: de::Error>(self, v: &str) -> Result<bool, E> {
264 match norm_token(v).as_str() {
265 "true" | "yes" | "y" | "1" => Ok(true),
266 "false" | "no" | "n" | "0" => Ok(false),
267 other => Err(E::custom(format!("{other} is not a boolean"))),
268 }
269 }
270 }
271 d.deserialize_any(V)
272}
273
274fn de_bool_default_true<'de, D: Deserializer<'de>>(d: D) -> Result<bool, D::Error> {
275 #[derive(Deserialize)]
276 struct Wrap(#[serde(deserialize_with = "de_bool")] bool);
277 Ok(Option::<Wrap>::deserialize(d)?
278 .map(|Wrap(b)| b)
279 .unwrap_or(true))
280}
281
282fn de_string<'de, D: Deserializer<'de>>(d: D) -> Result<String, D::Error> {
283 Ok(Option::<String>::deserialize(d)?.unwrap_or_default())
284}
285
286#[derive(Debug, Clone, Serialize, Deserialize)]
291pub struct TriageVerdict {
292 #[serde(deserialize_with = "de_i64")]
293 pub issue: i64,
294 #[serde(deserialize_with = "de_bool")]
295 pub worth_doing: bool,
296 #[serde(default, deserialize_with = "de_string")]
297 pub reason: String,
298 pub complexity: Complexity,
299 #[serde(default, deserialize_with = "de_i64_vec")]
300 pub depends_on: Vec<i64>,
301 pub risk: Risk,
302}
303
304#[derive(Debug, Clone, Serialize, Deserialize)]
305pub struct TriageResponse {
306 #[serde(default)]
307 pub issues: Vec<TriageVerdict>,
308}
309
310#[derive(Debug, Clone, Serialize, Deserialize)]
311pub struct Finding {
312 pub severity: Severity,
313 #[serde(default, deserialize_with = "de_string")]
314 pub title: String,
315 #[serde(default, deserialize_with = "de_string")]
316 pub detail: String,
317 #[serde(default, deserialize_with = "de_string")]
318 pub file: String,
319 #[serde(default = "yes", deserialize_with = "de_bool_default_true")]
322 pub in_scope: bool,
323
324 #[serde(default)]
332 pub problem: Option<String>,
333 #[serde(default)]
335 pub reproduction: Option<String>,
336 #[serde(default)]
338 pub impact: Option<String>,
339 #[serde(default)]
341 pub expected: Option<String>,
342}
343
344impl Default for Finding {
345 fn default() -> Self {
352 Self {
353 severity: Severity::Nit,
354 title: String::new(),
355 detail: String::new(),
356 file: String::new(),
357 in_scope: true,
358 problem: None,
359 reproduction: None,
360 impact: None,
361 expected: None,
362 }
363 }
364}
365
366impl Finding {
367 pub fn report_sections(&self) -> Vec<(&'static str, &str)> {
370 [
371 ("Problem", self.problem.as_deref()),
372 ("Reproduction", self.reproduction.as_deref()),
373 ("Impact", self.impact.as_deref()),
374 ("Expected behavior", self.expected.as_deref()),
375 ]
376 .into_iter()
377 .filter_map(|(heading, text)| {
378 text.map(str::trim)
379 .filter(|t| !t.is_empty())
380 .map(|t| (heading, t))
381 })
382 .collect()
383 }
384}
385
386fn yes() -> bool {
387 true
388}
389
390impl Finding {
391 pub fn blocks(&self) -> bool {
392 self.severity == Severity::Blocking && self.in_scope
393 }
394
395 pub fn where_at(&self) -> &str {
396 if self.file.trim().is_empty() {
397 "general"
398 } else {
399 self.file.trim()
400 }
401 }
402}
403
404#[derive(Debug, Clone, Serialize, Deserialize)]
405pub struct Review {
406 pub verdict: Verdict,
407 pub next_action: NextAction,
408 #[serde(default, deserialize_with = "de_string")]
409 pub summary: String,
410 #[serde(default)]
411 pub findings: Vec<Finding>,
412}
413
414#[derive(Debug, Clone, Serialize, Deserialize)]
415pub struct Disposition {
416 #[serde(default, deserialize_with = "de_string")]
417 pub title: String,
418 #[serde(default, deserialize_with = "de_string")]
422 pub file: String,
423 pub action: Action,
424 #[serde(default, deserialize_with = "de_string")]
425 pub reasoning: String,
426 #[serde(default)]
427 pub new_issue_title: Option<String>,
428 #[serde(default)]
429 pub new_issue_body: Option<String>,
430}
431
432#[derive(Debug, Clone, Serialize, Deserialize)]
439pub struct Adjudication {
440 #[serde(default, deserialize_with = "de_string")]
441 pub title: String,
442 #[serde(default, deserialize_with = "de_string")]
443 pub file: String,
444 #[serde(deserialize_with = "de_bool")]
447 pub agrees: bool,
448 pub severity: Severity,
450 #[serde(default, deserialize_with = "de_string")]
451 pub reasoning: String,
452}
453
454#[derive(Debug, Clone, Serialize, Deserialize)]
455pub struct AdjudicationDoc {
456 #[serde(default)]
457 pub verdicts: Vec<Adjudication>,
458}
459
460#[derive(Debug, Clone)]
462pub struct Judged {
463 pub finding: Finding,
464 pub raised_by: String,
466 pub standing: Standing,
468 pub counterpoint: Option<String>,
470 pub defence: Option<String>,
475}
476
477#[derive(Debug, Clone, Copy, PartialEq, Eq)]
478pub enum Standing {
479 Corroborated,
481 Confirmed,
483 Disputed,
486 Withdrawn,
488 Unverified,
490}
491
492#[derive(Debug, Clone, Serialize, Deserialize)]
493pub struct ResponseDoc {
494 #[serde(default, deserialize_with = "de_string")]
495 pub summary: String,
496 #[serde(default)]
497 pub dispositions: Vec<Disposition>,
498}
499
500#[derive(Debug, Clone, Serialize, Deserialize)]
505pub struct PlanItem {
506 pub issue: i64,
507 pub title: String,
508 pub complexity: Complexity,
509 pub risk: Risk,
510 pub depends_on: Vec<i64>,
511 pub reason: String,
512}
513
514#[derive(Debug, Clone, Serialize, Deserialize)]
515pub struct SkippedItem {
516 pub issue: i64,
517 pub title: String,
518 pub reasons: BTreeMap<String, String>,
520}
521
522#[derive(Debug, Clone, Serialize, Deserialize)]
523pub struct ContestedItem {
524 pub issue: i64,
525 pub title: String,
526 pub positions: BTreeMap<String, String>,
528 pub reasons: BTreeMap<String, String>,
529 #[serde(default, skip_serializing_if = "Option::is_none")]
530 pub note: Option<String>,
531}
532
533#[derive(Debug, Clone, Default, Serialize, Deserialize)]
534pub struct Plan {
535 #[serde(default)]
536 pub order: Vec<PlanItem>,
537 #[serde(default)]
538 pub skipped: Vec<SkippedItem>,
539 #[serde(default)]
540 pub contested: Vec<ContestedItem>,
541}
542
543#[derive(Debug, Clone, Serialize, Deserialize)]
544pub struct LedgerEntry {
545 pub title: String,
546 pub file: String,
547 pub reasoning: String,
548 pub round: u32,
549 #[serde(default)]
550 pub reraised: u32,
551}
552
553pub type Ledger = BTreeMap<String, LedgerEntry>;
557
558#[derive(Debug, Clone, Serialize, Deserialize)]
559pub struct Dispute {
560 pub title: String,
561 pub reasoning: String,
562}
563
564#[derive(Debug, Clone, Serialize, Deserialize)]
566pub struct IssueRun {
567 pub issue: i64,
568 pub title: String,
569 pub status: Status,
570 #[serde(default, skip_serializing_if = "Option::is_none")]
571 pub pr: Option<String>,
572 #[serde(default)]
573 pub rounds: u32,
574 #[serde(default)]
575 pub disputes: Vec<Dispute>,
576 #[serde(default)]
577 pub filed: Vec<String>,
578 #[serde(default)]
579 pub notes: Vec<String>,
580}
581
582impl IssueRun {
583 pub fn new(issue: i64, title: impl Into<String>) -> Self {
584 Self {
585 issue,
586 title: title.into(),
587 status: Status::Pending,
588 pr: None,
589 rounds: 0,
590 disputes: Vec::new(),
591 filed: Vec::new(),
592 notes: Vec::new(),
593 }
594 }
595
596 pub fn succeeded(&self) -> bool {
601 matches!(
602 self.status,
603 Status::Merged
604 | Status::Approved
605 | Status::Abandoned
606 | Status::Reviewed
607 | Status::Clean
608 )
609 }
610}
611
612#[derive(Debug, Clone, Serialize, Deserialize)]
614pub struct PersistedState {
615 pub version: u32,
616 pub round: u32,
617 pub next_actor: String,
618 pub status: Status,
619 #[serde(default)]
620 pub ledger: Ledger,
621 #[serde(default)]
622 pub filed: Vec<String>,
623}
624
625pub const STATE_VERSION: u32 = 1;
626
627#[derive(Debug, Clone, Deserialize)]
632pub struct Label {
633 #[serde(default)]
634 pub name: String,
635}
636
637#[derive(Debug, Clone, Deserialize)]
638pub struct Issue {
639 pub number: i64,
640 #[serde(default)]
641 pub title: String,
642 #[serde(default)]
643 pub body: Option<String>,
644 #[serde(default)]
645 pub state: String,
646 #[serde(default)]
647 pub url: String,
648 #[serde(default)]
649 pub labels: Vec<Label>,
650}
651
652impl Issue {
653 pub fn body_text(&self) -> &str {
654 self.body.as_deref().unwrap_or("")
655 }
656
657 pub fn is_closed(&self) -> bool {
658 self.state.eq_ignore_ascii_case("closed")
659 }
660}
661
662#[derive(Debug, Clone, Deserialize)]
663pub struct PrRef {
664 pub number: i64,
665 #[serde(default)]
666 pub url: String,
667 #[serde(default)]
668 pub title: String,
669}
670
671#[derive(Debug, Clone, Deserialize)]
672pub struct IssueRef {
673 pub number: i64,
674}
675
676#[derive(Debug, Clone, Deserialize)]
677#[serde(rename_all = "camelCase")]
678pub struct PrView {
679 pub number: i64,
680 #[serde(default)]
681 pub url: String,
682 #[serde(default)]
683 pub title: String,
684 #[serde(default)]
685 pub head_ref_name: String,
686 #[serde(default)]
687 pub base_ref_name: String,
688 #[serde(default)]
689 pub state: String,
690 #[serde(default)]
691 pub closing_issues_references: Vec<IssueRef>,
692 #[serde(default)]
695 pub is_cross_repository: bool,
696}
697
698#[derive(Debug, Clone, Copy, PartialEq, Eq)]
701pub enum ItemKind {
702 Issue,
703 Pr,
704}
705
706impl std::fmt::Display for ItemKind {
707 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
708 f.write_str(match self {
709 ItemKind::Issue => "issue",
710 ItemKind::Pr => "pull request",
711 })
712 }
713}
714
715impl PrView {
716 pub fn is_open(&self) -> bool {
717 self.state.eq_ignore_ascii_case("open")
718 }
719}
720
721#[cfg(test)]
722mod tests {
723 use super::*;
724
725 #[test]
726 fn severity_accepts_the_canonical_spelling() {
727 assert_eq!(
728 Some(Severity::NonBlocking),
729 Severity::parse_lenient("non-blocking")
730 );
731 }
732
733 #[test]
734 fn severity_accepts_near_misses() {
735 for text in ["NonBlocking", "non_blocking", " NON-BLOCKING ", "minor"] {
736 assert_eq!(
737 Some(Severity::NonBlocking),
738 Severity::parse_lenient(text),
739 "{text}"
740 );
741 }
742 }
743
744 #[test]
745 fn severity_rejects_nonsense() {
746 assert_eq!(None, Severity::parse_lenient("catastrophic-ish"));
747 }
748
749 #[test]
750 fn complexity_ordering_is_cheapest_first() {
751 assert!(Complexity::S.rank() < Complexity::M.rank());
752 assert!(Complexity::M.rank() < Complexity::L.rank());
753 }
754
755 #[test]
756 fn finding_defaults_to_in_scope() {
757 let f: Finding = serde_json::from_value(serde_json::json!({
758 "severity": "blocking", "title": "t", "detail": "d", "file": "a.rs"
759 }))
760 .unwrap();
761 assert!(f.in_scope);
762 assert!(f.blocks());
763 }
764
765 #[test]
766 fn out_of_scope_blocking_does_not_block() {
767 let f: Finding = serde_json::from_value(serde_json::json!({
768 "severity": "blocking", "title": "t", "detail": "d",
769 "file": "a.rs", "in_scope": false
770 }))
771 .unwrap();
772 assert!(!f.blocks());
773 }
774
775 #[test]
776 fn triage_tolerates_a_quoted_issue_number() {
777 let v: TriageVerdict = serde_json::from_value(serde_json::json!({
778 "issue": "#42", "worth_doing": "yes", "reason": "r",
779 "complexity": "medium", "depends_on": ["39"], "risk": "low"
780 }))
781 .unwrap();
782 assert_eq!(42, v.issue);
783 assert!(v.worth_doing);
784 assert_eq!(Complexity::M, v.complexity);
785 assert_eq!(vec![39], v.depends_on);
786 }
787
788 #[test]
789 fn triage_tolerates_a_missing_depends_on() {
790 let v: TriageVerdict = serde_json::from_value(serde_json::json!({
791 "issue": 1, "worth_doing": false, "reason": "r",
792 "complexity": "s", "risk": "high"
793 }))
794 .unwrap();
795 assert!(v.depends_on.is_empty());
796 }
797
798 #[test]
799 fn review_tolerates_a_missing_findings_array() {
800 let r: Review = serde_json::from_value(serde_json::json!({
801 "verdict": "approve", "next_action": "merge", "summary": "fine"
802 }))
803 .unwrap();
804 assert!(r.findings.is_empty());
805 }
806
807 #[test]
808 fn a_null_reason_is_an_empty_string_not_a_failure() {
809 let v: TriageVerdict = serde_json::from_value(serde_json::json!({
810 "issue": 1, "worth_doing": true, "reason": null,
811 "complexity": "s", "depends_on": [], "risk": "low"
812 }))
813 .unwrap();
814 assert_eq!("", v.reason);
815 }
816
817 #[test]
818 fn unknown_severity_is_an_error_not_a_silent_downgrade() {
819 let out: Result<Finding, _> = serde_json::from_value(serde_json::json!({
820 "severity": "showstopper-maybe", "title": "t", "detail": "d", "file": "a.rs"
821 }));
822 assert!(out.is_err());
823 }
824
825 #[test]
826 fn status_round_trips_through_json() {
827 let run = IssueRun::new(4, "t");
828 let text = serde_json::to_string(&run).unwrap();
829 let back: IssueRun = serde_json::from_str(&text).unwrap();
830 assert_eq!(Status::Pending, back.status);
831 }
832}