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
325fn yes() -> bool {
326 true
327}
328
329impl Finding {
330 pub fn blocks(&self) -> bool {
331 self.severity == Severity::Blocking && self.in_scope
332 }
333
334 pub fn where_at(&self) -> &str {
335 if self.file.trim().is_empty() {
336 "general"
337 } else {
338 self.file.trim()
339 }
340 }
341}
342
343#[derive(Debug, Clone, Serialize, Deserialize)]
344pub struct Review {
345 pub verdict: Verdict,
346 pub next_action: NextAction,
347 #[serde(default, deserialize_with = "de_string")]
348 pub summary: String,
349 #[serde(default)]
350 pub findings: Vec<Finding>,
351}
352
353#[derive(Debug, Clone, Serialize, Deserialize)]
354pub struct Disposition {
355 #[serde(default, deserialize_with = "de_string")]
356 pub title: String,
357 #[serde(default, deserialize_with = "de_string")]
361 pub file: String,
362 pub action: Action,
363 #[serde(default, deserialize_with = "de_string")]
364 pub reasoning: String,
365 #[serde(default)]
366 pub new_issue_title: Option<String>,
367 #[serde(default)]
368 pub new_issue_body: Option<String>,
369}
370
371#[derive(Debug, Clone, Serialize, Deserialize)]
378pub struct Adjudication {
379 #[serde(default, deserialize_with = "de_string")]
380 pub title: String,
381 #[serde(default, deserialize_with = "de_string")]
382 pub file: String,
383 #[serde(deserialize_with = "de_bool")]
386 pub agrees: bool,
387 pub severity: Severity,
389 #[serde(default, deserialize_with = "de_string")]
390 pub reasoning: String,
391}
392
393#[derive(Debug, Clone, Serialize, Deserialize)]
394pub struct AdjudicationDoc {
395 #[serde(default)]
396 pub verdicts: Vec<Adjudication>,
397}
398
399#[derive(Debug, Clone)]
401pub struct Judged {
402 pub finding: Finding,
403 pub raised_by: String,
405 pub standing: Standing,
407 pub counterpoint: Option<String>,
409}
410
411#[derive(Debug, Clone, Copy, PartialEq, Eq)]
412pub enum Standing {
413 Corroborated,
415 Confirmed,
417 Disputed,
420 Withdrawn,
422 Unverified,
424}
425
426#[derive(Debug, Clone, Serialize, Deserialize)]
427pub struct ResponseDoc {
428 #[serde(default, deserialize_with = "de_string")]
429 pub summary: String,
430 #[serde(default)]
431 pub dispositions: Vec<Disposition>,
432}
433
434#[derive(Debug, Clone, Serialize, Deserialize)]
439pub struct PlanItem {
440 pub issue: i64,
441 pub title: String,
442 pub complexity: Complexity,
443 pub risk: Risk,
444 pub depends_on: Vec<i64>,
445 pub reason: String,
446}
447
448#[derive(Debug, Clone, Serialize, Deserialize)]
449pub struct SkippedItem {
450 pub issue: i64,
451 pub title: String,
452 pub reasons: BTreeMap<String, String>,
454}
455
456#[derive(Debug, Clone, Serialize, Deserialize)]
457pub struct ContestedItem {
458 pub issue: i64,
459 pub title: String,
460 pub positions: BTreeMap<String, String>,
462 pub reasons: BTreeMap<String, String>,
463 #[serde(default, skip_serializing_if = "Option::is_none")]
464 pub note: Option<String>,
465}
466
467#[derive(Debug, Clone, Default, Serialize, Deserialize)]
468pub struct Plan {
469 #[serde(default)]
470 pub order: Vec<PlanItem>,
471 #[serde(default)]
472 pub skipped: Vec<SkippedItem>,
473 #[serde(default)]
474 pub contested: Vec<ContestedItem>,
475}
476
477#[derive(Debug, Clone, Serialize, Deserialize)]
478pub struct LedgerEntry {
479 pub title: String,
480 pub file: String,
481 pub reasoning: String,
482 pub round: u32,
483 #[serde(default)]
484 pub reraised: u32,
485}
486
487pub type Ledger = BTreeMap<String, LedgerEntry>;
491
492#[derive(Debug, Clone, Serialize, Deserialize)]
493pub struct Dispute {
494 pub title: String,
495 pub reasoning: String,
496}
497
498#[derive(Debug, Clone, Serialize, Deserialize)]
500pub struct IssueRun {
501 pub issue: i64,
502 pub title: String,
503 pub status: Status,
504 #[serde(default, skip_serializing_if = "Option::is_none")]
505 pub pr: Option<String>,
506 #[serde(default)]
507 pub rounds: u32,
508 #[serde(default)]
509 pub disputes: Vec<Dispute>,
510 #[serde(default)]
511 pub filed: Vec<String>,
512 #[serde(default)]
513 pub notes: Vec<String>,
514}
515
516impl IssueRun {
517 pub fn new(issue: i64, title: impl Into<String>) -> Self {
518 Self {
519 issue,
520 title: title.into(),
521 status: Status::Pending,
522 pr: None,
523 rounds: 0,
524 disputes: Vec::new(),
525 filed: Vec::new(),
526 notes: Vec::new(),
527 }
528 }
529
530 pub fn succeeded(&self) -> bool {
535 matches!(
536 self.status,
537 Status::Merged
538 | Status::Approved
539 | Status::Abandoned
540 | Status::Reviewed
541 | Status::Clean
542 )
543 }
544}
545
546#[derive(Debug, Clone, Serialize, Deserialize)]
548pub struct PersistedState {
549 pub version: u32,
550 pub round: u32,
551 pub next_actor: String,
552 pub status: Status,
553 #[serde(default)]
554 pub ledger: Ledger,
555 #[serde(default)]
556 pub filed: Vec<String>,
557}
558
559pub const STATE_VERSION: u32 = 1;
560
561#[derive(Debug, Clone, Deserialize)]
566pub struct Label {
567 #[serde(default)]
568 pub name: String,
569}
570
571#[derive(Debug, Clone, Deserialize)]
572pub struct Issue {
573 pub number: i64,
574 #[serde(default)]
575 pub title: String,
576 #[serde(default)]
577 pub body: Option<String>,
578 #[serde(default)]
579 pub state: String,
580 #[serde(default)]
581 pub url: String,
582 #[serde(default)]
583 pub labels: Vec<Label>,
584}
585
586impl Issue {
587 pub fn body_text(&self) -> &str {
588 self.body.as_deref().unwrap_or("")
589 }
590
591 pub fn is_closed(&self) -> bool {
592 self.state.eq_ignore_ascii_case("closed")
593 }
594}
595
596#[derive(Debug, Clone, Deserialize)]
597pub struct PrRef {
598 pub number: i64,
599 #[serde(default)]
600 pub url: String,
601 #[serde(default)]
602 pub title: String,
603}
604
605#[derive(Debug, Clone, Deserialize)]
606pub struct IssueRef {
607 pub number: i64,
608}
609
610#[derive(Debug, Clone, Deserialize)]
611#[serde(rename_all = "camelCase")]
612pub struct PrView {
613 pub number: i64,
614 #[serde(default)]
615 pub url: String,
616 #[serde(default)]
617 pub title: String,
618 #[serde(default)]
619 pub head_ref_name: String,
620 #[serde(default)]
621 pub base_ref_name: String,
622 #[serde(default)]
623 pub state: String,
624 #[serde(default)]
625 pub closing_issues_references: Vec<IssueRef>,
626 #[serde(default)]
629 pub is_cross_repository: bool,
630}
631
632#[derive(Debug, Clone, Copy, PartialEq, Eq)]
635pub enum ItemKind {
636 Issue,
637 Pr,
638}
639
640impl std::fmt::Display for ItemKind {
641 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
642 f.write_str(match self {
643 ItemKind::Issue => "issue",
644 ItemKind::Pr => "pull request",
645 })
646 }
647}
648
649impl PrView {
650 pub fn is_open(&self) -> bool {
651 self.state.eq_ignore_ascii_case("open")
652 }
653}
654
655#[cfg(test)]
656mod tests {
657 use super::*;
658
659 #[test]
660 fn severity_accepts_the_canonical_spelling() {
661 assert_eq!(
662 Some(Severity::NonBlocking),
663 Severity::parse_lenient("non-blocking")
664 );
665 }
666
667 #[test]
668 fn severity_accepts_near_misses() {
669 for text in ["NonBlocking", "non_blocking", " NON-BLOCKING ", "minor"] {
670 assert_eq!(
671 Some(Severity::NonBlocking),
672 Severity::parse_lenient(text),
673 "{text}"
674 );
675 }
676 }
677
678 #[test]
679 fn severity_rejects_nonsense() {
680 assert_eq!(None, Severity::parse_lenient("catastrophic-ish"));
681 }
682
683 #[test]
684 fn complexity_ordering_is_cheapest_first() {
685 assert!(Complexity::S.rank() < Complexity::M.rank());
686 assert!(Complexity::M.rank() < Complexity::L.rank());
687 }
688
689 #[test]
690 fn finding_defaults_to_in_scope() {
691 let f: Finding = serde_json::from_value(serde_json::json!({
692 "severity": "blocking", "title": "t", "detail": "d", "file": "a.rs"
693 }))
694 .unwrap();
695 assert!(f.in_scope);
696 assert!(f.blocks());
697 }
698
699 #[test]
700 fn out_of_scope_blocking_does_not_block() {
701 let f: Finding = serde_json::from_value(serde_json::json!({
702 "severity": "blocking", "title": "t", "detail": "d",
703 "file": "a.rs", "in_scope": false
704 }))
705 .unwrap();
706 assert!(!f.blocks());
707 }
708
709 #[test]
710 fn triage_tolerates_a_quoted_issue_number() {
711 let v: TriageVerdict = serde_json::from_value(serde_json::json!({
712 "issue": "#42", "worth_doing": "yes", "reason": "r",
713 "complexity": "medium", "depends_on": ["39"], "risk": "low"
714 }))
715 .unwrap();
716 assert_eq!(42, v.issue);
717 assert!(v.worth_doing);
718 assert_eq!(Complexity::M, v.complexity);
719 assert_eq!(vec![39], v.depends_on);
720 }
721
722 #[test]
723 fn triage_tolerates_a_missing_depends_on() {
724 let v: TriageVerdict = serde_json::from_value(serde_json::json!({
725 "issue": 1, "worth_doing": false, "reason": "r",
726 "complexity": "s", "risk": "high"
727 }))
728 .unwrap();
729 assert!(v.depends_on.is_empty());
730 }
731
732 #[test]
733 fn review_tolerates_a_missing_findings_array() {
734 let r: Review = serde_json::from_value(serde_json::json!({
735 "verdict": "approve", "next_action": "merge", "summary": "fine"
736 }))
737 .unwrap();
738 assert!(r.findings.is_empty());
739 }
740
741 #[test]
742 fn a_null_reason_is_an_empty_string_not_a_failure() {
743 let v: TriageVerdict = serde_json::from_value(serde_json::json!({
744 "issue": 1, "worth_doing": true, "reason": null,
745 "complexity": "s", "depends_on": [], "risk": "low"
746 }))
747 .unwrap();
748 assert_eq!("", v.reason);
749 }
750
751 #[test]
752 fn unknown_severity_is_an_error_not_a_silent_downgrade() {
753 let out: Result<Finding, _> = serde_json::from_value(serde_json::json!({
754 "severity": "showstopper-maybe", "title": "t", "detail": "d", "file": "a.rs"
755 }));
756 assert!(out.is_err());
757 }
758
759 #[test]
760 fn status_round_trips_through_json() {
761 let run = IssueRun::new(4, "t");
762 let text = serde_json::to_string(&run).unwrap();
763 let back: IssueRun = serde_json::from_str(&text).unwrap();
764 assert_eq!(Status::Pending, back.status);
765 }
766}