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 Ask {
147 Implement = "implement" | "do" | "accept" | "fix",
150 Defer = "defer" | "file_issue" | "filed_issue" | "out_of_scope" | "followup",
152 Decline = "decline" | "refute" | "reject" | "disagree" | "wontfix",
154 Answer = "answer" | "question" | "reply" | "clarify",
156 Nothing = "nothing" | "none" | "no_request" | "noop" | "skip",
158 }
159}
160
161string_enum! {
162 pub enum Screened {
168 StillRelevant = "still_relevant" | "still-relevant" | "relevant" | "keep" | "file",
169 AlreadyFixed = "already_fixed" | "already-fixed" | "fixed" | "done" | "resolved",
170 NotWorthIt = "not_worth_it" | "not-worth-it" | "not_worth_doing" | "skip" | "drop" | "wontfix",
171 Duplicate = "duplicate" | "dupe" | "dup",
172 }
173}
174
175string_enum! {
176 pub enum Status {
178 Pending = "pending",
179 Abandoned = "abandoned",
180 Approved = "approved",
181 Merged = "merged",
182 Escalated = "escalated",
183 Error = "error",
184 Reviewed = "reviewed",
186 Clean = "clean",
188 Answered = "answered",
190 Split = "split",
192 Whole = "whole",
194 }
195}
196
197impl Complexity {
198 pub fn rank(self) -> u8 {
199 match self {
200 Complexity::S => 0,
201 Complexity::M => 1,
202 Complexity::L => 2,
203 }
204 }
205}
206
207impl Severity {
208 pub fn rank(self) -> u8 {
212 match self {
213 Severity::Nit => 0,
214 Severity::NonBlocking => 1,
215 Severity::Blocking => 2,
216 }
217 }
218
219 pub fn graver(self, other: Self) -> Self {
226 if self.rank() >= other.rank() {
227 self
228 } else {
229 other
230 }
231 }
232}
233
234impl Risk {
235 pub fn rank(self) -> u8 {
236 match self {
237 Risk::Low => 0,
238 Risk::Med => 1,
239 Risk::High => 2,
240 }
241 }
242}
243
244pub fn de_i64<'de, D: Deserializer<'de>>(d: D) -> Result<i64, D::Error> {
251 struct V;
252 impl<'de> Visitor<'de> for V {
253 type Value = i64;
254 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
255 f.write_str("an issue number")
256 }
257 fn visit_i64<E: de::Error>(self, v: i64) -> Result<i64, E> {
258 Ok(v)
259 }
260 fn visit_u64<E: de::Error>(self, v: u64) -> Result<i64, E> {
261 Ok(v as i64)
262 }
263 fn visit_f64<E: de::Error>(self, v: f64) -> Result<i64, E> {
264 Ok(v as i64)
265 }
266 fn visit_str<E: de::Error>(self, v: &str) -> Result<i64, E> {
267 v.trim()
268 .trim_start_matches('#')
269 .parse()
270 .map_err(|_| E::custom(format!("{v} is not a number")))
271 }
272 }
273 d.deserialize_any(V)
274}
275
276fn de_i64_vec<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<i64>, D::Error> {
277 #[derive(Deserialize)]
278 struct One(#[serde(deserialize_with = "de_i64")] i64);
279 let raw = Option::<Vec<One>>::deserialize(d)?;
280 Ok(raw
281 .unwrap_or_default()
282 .into_iter()
283 .map(|One(n)| n)
284 .collect())
285}
286
287pub fn de_bool<'de, D: Deserializer<'de>>(d: D) -> Result<bool, D::Error> {
289 struct V;
290 impl<'de> Visitor<'de> for V {
291 type Value = bool;
292 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
293 f.write_str("a boolean")
294 }
295 fn visit_bool<E: de::Error>(self, v: bool) -> Result<bool, E> {
296 Ok(v)
297 }
298 fn visit_i64<E: de::Error>(self, v: i64) -> Result<bool, E> {
299 Ok(v != 0)
300 }
301 fn visit_u64<E: de::Error>(self, v: u64) -> Result<bool, E> {
302 Ok(v != 0)
303 }
304 fn visit_str<E: de::Error>(self, v: &str) -> Result<bool, E> {
305 match norm_token(v).as_str() {
306 "true" | "yes" | "y" | "1" => Ok(true),
307 "false" | "no" | "n" | "0" => Ok(false),
308 other => Err(E::custom(format!("{other} is not a boolean"))),
309 }
310 }
311 }
312 d.deserialize_any(V)
313}
314
315pub fn de_opt_i64<'de, D: Deserializer<'de>>(d: D) -> Result<Option<i64>, D::Error> {
321 Ok(match Option::<serde_json::Value>::deserialize(d)? {
322 Some(serde_json::Value::Number(n)) => n.as_i64(),
323 Some(serde_json::Value::String(s)) => s.trim().trim_start_matches('#').parse().ok(),
324 _ => None,
325 })
326}
327
328fn de_string_vec<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<String>, D::Error> {
330 Ok(Option::<Vec<String>>::deserialize(d)?.unwrap_or_default())
331}
332
333fn de_bool_default_true<'de, D: Deserializer<'de>>(d: D) -> Result<bool, D::Error> {
334 #[derive(Deserialize)]
335 struct Wrap(#[serde(deserialize_with = "de_bool")] bool);
336 Ok(Option::<Wrap>::deserialize(d)?
337 .map(|Wrap(b)| b)
338 .unwrap_or(true))
339}
340
341fn de_string<'de, D: Deserializer<'de>>(d: D) -> Result<String, D::Error> {
342 Ok(Option::<String>::deserialize(d)?.unwrap_or_default())
343}
344
345#[derive(Debug, Clone, Serialize, Deserialize)]
350pub struct TriageVerdict {
351 #[serde(deserialize_with = "de_i64")]
352 pub issue: i64,
353 #[serde(deserialize_with = "de_bool")]
354 pub worth_doing: bool,
355 #[serde(default, deserialize_with = "de_bool")]
358 pub tracker: bool,
359 #[serde(default, deserialize_with = "de_string")]
360 pub reason: String,
361 pub complexity: Complexity,
362 #[serde(default, deserialize_with = "de_i64_vec")]
363 pub depends_on: Vec<i64>,
364 pub risk: Risk,
365}
366
367#[derive(Debug, Clone, Serialize, Deserialize)]
368pub struct TriageResponse {
369 #[serde(default)]
370 pub issues: Vec<TriageVerdict>,
371}
372
373#[derive(Debug, Clone, Serialize, Deserialize)]
375pub struct ScreenVerdict {
376 #[serde(deserialize_with = "de_i64")]
381 pub entry: i64,
382 pub verdict: Screened,
383 #[serde(default, deserialize_with = "de_string")]
384 pub title: String,
385 #[serde(default, deserialize_with = "de_string")]
386 pub reason: String,
387 #[serde(default, deserialize_with = "de_opt_i64")]
393 pub duplicate_of_issue: Option<i64>,
394 #[serde(default, deserialize_with = "de_opt_i64")]
396 pub duplicate_of_entry: Option<i64>,
397}
398
399impl ScreenVerdict {
400 pub fn names_a_duplicate(&self) -> bool {
402 self.duplicate_of_issue.is_some() || self.duplicate_of_entry.is_some()
403 }
404}
405
406#[derive(Debug, Clone, Serialize, Deserialize)]
407pub struct ScreenResponse {
408 #[serde(default)]
409 pub entries: Vec<ScreenVerdict>,
410}
411
412#[derive(Debug, Clone, Serialize, Deserialize)]
418pub struct SplitScreen {
419 #[serde(deserialize_with = "de_i64")]
422 pub item: i64,
423 #[serde(deserialize_with = "de_bool")]
424 pub split: bool,
425 #[serde(default, deserialize_with = "de_string")]
426 pub reason: String,
427}
428
429#[derive(Debug, Clone, Serialize, Deserialize)]
430pub struct SplitScreenDoc {
431 #[serde(default)]
432 pub items: Vec<SplitScreen>,
433}
434
435#[derive(Debug, Clone, Default, Serialize, Deserialize)]
437pub struct SplitPart {
438 #[serde(default, deserialize_with = "de_string")]
439 pub title: String,
440 #[serde(default, deserialize_with = "de_string")]
442 pub body: String,
443 #[serde(default, deserialize_with = "de_string_vec")]
446 pub files: Vec<String>,
447}
448
449#[derive(Debug, Clone, Default, Serialize, Deserialize)]
455pub struct SplitProposal {
456 #[serde(default, deserialize_with = "de_bool")]
457 pub should_split: bool,
458 #[serde(default, deserialize_with = "de_string")]
459 pub reason: String,
460 #[serde(default, deserialize_with = "de_bool")]
464 pub stacked: bool,
465 #[serde(default)]
466 pub parts: Vec<SplitPart>,
467}
468
469#[derive(Debug, Clone, Default, Serialize, Deserialize)]
471pub struct SplitCheck {
472 #[serde(default, deserialize_with = "de_bool")]
473 pub accept: bool,
474 #[serde(default, deserialize_with = "de_bool")]
475 pub stacked: bool,
476 #[serde(default, deserialize_with = "de_i64_vec")]
478 pub strike: Vec<i64>,
479 #[serde(default, deserialize_with = "de_string")]
480 pub reasoning: String,
481}
482
483#[derive(Debug, Clone, Serialize, Deserialize)]
485pub struct CommentVerdict {
486 #[serde(default, deserialize_with = "de_string")]
491 pub ref_id: String,
492 pub ask: Ask,
493 #[serde(default, deserialize_with = "de_string")]
496 pub request: String,
497 #[serde(default, deserialize_with = "de_string")]
500 pub reasoning: String,
501 #[serde(deserialize_with = "de_bool")]
504 pub unambiguous: bool,
505 #[serde(default)]
506 pub new_issue_title: Option<String>,
507 #[serde(default)]
508 pub new_issue_body: Option<String>,
509}
510
511#[derive(Debug, Clone, Serialize, Deserialize)]
512pub struct CheckinDoc {
513 #[serde(default)]
514 pub verdicts: Vec<CommentVerdict>,
515}
516
517#[derive(Debug, Clone, Serialize, Deserialize)]
519pub struct CommentCheck {
520 #[serde(default, deserialize_with = "de_string")]
521 pub ref_id: String,
522 #[serde(deserialize_with = "de_bool")]
523 pub agrees: bool,
524 pub ask: Ask,
529 #[serde(deserialize_with = "de_bool")]
530 pub unambiguous: bool,
531 #[serde(default, deserialize_with = "de_string")]
532 pub reasoning: String,
533}
534
535#[derive(Debug, Clone, Serialize, Deserialize)]
536pub struct CheckDoc {
537 #[serde(default)]
538 pub checks: Vec<CommentCheck>,
539}
540
541#[derive(Debug, Clone, Serialize, Deserialize)]
543pub struct FixOutcome {
544 #[serde(default, deserialize_with = "de_string")]
545 pub ref_id: String,
546 #[serde(deserialize_with = "de_bool")]
550 pub changed: bool,
551 #[serde(default, deserialize_with = "de_string")]
554 pub summary: String,
555 #[serde(default)]
558 pub files: Vec<String>,
559}
560
561#[derive(Debug, Clone, Serialize, Deserialize)]
562pub struct FixReport {
563 #[serde(default)]
564 pub done: Vec<FixOutcome>,
565}
566
567#[derive(Debug, Clone, Default, Serialize, Deserialize)]
579pub struct Answered {
580 #[serde(default)]
581 pub version: u32,
582 #[serde(default)]
583 pub seen: BTreeMap<String, String>,
584}
585
586#[derive(Debug, Clone, Serialize, Deserialize)]
587pub struct Finding {
588 pub severity: Severity,
589 #[serde(default, deserialize_with = "de_string")]
590 pub title: String,
591 #[serde(default, deserialize_with = "de_string")]
592 pub detail: String,
593 #[serde(default, deserialize_with = "de_string")]
594 pub file: String,
595 #[serde(default = "yes", deserialize_with = "de_bool_default_true")]
598 pub in_scope: bool,
599
600 #[serde(default)]
608 pub problem: Option<String>,
609 #[serde(default)]
611 pub reproduction: Option<String>,
612 #[serde(default)]
614 pub impact: Option<String>,
615 #[serde(default)]
617 pub expected: Option<String>,
618}
619
620impl Default for Finding {
621 fn default() -> Self {
628 Self {
629 severity: Severity::Nit,
630 title: String::new(),
631 detail: String::new(),
632 file: String::new(),
633 in_scope: true,
634 problem: None,
635 reproduction: None,
636 impact: None,
637 expected: None,
638 }
639 }
640}
641
642impl Finding {
643 pub fn report_sections(&self) -> Vec<(&'static str, &str)> {
646 [
647 ("Problem", self.problem.as_deref()),
648 ("Reproduction", self.reproduction.as_deref()),
649 ("Impact", self.impact.as_deref()),
650 ("Expected behavior", self.expected.as_deref()),
651 ]
652 .into_iter()
653 .filter_map(|(heading, text)| {
654 text.map(str::trim)
655 .filter(|t| !t.is_empty())
656 .map(|t| (heading, t))
657 })
658 .collect()
659 }
660}
661
662fn yes() -> bool {
663 true
664}
665
666impl Finding {
667 pub fn blocks(&self) -> bool {
668 self.severity == Severity::Blocking && self.in_scope
669 }
670
671 pub fn where_at(&self) -> &str {
672 if self.file.trim().is_empty() {
673 "general"
674 } else {
675 self.file.trim()
676 }
677 }
678}
679
680#[derive(Debug, Clone, Serialize, Deserialize)]
681pub struct Review {
682 pub verdict: Verdict,
683 pub next_action: NextAction,
684 #[serde(default, deserialize_with = "de_string")]
685 pub summary: String,
686 #[serde(default)]
687 pub findings: Vec<Finding>,
688}
689
690#[derive(Debug, Clone, Serialize, Deserialize)]
691pub struct Disposition {
692 #[serde(default, deserialize_with = "de_string")]
693 pub title: String,
694 #[serde(default, deserialize_with = "de_string")]
698 pub file: String,
699 pub action: Action,
700 #[serde(default, deserialize_with = "de_string")]
701 pub reasoning: String,
702 #[serde(default)]
703 pub new_issue_title: Option<String>,
704 #[serde(default)]
705 pub new_issue_body: Option<String>,
706}
707
708#[derive(Debug, Clone, Serialize, Deserialize)]
716pub struct OwnFix {
717 #[serde(default, deserialize_with = "de_string")]
718 pub title: String,
719 #[serde(default, deserialize_with = "de_string")]
722 pub file: String,
723 #[serde(deserialize_with = "de_bool")]
724 pub fixed: bool,
725 #[serde(default, deserialize_with = "de_string")]
726 pub reason: String,
727}
728
729#[derive(Debug, Clone, Serialize, Deserialize)]
730pub struct OwnFixDoc {
731 #[serde(default, deserialize_with = "de_string")]
732 pub summary: String,
733 #[serde(default)]
734 pub fixes: Vec<OwnFix>,
735}
736
737#[derive(Debug, Clone, Serialize, Deserialize)]
744pub struct Adjudication {
745 #[serde(default, deserialize_with = "de_string")]
746 pub title: String,
747 #[serde(default, deserialize_with = "de_string")]
748 pub file: String,
749 #[serde(deserialize_with = "de_bool")]
752 pub agrees: bool,
753 pub severity: Severity,
755 #[serde(default, deserialize_with = "de_string")]
756 pub reasoning: String,
757}
758
759#[derive(Debug, Clone, Serialize, Deserialize)]
760pub struct AdjudicationDoc {
761 #[serde(default)]
762 pub verdicts: Vec<Adjudication>,
763}
764
765#[derive(Debug, Clone)]
767pub struct Judged {
768 pub finding: Finding,
769 pub raised_by: String,
771 pub standing: Standing,
773 pub counterpoint: Option<String>,
775 pub defence: Option<String>,
780}
781
782#[derive(Debug, Clone, Copy, PartialEq, Eq)]
783pub enum Standing {
784 Corroborated,
786 Confirmed,
788 Disputed,
791 Withdrawn,
793 Unverified,
795}
796
797#[derive(Debug, Clone, Default, Serialize, Deserialize)]
806pub struct Implementation {
807 #[serde(default, deserialize_with = "de_bool")]
809 pub not_worth_doing: bool,
810 #[serde(default, deserialize_with = "de_string")]
813 pub reason: String,
814 #[serde(default, deserialize_with = "de_string")]
816 pub summary: String,
817 #[serde(default, deserialize_with = "de_string")]
820 pub problem: String,
821 #[serde(default)]
823 pub changes: Vec<String>,
824 #[serde(default)]
826 pub testing: Vec<String>,
827 #[serde(default)]
830 pub notes: Option<String>,
831}
832
833#[derive(Debug, Clone, Serialize, Deserialize)]
834pub struct ResponseDoc {
835 #[serde(default, deserialize_with = "de_string")]
836 pub summary: String,
837 #[serde(default)]
838 pub dispositions: Vec<Disposition>,
839}
840
841#[derive(Debug, Clone, Serialize, Deserialize)]
846pub struct PlanItem {
847 pub issue: i64,
848 pub title: String,
849 pub complexity: Complexity,
850 pub risk: Risk,
851 pub depends_on: Vec<i64>,
852 pub reason: String,
853}
854
855#[derive(Debug, Clone, Serialize, Deserialize)]
856pub struct SkippedItem {
857 pub issue: i64,
858 pub title: String,
859 pub reasons: BTreeMap<String, String>,
861 #[serde(default)]
869 pub tracker: bool,
870}
871
872#[derive(Debug, Clone, Serialize, Deserialize)]
873pub struct ContestedItem {
874 pub issue: i64,
875 pub title: String,
876 pub positions: BTreeMap<String, String>,
878 pub reasons: BTreeMap<String, String>,
879 #[serde(default, skip_serializing_if = "Option::is_none")]
880 pub note: Option<String>,
881}
882
883#[derive(Debug, Clone, Default, Serialize, Deserialize)]
890pub struct Contested {
891 #[serde(default)]
892 pub title: String,
893 #[serde(default)]
895 pub positions: BTreeMap<String, String>,
896 #[serde(default)]
897 pub reasons: BTreeMap<String, String>,
898}
899
900#[derive(Debug, Clone, Default, Serialize, Deserialize)]
901pub struct Plan {
902 #[serde(default)]
903 pub order: Vec<PlanItem>,
904 #[serde(default)]
905 pub skipped: Vec<SkippedItem>,
906 #[serde(default)]
907 pub contested: Vec<ContestedItem>,
908}
909
910string_enum! {
911 pub enum Settled {
925 Refuted = "refuted" | "refute" | "rejected",
926 Filed = "filed" | "filed_issue" | "filed-issue" | "out_of_scope",
927 Dropped = "dropped" | "not_filed" | "not-filed" | "unfiled",
928 Fixed = "fixed" | "fix" | "changed",
929 }
930}
931
932impl Default for Settled {
933 fn default() -> Self {
935 Settled::Refuted
936 }
937}
938
939#[derive(Debug, Clone, PartialEq, Eq)]
946pub enum Followup {
947 Recorded(String),
950 Covered(String),
954 Dropped(&'static str),
957 Failed,
960}
961
962impl Followup {
963 pub fn url(&self) -> Option<&str> {
968 match self {
969 Followup::Recorded(url) => Some(url),
970 _ => None,
971 }
972 }
973}
974
975#[derive(Debug, Clone, Serialize, Deserialize)]
976pub struct LedgerEntry {
977 pub title: String,
978 pub file: String,
979 pub reasoning: String,
980 pub round: u32,
981 #[serde(default)]
982 pub reraised: u32,
983 #[serde(default)]
984 pub outcome: Settled,
985}
986
987pub type Ledger = BTreeMap<String, LedgerEntry>;
991
992#[derive(Debug, Clone, Serialize, Deserialize)]
993pub struct Dispute {
994 pub title: String,
995 #[serde(default, deserialize_with = "de_string")]
996 pub file: String,
997 pub reasoning: String,
998}
999
1000#[derive(Debug, Clone, Serialize, Deserialize)]
1002pub struct IssueRun {
1003 pub issue: i64,
1004 pub title: String,
1005 pub status: Status,
1006 #[serde(default, skip_serializing_if = "Option::is_none")]
1007 pub pr: Option<String>,
1008 #[serde(default)]
1009 pub rounds: u32,
1010 #[serde(default)]
1011 pub disputes: Vec<Dispute>,
1012 #[serde(default)]
1013 pub filed: Vec<String>,
1014 #[serde(default)]
1023 pub noted: Vec<Finding>,
1024 #[serde(default)]
1025 pub notes: Vec<String>,
1026 #[serde(skip)]
1029 pub followup_writes_uncertain: bool,
1030}
1031
1032impl IssueRun {
1033 pub fn new(issue: i64, title: impl Into<String>) -> Self {
1034 Self {
1035 issue,
1036 title: title.into(),
1037 status: Status::Pending,
1038 pr: None,
1039 rounds: 0,
1040 disputes: Vec::new(),
1041 filed: Vec::new(),
1042 noted: Vec::new(),
1043 notes: Vec::new(),
1044 followup_writes_uncertain: false,
1045 }
1046 }
1047
1048 pub fn succeeded(&self) -> bool {
1053 matches!(
1054 self.status,
1055 Status::Merged
1056 | Status::Approved
1057 | Status::Abandoned
1058 | Status::Reviewed
1059 | Status::Clean
1060 | Status::Answered
1061 | Status::Split
1065 | Status::Whole
1066 )
1067 }
1068}
1069
1070#[derive(Debug, Clone, Serialize, Deserialize)]
1072pub struct PersistedState {
1073 pub version: u32,
1074 #[serde(default)]
1076 pub checkpoint: u64,
1077 pub round: u32,
1078 pub next_actor: String,
1079 pub status: Status,
1080 #[serde(default, skip_serializing_if = "String::is_empty")]
1082 pub pr_head: String,
1083 #[serde(default)]
1084 pub ledger: Ledger,
1085 #[serde(default)]
1086 pub filed: Vec<String>,
1087 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1088 pub open_findings: Vec<Finding>,
1089 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1090 pub disputes: Vec<Dispute>,
1091 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1092 pub noted: Vec<Finding>,
1093}
1094
1095pub const STATE_VERSION: u32 = 2;
1096
1097#[derive(Debug, Clone, Deserialize)]
1102pub struct Label {
1103 #[serde(default)]
1104 pub name: String,
1105}
1106
1107#[derive(Debug, Clone, Deserialize)]
1108pub struct Issue {
1109 pub number: i64,
1110 #[serde(default)]
1111 pub title: String,
1112 #[serde(default)]
1113 pub body: Option<String>,
1114 #[serde(default)]
1115 pub state: String,
1116 #[serde(default, rename = "stateReason")]
1124 pub state_reason: Option<String>,
1125 #[serde(default)]
1126 pub url: String,
1127 #[serde(default)]
1128 pub labels: Vec<Label>,
1129}
1130
1131impl Issue {
1132 pub fn body_text(&self) -> &str {
1133 self.body.as_deref().unwrap_or("")
1134 }
1135
1136 pub fn body_for_prompt(&self, max: usize) -> (String, bool) {
1148 let body = self.body_text().trim();
1149 if body.chars().count() <= max {
1150 return (body.to_string(), false);
1151 }
1152 let clipped: String = body.chars().take(max).collect();
1153 let mut kept = match clipped.rfind('\n') {
1154 Some(at) => clipped[..at].to_string(),
1155 None => clipped,
1156 };
1157 if kept.matches("```").count() % 2 == 1 {
1158 kept.push_str("\n```");
1159 }
1160 kept.push_str("\n\n[Shortened to fit. The rest of this issue was not included.]");
1161 (kept, true)
1162 }
1163
1164 pub fn is_closed(&self) -> bool {
1165 self.state.eq_ignore_ascii_case("closed")
1166 }
1167
1168 pub fn closed_as_completed(&self) -> bool {
1175 self.is_closed() && !self.closed_as_not_planned()
1176 }
1177
1178 pub fn closed_as_not_planned(&self) -> bool {
1179 self.is_closed()
1180 && self
1181 .state_reason
1182 .as_deref()
1183 .is_some_and(|reason| reason.eq_ignore_ascii_case("not_planned"))
1184 }
1185}
1186
1187#[derive(Debug, Clone, Deserialize)]
1188pub struct PrRef {
1189 pub number: i64,
1190 #[serde(default)]
1191 pub url: String,
1192 #[serde(default)]
1193 pub title: String,
1194}
1195
1196#[derive(Debug, Clone, Deserialize)]
1197pub struct IssueRef {
1198 pub number: i64,
1199}
1200
1201#[derive(Debug, Clone, Default, Deserialize)]
1207#[serde(rename_all = "camelCase")]
1208pub struct PrRow {
1209 pub number: i64,
1210 #[serde(default)]
1211 pub title: String,
1212 #[serde(default)]
1213 pub changed_files: i64,
1214 #[serde(default)]
1215 pub additions: i64,
1216 #[serde(default)]
1217 pub deletions: i64,
1218}
1219
1220impl PrRow {
1221 pub fn size(&self) -> String {
1223 format!(
1224 "{} file(s), +{} -{}",
1225 self.changed_files, self.additions, self.deletions
1226 )
1227 }
1228}
1229
1230#[derive(Debug, Clone, Deserialize)]
1231#[serde(rename_all = "camelCase")]
1232pub struct PrView {
1233 pub number: i64,
1234 #[serde(default)]
1235 pub url: String,
1236 #[serde(default)]
1237 pub title: String,
1238 #[serde(default)]
1241 pub body: String,
1242 #[serde(default)]
1243 pub head_ref_name: String,
1244 #[serde(default)]
1245 pub base_ref_name: String,
1246 #[serde(default)]
1247 pub state: String,
1248 #[serde(default)]
1249 pub closing_issues_references: Vec<IssueRef>,
1250 #[serde(default)]
1253 pub is_cross_repository: bool,
1254}
1255
1256#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1259pub enum ItemKind {
1260 Issue,
1261 Pr,
1262}
1263
1264impl std::fmt::Display for ItemKind {
1265 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1266 f.write_str(match self {
1267 ItemKind::Issue => "issue",
1268 ItemKind::Pr => "pull request",
1269 })
1270 }
1271}
1272
1273impl PrView {
1274 pub fn is_open(&self) -> bool {
1275 self.state.eq_ignore_ascii_case("open")
1276 }
1277}
1278
1279#[cfg(test)]
1280mod tests {
1281 use super::*;
1282
1283 #[test]
1284 fn severity_accepts_the_canonical_spelling() {
1285 assert_eq!(
1286 Some(Severity::NonBlocking),
1287 Severity::parse_lenient("non-blocking")
1288 );
1289 }
1290
1291 #[test]
1292 fn severity_accepts_near_misses() {
1293 for text in ["NonBlocking", "non_blocking", " NON-BLOCKING ", "minor"] {
1294 assert_eq!(
1295 Some(Severity::NonBlocking),
1296 Severity::parse_lenient(text),
1297 "{text}"
1298 );
1299 }
1300 }
1301
1302 #[test]
1303 fn severity_rejects_nonsense() {
1304 assert_eq!(None, Severity::parse_lenient("catastrophic-ish"));
1305 }
1306
1307 #[test]
1308 fn complexity_ordering_is_cheapest_first() {
1309 assert!(Complexity::S.rank() < Complexity::M.rank());
1310 assert!(Complexity::M.rank() < Complexity::L.rank());
1311 }
1312
1313 #[test]
1314 fn finding_defaults_to_in_scope() {
1315 let f: Finding = serde_json::from_value(serde_json::json!({
1316 "severity": "blocking", "title": "t", "detail": "d", "file": "a.rs"
1317 }))
1318 .unwrap();
1319 assert!(f.in_scope);
1320 assert!(f.blocks());
1321 }
1322
1323 #[test]
1324 fn out_of_scope_blocking_does_not_block() {
1325 let f: Finding = serde_json::from_value(serde_json::json!({
1326 "severity": "blocking", "title": "t", "detail": "d",
1327 "file": "a.rs", "in_scope": false
1328 }))
1329 .unwrap();
1330 assert!(!f.blocks());
1331 }
1332
1333 #[test]
1334 fn triage_tolerates_a_quoted_issue_number() {
1335 let v: TriageVerdict = serde_json::from_value(serde_json::json!({
1336 "issue": "#42", "worth_doing": "yes", "reason": "r",
1337 "complexity": "medium", "depends_on": ["39"], "risk": "low"
1338 }))
1339 .unwrap();
1340 assert_eq!(42, v.issue);
1341 assert!(v.worth_doing);
1342 assert_eq!(Complexity::M, v.complexity);
1343 assert_eq!(vec![39], v.depends_on);
1344 }
1345
1346 #[test]
1347 fn triage_tolerates_a_missing_depends_on() {
1348 let v: TriageVerdict = serde_json::from_value(serde_json::json!({
1349 "issue": 1, "worth_doing": false, "reason": "r",
1350 "complexity": "s", "risk": "high"
1351 }))
1352 .unwrap();
1353 assert!(v.depends_on.is_empty());
1354 }
1355
1356 #[test]
1357 fn review_tolerates_a_missing_findings_array() {
1358 let r: Review = serde_json::from_value(serde_json::json!({
1359 "verdict": "approve", "next_action": "merge", "summary": "fine"
1360 }))
1361 .unwrap();
1362 assert!(r.findings.is_empty());
1363 }
1364
1365 #[test]
1366 fn a_null_reason_is_an_empty_string_not_a_failure() {
1367 let v: TriageVerdict = serde_json::from_value(serde_json::json!({
1368 "issue": 1, "worth_doing": true, "reason": null,
1369 "complexity": "s", "depends_on": [], "risk": "low"
1370 }))
1371 .unwrap();
1372 assert_eq!("", v.reason);
1373 }
1374
1375 #[test]
1376 fn unknown_severity_is_an_error_not_a_silent_downgrade() {
1377 let out: Result<Finding, _> = serde_json::from_value(serde_json::json!({
1378 "severity": "showstopper-maybe", "title": "t", "detail": "d", "file": "a.rs"
1379 }));
1380 assert!(out.is_err());
1381 }
1382
1383 #[test]
1387 fn deciding_not_to_split_is_not_a_failure() {
1388 for status in [Status::Split, Status::Whole] {
1389 let mut run = IssueRun::new(1, "t");
1390 run.status = status;
1391 assert!(run.succeeded(), "{status}");
1392 }
1393 }
1394
1395 #[test]
1396 fn status_round_trips_through_json() {
1397 let run = IssueRun::new(4, "t");
1398 let text = serde_json::to_string(&run).unwrap();
1399 let back: IssueRun = serde_json::from_str(&text).unwrap();
1400 assert_eq!(Status::Pending, back.status);
1401 }
1402}
1403
1404#[cfg(test)]
1405mod body_for_prompt_tests {
1406 use super::*;
1407
1408 fn issue(body: &str) -> Issue {
1409 let mut i: Issue = serde_json::from_value(serde_json::json!({
1410 "number": 1, "title": "t", "state": "open", "url": "u"
1411 }))
1412 .expect("an issue");
1413 i.body = Some(body.to_string());
1414 i
1415 }
1416
1417 #[test]
1420 fn an_issue_that_fits_is_handed_over_whole() {
1421 let (body, cut) = issue("The guard is inverted.").body_for_prompt(60_000);
1422 assert_eq!("The guard is inverted.", body);
1423 assert!(!cut);
1424 }
1425
1426 #[test]
1430 fn a_shortened_body_says_so_in_the_text() {
1431 let long = "line of text\n".repeat(500);
1432 let (body, cut) = issue(&long).body_for_prompt(200);
1433 assert!(cut);
1434 assert!(body.contains("Shortened to fit"), "{body}");
1435 assert!(body.len() < long.len());
1436 }
1437
1438 #[test]
1441 fn a_cut_never_leaves_a_code_fence_open() {
1442 let body = format!("intro\n\n```rust\n{}\n```\n", "let x = 1;\n".repeat(200));
1443 let (out, cut) = issue(&body).body_for_prompt(120);
1444 assert!(cut);
1445 assert_eq!(0, out.matches("```").count() % 2, "{out}");
1446 }
1447
1448 #[test]
1450 fn a_cut_lands_on_a_line_boundary() {
1451 let body = "aaaa bbbb cccc\n".repeat(100);
1452 let (out, _) = issue(&body).body_for_prompt(100);
1453 let kept = out.split("\n\n[Shortened").next().expect("the kept part");
1454 assert!(kept.ends_with("cccc"), "{kept:?}");
1455 }
1456}