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 ReviewVerdict {
127 Approve = "approve" | "approved",
128 RequestChanges = "request_changes" | "changes_requested" | "request-changes",
129 }
130}
131
132impl ReviewVerdict {
133 pub fn api_event(self) -> &'static str {
135 match self {
136 ReviewVerdict::Approve => "APPROVE",
137 ReviewVerdict::RequestChanges => "REQUEST_CHANGES",
138 }
139 }
140
141 pub fn words(self) -> &'static str {
144 match self {
145 ReviewVerdict::Approve => "approve",
146 ReviewVerdict::RequestChanges => "changes requested",
147 }
148 }
149}
150
151string_enum! {
152 pub enum NextAction {
153 Merge = "merge" | "approve" | "ship",
154 FixMyself = "fix_myself" | "fix-myself" | "fix" | "self_fix",
155 HandBack = "hand_back" | "hand-back" | "handback" | "return",
156 }
157}
158
159string_enum! {
160 pub enum Action {
164 Fixed = "fixed" | "fix" | "accepted" | "done",
165 Refuted = "refuted" | "refute" | "rejected" | "disagree" | "wontfix",
166 FiledIssue = "filed_issue" | "filed-issue" | "filed" | "deferred" | "out_of_scope",
167 }
168}
169
170string_enum! {
171 pub enum Ask {
177 Implement = "implement" | "do" | "accept" | "fix",
180 Defer = "defer" | "file_issue" | "filed_issue" | "out_of_scope" | "followup",
182 Decline = "decline" | "refute" | "reject" | "disagree" | "wontfix",
184 Answer = "answer" | "question" | "reply" | "clarify",
186 Nothing = "nothing" | "none" | "no_request" | "noop" | "skip",
188 }
189}
190
191string_enum! {
192 pub enum Screened {
198 StillRelevant = "still_relevant" | "still-relevant" | "relevant" | "keep" | "file",
199 AlreadyFixed = "already_fixed" | "already-fixed" | "fixed" | "done" | "resolved",
200 NotWorthIt = "not_worth_it" | "not-worth-it" | "not_worth_doing" | "skip" | "drop" | "wontfix",
201 Duplicate = "duplicate" | "dupe" | "dup",
202 }
203}
204
205string_enum! {
206 pub enum Status {
208 Pending = "pending",
209 Abandoned = "abandoned",
210 Approved = "approved",
211 Merged = "merged",
212 Escalated = "escalated",
213 Error = "error",
214 Reviewed = "reviewed",
216 Clean = "clean",
218 Answered = "answered",
220 Split = "split",
222 Whole = "whole",
224 Moved = "moved",
228 }
229}
230
231impl Complexity {
232 pub fn rank(self) -> u8 {
233 match self {
234 Complexity::S => 0,
235 Complexity::M => 1,
236 Complexity::L => 2,
237 }
238 }
239}
240
241impl Severity {
242 pub fn rank(self) -> u8 {
246 match self {
247 Severity::Nit => 0,
248 Severity::NonBlocking => 1,
249 Severity::Blocking => 2,
250 }
251 }
252
253 pub fn graver(self, other: Self) -> Self {
259 if self.rank() >= other.rank() {
260 self
261 } else {
262 other
263 }
264 }
265}
266
267impl Risk {
268 pub fn rank(self) -> u8 {
269 match self {
270 Risk::Low => 0,
271 Risk::Med => 1,
272 Risk::High => 2,
273 }
274 }
275}
276
277pub fn de_i64<'de, D: Deserializer<'de>>(d: D) -> Result<i64, D::Error> {
284 struct V;
285 impl<'de> Visitor<'de> for V {
286 type Value = i64;
287 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
288 f.write_str("an issue number")
289 }
290 fn visit_i64<E: de::Error>(self, v: i64) -> Result<i64, E> {
291 Ok(v)
292 }
293 fn visit_u64<E: de::Error>(self, v: u64) -> Result<i64, E> {
294 Ok(v as i64)
295 }
296 fn visit_f64<E: de::Error>(self, v: f64) -> Result<i64, E> {
297 Ok(v as i64)
298 }
299 fn visit_str<E: de::Error>(self, v: &str) -> Result<i64, E> {
300 v.trim()
301 .trim_start_matches('#')
302 .parse()
303 .map_err(|_| E::custom(format!("{v} is not a number")))
304 }
305 }
306 d.deserialize_any(V)
307}
308
309fn de_i64_vec<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<i64>, D::Error> {
310 #[derive(Deserialize)]
311 struct One(#[serde(deserialize_with = "de_i64")] i64);
312 let raw = Option::<Vec<One>>::deserialize(d)?;
313 Ok(raw
314 .unwrap_or_default()
315 .into_iter()
316 .map(|One(n)| n)
317 .collect())
318}
319
320pub fn de_bool<'de, D: Deserializer<'de>>(d: D) -> Result<bool, D::Error> {
322 struct V;
323 impl<'de> Visitor<'de> for V {
324 type Value = bool;
325 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
326 f.write_str("a boolean")
327 }
328 fn visit_bool<E: de::Error>(self, v: bool) -> Result<bool, E> {
329 Ok(v)
330 }
331 fn visit_i64<E: de::Error>(self, v: i64) -> Result<bool, E> {
332 Ok(v != 0)
333 }
334 fn visit_u64<E: de::Error>(self, v: u64) -> Result<bool, E> {
335 Ok(v != 0)
336 }
337 fn visit_str<E: de::Error>(self, v: &str) -> Result<bool, E> {
338 match norm_token(v).as_str() {
339 "true" | "yes" | "y" | "1" => Ok(true),
340 "false" | "no" | "n" | "0" => Ok(false),
341 other => Err(E::custom(format!("{other} is not a boolean"))),
342 }
343 }
344 }
345 d.deserialize_any(V)
346}
347
348pub fn de_opt_i64<'de, D: Deserializer<'de>>(d: D) -> Result<Option<i64>, D::Error> {
354 Ok(match Option::<serde_json::Value>::deserialize(d)? {
355 Some(serde_json::Value::Number(n)) => n.as_i64(),
356 Some(serde_json::Value::String(s)) => s.trim().trim_start_matches('#').parse().ok(),
357 _ => None,
358 })
359}
360
361fn de_string_vec<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<String>, D::Error> {
363 Ok(Option::<Vec<String>>::deserialize(d)?.unwrap_or_default())
364}
365
366fn de_bool_default_true<'de, D: Deserializer<'de>>(d: D) -> Result<bool, D::Error> {
367 #[derive(Deserialize)]
368 struct Wrap(#[serde(deserialize_with = "de_bool")] bool);
369 Ok(Option::<Wrap>::deserialize(d)?
370 .map(|Wrap(b)| b)
371 .unwrap_or(true))
372}
373
374fn de_string<'de, D: Deserializer<'de>>(d: D) -> Result<String, D::Error> {
375 Ok(Option::<String>::deserialize(d)?.unwrap_or_default())
376}
377
378#[derive(Debug, Clone, Serialize, Deserialize)]
383pub struct TriageVerdict {
384 #[serde(deserialize_with = "de_i64")]
385 pub issue: i64,
386 #[serde(deserialize_with = "de_bool")]
387 pub worth_doing: bool,
388 #[serde(default, deserialize_with = "de_bool")]
391 pub tracker: bool,
392 #[serde(default, deserialize_with = "de_string")]
393 pub reason: String,
394 pub complexity: Complexity,
395 #[serde(default, deserialize_with = "de_i64_vec")]
396 pub depends_on: Vec<i64>,
397 pub risk: Risk,
398}
399
400#[derive(Debug, Clone, Serialize, Deserialize)]
401pub struct TriageResponse {
402 #[serde(default)]
403 pub issues: Vec<TriageVerdict>,
404}
405
406#[derive(Debug, Clone, Serialize, Deserialize)]
408pub struct ScreenVerdict {
409 #[serde(deserialize_with = "de_i64")]
414 pub entry: i64,
415 pub verdict: Screened,
416 #[serde(default, deserialize_with = "de_string")]
417 pub title: String,
418 #[serde(default, deserialize_with = "de_string")]
419 pub reason: String,
420 #[serde(default, deserialize_with = "de_opt_i64")]
426 pub duplicate_of_issue: Option<i64>,
427 #[serde(default, deserialize_with = "de_opt_i64")]
429 pub duplicate_of_entry: Option<i64>,
430}
431
432impl ScreenVerdict {
433 pub fn names_a_duplicate(&self) -> bool {
435 self.duplicate_of_issue.is_some() || self.duplicate_of_entry.is_some()
436 }
437}
438
439#[derive(Debug, Clone, Serialize, Deserialize)]
440pub struct ScreenResponse {
441 #[serde(default)]
442 pub entries: Vec<ScreenVerdict>,
443}
444
445#[derive(Debug, Clone, Serialize, Deserialize)]
451pub struct SplitScreen {
452 #[serde(deserialize_with = "de_i64")]
455 pub item: i64,
456 #[serde(deserialize_with = "de_bool")]
457 pub split: bool,
458 #[serde(default, deserialize_with = "de_string")]
459 pub reason: String,
460}
461
462#[derive(Debug, Clone, Serialize, Deserialize)]
463pub struct SplitScreenDoc {
464 #[serde(default)]
465 pub items: Vec<SplitScreen>,
466}
467
468#[derive(Debug, Clone, Default, Serialize, Deserialize)]
470pub struct SplitPart {
471 #[serde(default, deserialize_with = "de_string")]
472 pub title: String,
473 #[serde(default, deserialize_with = "de_string")]
475 pub body: String,
476 #[serde(default, deserialize_with = "de_string_vec")]
479 pub files: Vec<String>,
480}
481
482#[derive(Debug, Clone, Default, Serialize, Deserialize)]
488pub struct SplitProposal {
489 #[serde(default, deserialize_with = "de_bool")]
490 pub should_split: bool,
491 #[serde(default, deserialize_with = "de_string")]
492 pub reason: String,
493 #[serde(default, deserialize_with = "de_bool")]
497 pub stacked: bool,
498 #[serde(default)]
499 pub parts: Vec<SplitPart>,
500}
501
502#[derive(Debug, Clone, Default, Serialize, Deserialize)]
504pub struct SplitCheck {
505 #[serde(default, deserialize_with = "de_bool")]
506 pub accept: bool,
507 #[serde(default, deserialize_with = "de_bool")]
508 pub stacked: bool,
509 #[serde(default, deserialize_with = "de_i64_vec")]
511 pub strike: Vec<i64>,
512 #[serde(default, deserialize_with = "de_string")]
513 pub reasoning: String,
514}
515
516#[derive(Debug, Clone, Serialize, Deserialize)]
518pub struct CommentVerdict {
519 #[serde(default, deserialize_with = "de_string")]
524 pub ref_id: String,
525 pub ask: Ask,
526 #[serde(default, deserialize_with = "de_string")]
529 pub request: String,
530 #[serde(default, deserialize_with = "de_string")]
533 pub reasoning: String,
534 #[serde(deserialize_with = "de_bool")]
537 pub unambiguous: bool,
538 #[serde(default)]
539 pub new_issue_title: Option<String>,
540 #[serde(default)]
541 pub new_issue_body: Option<String>,
542}
543
544#[derive(Debug, Clone, Serialize, Deserialize)]
545pub struct CheckinDoc {
546 #[serde(default)]
547 pub verdicts: Vec<CommentVerdict>,
548}
549
550#[derive(Debug, Clone, Serialize, Deserialize)]
552pub struct CommentCheck {
553 #[serde(default, deserialize_with = "de_string")]
554 pub ref_id: String,
555 #[serde(deserialize_with = "de_bool")]
556 pub agrees: bool,
557 pub ask: Ask,
562 #[serde(deserialize_with = "de_bool")]
563 pub unambiguous: bool,
564 #[serde(default, deserialize_with = "de_string")]
565 pub reasoning: String,
566}
567
568#[derive(Debug, Clone, Serialize, Deserialize)]
569pub struct CheckDoc {
570 #[serde(default)]
571 pub checks: Vec<CommentCheck>,
572}
573
574#[derive(Debug, Clone, Serialize, Deserialize)]
576pub struct FixOutcome {
577 #[serde(default, deserialize_with = "de_string")]
578 pub ref_id: String,
579 #[serde(deserialize_with = "de_bool")]
583 pub changed: bool,
584 #[serde(default, deserialize_with = "de_string")]
587 pub summary: String,
588 #[serde(default)]
591 pub files: Vec<String>,
592}
593
594#[derive(Debug, Clone, Serialize, Deserialize)]
595pub struct FixReport {
596 #[serde(default)]
597 pub done: Vec<FixOutcome>,
598}
599
600#[derive(Debug, Clone, Default, Serialize, Deserialize)]
612pub struct Answered {
613 #[serde(default)]
614 pub version: u32,
615 #[serde(default)]
616 pub seen: BTreeMap<String, String>,
617}
618
619string_enum! {
620 pub enum QuestionKind {
622 Answer = "answer" | "factual" | "fact" | "spar",
625 Yours = "yours" | "person" | "decision" | "human" | "unverified",
628 }
629}
630
631#[derive(Debug, Clone, Serialize, Deserialize)]
633pub struct Question {
634 #[serde(default, deserialize_with = "de_string")]
636 pub ref_id: String,
637 #[serde(default, deserialize_with = "de_string")]
639 pub question: String,
640 pub kind: QuestionKind,
641 #[serde(default, deserialize_with = "de_string")]
644 pub answer: String,
645 #[serde(default, deserialize_with = "de_string")]
647 pub evidence: String,
648 #[serde(default, deserialize_with = "de_string")]
649 pub reasoning: String,
650}
651
652#[derive(Debug, Clone, Serialize, Deserialize)]
653pub struct AnswerDoc {
654 #[serde(default)]
655 pub questions: Vec<Question>,
656}
657
658#[derive(Debug, Clone, Serialize, Deserialize)]
660pub struct QuestionCheck {
661 #[serde(default, deserialize_with = "de_string")]
663 pub id: String,
664 #[serde(deserialize_with = "de_bool")]
667 pub agrees: bool,
668 pub kind: QuestionKind,
671 #[serde(default, deserialize_with = "de_string")]
672 pub reasoning: String,
673}
674
675#[derive(Debug, Clone, Serialize, Deserialize)]
676pub struct AnswerCheckDoc {
677 #[serde(default)]
678 pub checks: Vec<QuestionCheck>,
679 #[serde(default, deserialize_with = "de_string_vec")]
681 pub missed: Vec<String>,
682}
683
684#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
692pub struct AnswerRecord {
693 #[serde(default)]
694 pub version: u32,
695 #[serde(default)]
697 pub judged: BTreeMap<String, String>,
698 #[serde(default)]
700 pub automatic: u32,
701}
702
703#[derive(Debug, Clone, Serialize, Deserialize)]
704pub struct Finding {
705 pub severity: Severity,
706 #[serde(default, deserialize_with = "de_string")]
707 pub title: String,
708 #[serde(default, deserialize_with = "de_string")]
709 pub detail: String,
710 #[serde(default, deserialize_with = "de_string")]
711 pub file: String,
712 #[serde(default = "yes", deserialize_with = "de_bool_default_true")]
715 pub in_scope: bool,
716
717 #[serde(default)]
725 pub problem: Option<String>,
726 #[serde(default)]
728 pub reproduction: Option<String>,
729 #[serde(default)]
731 pub impact: Option<String>,
732 #[serde(default)]
734 pub expected: Option<String>,
735}
736
737impl Default for Finding {
738 fn default() -> Self {
745 Self {
746 severity: Severity::Nit,
747 title: String::new(),
748 detail: String::new(),
749 file: String::new(),
750 in_scope: true,
751 problem: None,
752 reproduction: None,
753 impact: None,
754 expected: None,
755 }
756 }
757}
758
759impl Finding {
760 pub fn report_sections(&self) -> Vec<(&'static str, &str)> {
763 [
764 ("Problem", self.problem.as_deref()),
765 ("Reproduction", self.reproduction.as_deref()),
766 ("Impact", self.impact.as_deref()),
767 ("Expected behavior", self.expected.as_deref()),
768 ]
769 .into_iter()
770 .filter_map(|(heading, text)| {
771 text.map(str::trim)
772 .filter(|t| !t.is_empty())
773 .map(|t| (heading, t))
774 })
775 .collect()
776 }
777}
778
779fn yes() -> bool {
780 true
781}
782
783impl Finding {
784 pub fn blocks(&self) -> bool {
785 self.severity == Severity::Blocking && self.in_scope
786 }
787
788 pub fn where_at(&self) -> &str {
789 if self.file.trim().is_empty() {
790 "general"
791 } else {
792 self.file.trim()
793 }
794 }
795}
796
797#[derive(Debug, Clone, Serialize, Deserialize)]
798pub struct Review {
799 pub verdict: Verdict,
800 pub next_action: NextAction,
801 #[serde(default, deserialize_with = "de_string")]
802 pub summary: String,
803 #[serde(default)]
804 pub findings: Vec<Finding>,
805 #[serde(default, skip_serializing_if = "Vec::is_empty")]
808 pub criteria: Vec<CriterionStatus>,
809}
810
811string_enum! {
812 pub enum Mark {
815 Met = "met" | "done",
816 NotMet = "not_met" | "not_done" | "unmet",
817 NeedsPerson = "needs_person" | "needs_a_person" | "manual",
818 }
819}
820
821#[derive(Debug, Clone, Serialize, Deserialize)]
823pub struct CriterionStatus {
824 pub number: u32,
825 pub status: Mark,
826 #[serde(default, deserialize_with = "de_string")]
827 pub reason: String,
828}
829
830#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
832pub struct Ruled {
833 pub raw: String,
835 #[serde(default)]
838 pub line: usize,
839 pub text: String,
840 pub status: Option<Mark>,
842 #[serde(default)]
843 pub reason: String,
844}
845
846#[derive(Debug, Clone, Serialize, Deserialize)]
847pub struct Disposition {
848 #[serde(default, deserialize_with = "de_string")]
849 pub title: String,
850 #[serde(default, deserialize_with = "de_string")]
854 pub file: String,
855 pub action: Action,
856 #[serde(default, deserialize_with = "de_string")]
857 pub reasoning: String,
858 #[serde(default)]
859 pub new_issue_title: Option<String>,
860 #[serde(default)]
861 pub new_issue_body: Option<String>,
862}
863
864#[derive(Debug, Clone, Serialize, Deserialize)]
872pub struct OwnFix {
873 #[serde(default, deserialize_with = "de_string")]
874 pub title: String,
875 #[serde(default, deserialize_with = "de_string")]
878 pub file: String,
879 #[serde(deserialize_with = "de_bool")]
880 pub fixed: bool,
881 #[serde(default, deserialize_with = "de_string")]
882 pub reason: String,
883}
884
885#[derive(Debug, Clone, Serialize, Deserialize)]
886pub struct OwnFixDoc {
887 #[serde(default, deserialize_with = "de_string")]
888 pub summary: String,
889 #[serde(default)]
890 pub fixes: Vec<OwnFix>,
891}
892
893#[derive(Debug, Clone, Serialize, Deserialize)]
900pub struct Adjudication {
901 #[serde(default, deserialize_with = "de_string")]
902 pub title: String,
903 #[serde(default, deserialize_with = "de_string")]
904 pub file: String,
905 #[serde(deserialize_with = "de_bool")]
908 pub agrees: bool,
909 pub severity: Severity,
911 #[serde(default, deserialize_with = "de_string")]
912 pub reasoning: String,
913}
914
915#[derive(Debug, Clone, Serialize, Deserialize)]
916pub struct AdjudicationDoc {
917 #[serde(default)]
918 pub verdicts: Vec<Adjudication>,
919}
920
921string_enum! {
922 pub enum Ruling {
924 Fixed = "fixed" | "resolved" | "addressed" | "done",
926 Rebutted = "rebutted" | "refuted" | "answered" | "withdrawn" | "not_a_bug",
929 Open = "open" | "still_open" | "unresolved" | "stands" | "unfixed",
932 }
933}
934
935#[derive(Debug, Clone, Serialize, Deserialize)]
937pub struct RecheckRuling {
938 #[serde(deserialize_with = "de_i64")]
942 pub index: i64,
943 pub outcome: Ruling,
944 #[serde(default, deserialize_with = "de_string")]
945 pub reasoning: String,
946}
947
948#[derive(Debug, Clone, Default, Serialize, Deserialize)]
951pub struct RecheckDoc {
952 #[serde(default, deserialize_with = "de_string")]
953 pub summary: String,
954 #[serde(default)]
955 pub rulings: Vec<RecheckRuling>,
956 #[serde(default)]
957 pub findings: Vec<Finding>,
958}
959
960#[derive(Debug, Clone, Default, Serialize, Deserialize)]
973pub struct Idea {
974 #[serde(default, deserialize_with = "de_string")]
975 pub title: String,
976 #[serde(default, deserialize_with = "de_string_vec")]
978 pub combines: Vec<String>,
979 #[serde(default, deserialize_with = "de_string")]
980 pub how_it_works: String,
981 #[serde(default, deserialize_with = "de_string")]
983 pub why_new: String,
984 #[serde(default, deserialize_with = "de_string")]
985 pub enables: String,
986 #[serde(default, deserialize_with = "de_string")]
987 pub risks: String,
988 #[serde(default, deserialize_with = "de_string")]
990 pub first_experiment: String,
991}
992
993#[derive(Debug, Clone, Default, Serialize, Deserialize)]
994pub struct IdeasDoc {
995 #[serde(default)]
996 pub ideas: Vec<Idea>,
997}
998
999string_enum! {
1000 pub enum CrossKind {
1002 Build = "build" | "extend" | "improve" | "combine",
1003 Challenge = "challenge" | "reject" | "exists" | "object",
1004 Keep = "keep" | "agree" | "accept" | "fine",
1005 }
1006}
1007
1008#[derive(Debug, Clone, Serialize, Deserialize)]
1010pub struct CrossVerdict {
1011 #[serde(default, deserialize_with = "de_i64")]
1014 pub idea: i64,
1015 pub verdict: CrossKind,
1016 #[serde(default, deserialize_with = "de_string")]
1017 pub reason: String,
1018 #[serde(default)]
1020 pub build: Option<Idea>,
1021}
1022
1023#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1024pub struct CrossDoc {
1025 #[serde(default)]
1026 pub verdicts: Vec<CrossVerdict>,
1027}
1028
1029#[derive(Debug, Clone, Serialize, Deserialize)]
1031pub struct Defence {
1032 #[serde(default, deserialize_with = "de_i64")]
1033 pub idea: i64,
1034 #[serde(deserialize_with = "de_bool")]
1036 pub stands: bool,
1037 #[serde(default, deserialize_with = "de_string")]
1038 pub reply: String,
1039}
1040
1041#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1044pub struct ConvergeDoc {
1045 #[serde(default)]
1046 pub defences: Vec<Defence>,
1047 #[serde(default, deserialize_with = "de_i64_vec")]
1049 pub ranking: Vec<i64>,
1050}
1051
1052#[derive(Debug, Clone)]
1054pub struct Judged {
1055 pub finding: Finding,
1056 pub raised_by: String,
1058 pub standing: Standing,
1060 pub counterpoint: Option<String>,
1062 pub defence: Option<String>,
1067 pub rated: Option<Severity>,
1071}
1072
1073string_enum! {
1074 pub enum Standing {
1077 Corroborated = "corroborated" | "both",
1079 Confirmed = "confirmed",
1081 Disputed = "disputed",
1085 Withdrawn = "withdrawn",
1087 Unverified = "unverified" | "one_reviewer",
1089 }
1090}
1091
1092#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1101pub struct Implementation {
1102 #[serde(default, deserialize_with = "de_bool")]
1104 pub not_worth_doing: bool,
1105 #[serde(default, deserialize_with = "de_string")]
1108 pub reason: String,
1109 #[serde(default, deserialize_with = "de_string")]
1111 pub summary: String,
1112 #[serde(default, deserialize_with = "de_string")]
1115 pub problem: String,
1116 #[serde(default)]
1118 pub changes: Vec<String>,
1119 #[serde(default)]
1121 pub testing: Vec<String>,
1122 #[serde(default)]
1125 pub notes: Option<String>,
1126 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1130 pub criteria: Vec<CriterionStatus>,
1131}
1132
1133#[derive(Debug, Clone, Serialize, Deserialize)]
1134pub struct ResponseDoc {
1135 #[serde(default, deserialize_with = "de_string")]
1136 pub summary: String,
1137 #[serde(default)]
1138 pub dispositions: Vec<Disposition>,
1139}
1140
1141#[derive(Debug, Clone, Serialize, Deserialize)]
1146pub struct PlanItem {
1147 pub issue: i64,
1148 pub title: String,
1149 pub complexity: Complexity,
1150 pub risk: Risk,
1151 pub depends_on: Vec<i64>,
1152 pub reason: String,
1153}
1154
1155#[derive(Debug, Clone, Serialize, Deserialize)]
1156pub struct SkippedItem {
1157 pub issue: i64,
1158 pub title: String,
1159 pub reasons: BTreeMap<String, String>,
1161 #[serde(default)]
1169 pub tracker: bool,
1170}
1171
1172#[derive(Debug, Clone, Serialize, Deserialize)]
1173pub struct ContestedItem {
1174 pub issue: i64,
1175 pub title: String,
1176 pub positions: BTreeMap<String, String>,
1178 pub reasons: BTreeMap<String, String>,
1179 #[serde(default, skip_serializing_if = "Option::is_none")]
1180 pub note: Option<String>,
1181}
1182
1183#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1190pub struct Contested {
1191 #[serde(default)]
1192 pub title: String,
1193 #[serde(default)]
1195 pub positions: BTreeMap<String, String>,
1196 #[serde(default)]
1197 pub reasons: BTreeMap<String, String>,
1198}
1199
1200#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1201pub struct Plan {
1202 #[serde(default)]
1203 pub order: Vec<PlanItem>,
1204 #[serde(default)]
1205 pub skipped: Vec<SkippedItem>,
1206 #[serde(default)]
1207 pub contested: Vec<ContestedItem>,
1208}
1209
1210string_enum! {
1211 pub enum Settled {
1225 Refuted = "refuted" | "refute" | "rejected",
1226 Filed = "filed" | "filed_issue" | "filed-issue" | "out_of_scope",
1227 Dropped = "dropped" | "not_filed" | "not-filed" | "unfiled",
1228 Fixed = "fixed" | "fix" | "changed",
1229 }
1230}
1231
1232impl Default for Settled {
1233 fn default() -> Self {
1235 Settled::Refuted
1236 }
1237}
1238
1239#[derive(Debug, Clone, PartialEq, Eq)]
1246pub enum Followup {
1247 Recorded(String),
1250 Covered(String),
1254 Dropped(&'static str),
1257 Failed,
1260}
1261
1262impl Followup {
1263 pub fn url(&self) -> Option<&str> {
1268 match self {
1269 Followup::Recorded(url) => Some(url),
1270 _ => None,
1271 }
1272 }
1273}
1274
1275#[derive(Debug, Clone, Serialize, Deserialize)]
1276pub struct LedgerEntry {
1277 pub title: String,
1278 pub file: String,
1279 pub reasoning: String,
1280 pub round: u32,
1281 #[serde(default)]
1282 pub reraised: u32,
1283 #[serde(default)]
1284 pub outcome: Settled,
1285}
1286
1287pub type Ledger = BTreeMap<String, LedgerEntry>;
1291
1292#[derive(Debug, Clone, Serialize, Deserialize)]
1293pub struct Dispute {
1294 pub title: String,
1295 #[serde(default, deserialize_with = "de_string")]
1296 pub file: String,
1297 pub reasoning: String,
1298}
1299
1300#[derive(Debug, Clone, Serialize, Deserialize)]
1302pub struct IssueRun {
1303 pub issue: i64,
1304 pub title: String,
1305 pub status: Status,
1306 #[serde(default, skip_serializing_if = "Option::is_none")]
1307 pub pr: Option<String>,
1308 #[serde(default)]
1309 pub rounds: u32,
1310 #[serde(default)]
1311 pub disputes: Vec<Dispute>,
1312 #[serde(default)]
1313 pub filed: Vec<String>,
1314 #[serde(default)]
1323 pub noted: Vec<Finding>,
1324 #[serde(default)]
1325 pub notes: Vec<String>,
1326 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1330 pub criteria: Vec<Ruled>,
1331 #[serde(skip)]
1334 pub ticks_criteria: bool,
1335 #[serde(skip)]
1338 pub followup_writes_uncertain: bool,
1339}
1340
1341impl IssueRun {
1342 pub fn new(issue: i64, title: impl Into<String>) -> Self {
1343 Self {
1344 issue,
1345 title: title.into(),
1346 status: Status::Pending,
1347 pr: None,
1348 rounds: 0,
1349 disputes: Vec::new(),
1350 filed: Vec::new(),
1351 noted: Vec::new(),
1352 notes: Vec::new(),
1353 criteria: Vec::new(),
1354 ticks_criteria: false,
1355 followup_writes_uncertain: false,
1356 }
1357 }
1358
1359 pub fn succeeded(&self) -> bool {
1364 matches!(
1365 self.status,
1366 Status::Merged
1367 | Status::Approved
1368 | Status::Abandoned
1369 | Status::Reviewed
1370 | Status::Clean
1371 | Status::Answered
1372 | Status::Split
1376 | Status::Whole
1377 )
1378 }
1379}
1380
1381#[derive(Debug, Clone, Serialize, Deserialize)]
1383pub struct PersistedState {
1384 pub version: u32,
1385 #[serde(default)]
1387 pub checkpoint: u64,
1388 pub round: u32,
1389 pub next_actor: String,
1390 pub status: Status,
1391 #[serde(default, skip_serializing_if = "String::is_empty")]
1393 pub pr_head: String,
1394 #[serde(default)]
1395 pub ledger: Ledger,
1396 #[serde(default)]
1397 pub filed: Vec<String>,
1398 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1399 pub open_findings: Vec<Finding>,
1400 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1401 pub disputes: Vec<Dispute>,
1402 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1403 pub noted: Vec<Finding>,
1404}
1405
1406pub const STATE_VERSION: u32 = 2;
1407
1408#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1413pub struct RecordedFinding {
1414 pub title: String,
1415 #[serde(default)]
1416 pub file: String,
1417 pub severity: Severity,
1418 #[serde(default)]
1419 pub detail: String,
1420 #[serde(default = "yes")]
1421 pub in_scope: bool,
1422 #[serde(default)]
1423 pub raised_by: String,
1424 pub standing: Standing,
1425 #[serde(default, skip_serializing_if = "Option::is_none")]
1426 pub counterpoint: Option<String>,
1427 #[serde(default, skip_serializing_if = "Option::is_none")]
1428 pub defence: Option<String>,
1429}
1430
1431impl RecordedFinding {
1432 pub fn blocks(&self) -> bool {
1433 self.severity == Severity::Blocking && self.in_scope
1434 }
1435
1436 pub fn where_at(&self) -> &str {
1437 if self.file.trim().is_empty() {
1438 "general"
1439 } else {
1440 self.file.trim()
1441 }
1442 }
1443
1444 pub fn to_judged(&self) -> Judged {
1447 Judged {
1448 finding: Finding {
1449 severity: self.severity,
1450 title: self.title.clone(),
1451 detail: self.detail.clone(),
1452 file: self.file.clone(),
1453 in_scope: self.in_scope,
1454 ..Finding::default()
1455 },
1456 raised_by: self.raised_by.clone(),
1457 standing: self.standing,
1458 counterpoint: self.counterpoint.clone(),
1459 defence: self.defence.clone(),
1460 rated: None,
1461 }
1462 }
1463}
1464
1465impl From<&Judged> for RecordedFinding {
1466 fn from(j: &Judged) -> Self {
1467 Self {
1468 title: j.finding.title.clone(),
1469 file: j.finding.file.clone(),
1470 severity: j.finding.severity,
1471 detail: j.finding.detail.clone(),
1472 in_scope: j.finding.in_scope,
1473 raised_by: j.raised_by.clone(),
1474 standing: j.standing,
1475 counterpoint: j.counterpoint.clone(),
1476 defence: j.defence.clone(),
1477 }
1478 }
1479}
1480
1481#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1487pub struct ReviewRecord {
1488 pub version: u32,
1489 pub head: String,
1492 pub reviewed_at: String,
1497 #[serde(default)]
1498 pub findings: Vec<RecordedFinding>,
1499 #[serde(default)]
1501 pub rechecks: u32,
1502 #[serde(default, skip_serializing_if = "Option::is_none")]
1504 pub verdict: Option<ReviewVerdict>,
1505 #[serde(default)]
1509 pub posted: bool,
1510}
1511
1512pub const REVIEW_RECORD_VERSION: u32 = 1;
1513
1514impl ReviewRecord {
1515 pub fn short_head(&self) -> &str {
1516 let end = self.head.len().min(7);
1517 &self.head[..end]
1518 }
1519
1520 pub fn open_points(&self) -> impl Iterator<Item = &RecordedFinding> {
1522 self.findings
1523 .iter()
1524 .filter(|f| f.standing != Standing::Withdrawn)
1525 }
1526}
1527
1528#[derive(Debug, Clone, PartialEq, Eq)]
1534pub struct InlineComment {
1535 pub path: String,
1536 pub line: u32,
1537 pub start_line: Option<u32>,
1538 pub body: String,
1539}
1540
1541#[derive(Debug, Clone, Deserialize)]
1546pub struct Label {
1547 #[serde(default)]
1548 pub name: String,
1549}
1550
1551#[derive(Debug, Clone, Deserialize, Default)]
1552pub struct Author {
1553 #[serde(default)]
1554 pub login: String,
1555}
1556
1557pub fn login_of(author: Option<&Author>) -> &str {
1560 match author.map(|a| a.login.trim()) {
1561 Some(login) if !login.is_empty() => login,
1562 _ => "ghost",
1563 }
1564}
1565
1566#[derive(Debug, Clone, Deserialize, Default)]
1569#[serde(rename_all = "camelCase")]
1570pub struct IssueComment {
1571 #[serde(default)]
1573 pub author: Option<Author>,
1574 #[serde(default)]
1575 pub author_association: String,
1576 #[serde(default)]
1578 pub viewer_did_author: bool,
1579 #[serde(default)]
1580 pub body: String,
1581 #[serde(default)]
1582 pub created_at: String,
1583 #[serde(default)]
1584 pub is_minimized: bool,
1585}
1586
1587impl IssueComment {
1588 pub fn login(&self) -> &str {
1589 login_of(self.author.as_ref())
1590 }
1591}
1592
1593#[derive(Debug, Clone, Deserialize)]
1594pub struct Issue {
1595 pub number: i64,
1596 #[serde(default)]
1597 pub title: String,
1598 #[serde(default)]
1599 pub body: Option<String>,
1600 #[serde(default)]
1601 pub state: String,
1602 #[serde(default, rename = "stateReason")]
1610 pub state_reason: Option<String>,
1611 #[serde(default)]
1612 pub url: String,
1613 #[serde(default)]
1614 pub labels: Vec<Label>,
1615 #[serde(default)]
1617 pub author: Option<Author>,
1618 #[serde(default)]
1621 pub comments: Vec<IssueComment>,
1622}
1623
1624impl Issue {
1625 pub fn body_text(&self) -> &str {
1626 self.body.as_deref().unwrap_or("")
1627 }
1628
1629 pub fn body_for_prompt(&self, max: usize) -> (String, bool) {
1641 let body = self.body_text().trim();
1642 if body.chars().count() <= max {
1643 return (body.to_string(), false);
1644 }
1645 let clipped: String = body.chars().take(max).collect();
1646 let mut kept = match clipped.rfind('\n') {
1647 Some(at) => clipped[..at].to_string(),
1648 None => clipped,
1649 };
1650 if kept.matches("```").count() % 2 == 1 {
1651 kept.push_str("\n```");
1652 }
1653 kept.push_str("\n\n[Shortened to fit. The rest of this issue was not included.]");
1654 (kept, true)
1655 }
1656
1657 pub fn is_closed(&self) -> bool {
1658 self.state.eq_ignore_ascii_case("closed")
1659 }
1660
1661 pub fn closed_as_completed(&self) -> bool {
1668 self.is_closed() && !self.closed_as_not_planned()
1669 }
1670
1671 pub fn closed_as_not_planned(&self) -> bool {
1672 self.is_closed()
1673 && self
1674 .state_reason
1675 .as_deref()
1676 .is_some_and(|reason| reason.eq_ignore_ascii_case("not_planned"))
1677 }
1678}
1679
1680#[derive(Debug, Clone, Deserialize)]
1681pub struct PrRef {
1682 pub number: i64,
1683 #[serde(default)]
1684 pub url: String,
1685 #[serde(default)]
1686 pub title: String,
1687}
1688
1689#[derive(Debug, Clone, Deserialize)]
1690pub struct IssueRef {
1691 pub number: i64,
1692 #[serde(default)]
1695 pub url: String,
1696}
1697
1698#[derive(Debug, Clone, Default, Deserialize)]
1704#[serde(rename_all = "camelCase")]
1705pub struct PrRow {
1706 pub number: i64,
1707 #[serde(default)]
1708 pub title: String,
1709 #[serde(default)]
1710 pub changed_files: i64,
1711 #[serde(default)]
1712 pub additions: i64,
1713 #[serde(default)]
1714 pub deletions: i64,
1715}
1716
1717impl PrRow {
1718 pub fn size(&self) -> String {
1720 format!(
1721 "{} file(s), +{} -{}",
1722 self.changed_files, self.additions, self.deletions
1723 )
1724 }
1725}
1726
1727#[derive(Debug, Clone, Deserialize)]
1728#[serde(rename_all = "camelCase")]
1729pub struct PrView {
1730 pub number: i64,
1731 #[serde(default)]
1732 pub url: String,
1733 #[serde(default)]
1734 pub title: String,
1735 #[serde(default)]
1738 pub body: String,
1739 #[serde(default)]
1740 pub head_ref_name: String,
1741 #[serde(default)]
1742 pub base_ref_name: String,
1743 #[serde(default)]
1744 pub state: String,
1745 #[serde(default)]
1746 pub closing_issues_references: Vec<IssueRef>,
1747 #[serde(default)]
1750 pub is_cross_repository: bool,
1751 #[serde(default)]
1755 pub head_repository_owner: Option<Author>,
1756 #[serde(default)]
1758 pub head_repository: Option<HeadRepository>,
1759}
1760
1761#[derive(Debug, Clone, Default, Deserialize)]
1762pub struct HeadRepository {
1763 #[serde(default)]
1764 pub name: String,
1765}
1766
1767pub const PR_SWEEP_FIELDS: &str =
1770 "number,title,headRefOid,updatedAt,author,isDraft,isCrossRepository,reviewRequests,assignees,state";
1771
1772#[derive(Debug, Clone, Default, Deserialize)]
1775#[serde(rename_all = "camelCase")]
1776pub struct PrSweepRow {
1777 pub number: i64,
1778 #[serde(default)]
1779 pub title: String,
1780 #[serde(default)]
1781 pub head_ref_oid: String,
1782 #[serde(default)]
1783 pub updated_at: String,
1784 #[serde(default)]
1785 pub author: Option<Author>,
1786 #[serde(default)]
1787 pub is_draft: bool,
1788 #[serde(default)]
1789 pub is_cross_repository: bool,
1790 #[serde(default)]
1791 pub review_requests: Vec<Login>,
1792 #[serde(default)]
1793 pub assignees: Vec<Login>,
1794 #[serde(default)]
1796 pub state: String,
1797}
1798
1799#[derive(Debug, Clone, Default, Deserialize)]
1803pub struct Login {
1804 #[serde(default)]
1805 pub login: String,
1806 #[serde(default)]
1808 pub slug: String,
1809}
1810
1811#[derive(Debug, Clone, Default)]
1814pub struct ReviewRequested {
1815 pub at: String,
1816 pub who: Login,
1817}
1818
1819#[derive(Debug, Clone, Default, PartialEq, Eq)]
1823pub struct AssignedIssue {
1824 pub number: i64,
1825 pub title: String,
1826 pub assignees: Vec<String>,
1828 pub assigned: Vec<(String, String)>,
1830}
1831
1832impl AssignedIssue {
1833 pub fn newest_for(&self, viewer: &str) -> Option<String> {
1837 let same = |login: &str| crate::comments::same_login(login, viewer);
1838 if !self.assignees.iter().any(|a| same(a)) {
1839 return None;
1840 }
1841 self.assigned
1842 .iter()
1843 .filter(|(_, who)| same(who))
1844 .filter_map(|(at, _)| crate::clock::parse_rfc3339(at).map(|t| (t, at)))
1845 .max_by_key(|(t, _)| *t)
1846 .map(|(_, at)| at.clone())
1847 }
1848}
1849
1850#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1853#[serde(rename_all = "lowercase")]
1854pub enum ItemKind {
1855 Issue,
1856 Pr,
1857}
1858
1859impl std::fmt::Display for ItemKind {
1860 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1861 f.write_str(match self {
1862 ItemKind::Issue => "issue",
1863 ItemKind::Pr => "pull request",
1864 })
1865 }
1866}
1867
1868impl PrView {
1869 pub fn is_open(&self) -> bool {
1870 self.state.eq_ignore_ascii_case("open")
1871 }
1872}
1873
1874#[derive(Debug, Clone, PartialEq, Eq)]
1882pub struct LiveHead {
1883 pub pull: String,
1885 pub branch: Option<String>,
1888}
1889
1890impl LiveHead {
1891 pub fn settled(&self) -> Option<&str> {
1893 match &self.branch {
1894 Some(branch) if !branch.eq_ignore_ascii_case(&self.pull) => None,
1895 _ => Some(&self.pull),
1896 }
1897 }
1898
1899 pub fn moved_from(&self, reviewed: &str) -> Option<&str> {
1902 self.branch
1903 .as_deref()
1904 .filter(|branch| !branch.eq_ignore_ascii_case(reviewed))
1905 .or_else(|| (!self.pull.eq_ignore_ascii_case(reviewed)).then_some(self.pull.as_str()))
1906 }
1907}
1908
1909#[cfg(test)]
1910mod tests {
1911 use super::*;
1912
1913 #[test]
1914 fn severity_accepts_the_canonical_spelling() {
1915 assert_eq!(
1916 Some(Severity::NonBlocking),
1917 Severity::parse_lenient("non-blocking")
1918 );
1919 }
1920
1921 #[test]
1922 fn severity_accepts_near_misses() {
1923 for text in ["NonBlocking", "non_blocking", " NON-BLOCKING ", "minor"] {
1924 assert_eq!(
1925 Some(Severity::NonBlocking),
1926 Severity::parse_lenient(text),
1927 "{text}"
1928 );
1929 }
1930 }
1931
1932 #[test]
1933 fn severity_rejects_nonsense() {
1934 assert_eq!(None, Severity::parse_lenient("catastrophic-ish"));
1935 }
1936
1937 #[test]
1938 fn complexity_ordering_is_cheapest_first() {
1939 assert!(Complexity::S.rank() < Complexity::M.rank());
1940 assert!(Complexity::M.rank() < Complexity::L.rank());
1941 }
1942
1943 #[test]
1944 fn finding_defaults_to_in_scope() {
1945 let f: Finding = serde_json::from_value(serde_json::json!({
1946 "severity": "blocking", "title": "t", "detail": "d", "file": "a.rs"
1947 }))
1948 .unwrap();
1949 assert!(f.in_scope);
1950 assert!(f.blocks());
1951 }
1952
1953 #[test]
1954 fn out_of_scope_blocking_does_not_block() {
1955 let f: Finding = serde_json::from_value(serde_json::json!({
1956 "severity": "blocking", "title": "t", "detail": "d",
1957 "file": "a.rs", "in_scope": false
1958 }))
1959 .unwrap();
1960 assert!(!f.blocks());
1961 }
1962
1963 #[test]
1964 fn triage_tolerates_a_quoted_issue_number() {
1965 let v: TriageVerdict = serde_json::from_value(serde_json::json!({
1966 "issue": "#42", "worth_doing": "yes", "reason": "r",
1967 "complexity": "medium", "depends_on": ["39"], "risk": "low"
1968 }))
1969 .unwrap();
1970 assert_eq!(42, v.issue);
1971 assert!(v.worth_doing);
1972 assert_eq!(Complexity::M, v.complexity);
1973 assert_eq!(vec![39], v.depends_on);
1974 }
1975
1976 #[test]
1977 fn triage_tolerates_a_missing_depends_on() {
1978 let v: TriageVerdict = serde_json::from_value(serde_json::json!({
1979 "issue": 1, "worth_doing": false, "reason": "r",
1980 "complexity": "s", "risk": "high"
1981 }))
1982 .unwrap();
1983 assert!(v.depends_on.is_empty());
1984 }
1985
1986 #[test]
1987 fn review_tolerates_a_missing_findings_array() {
1988 let r: Review = serde_json::from_value(serde_json::json!({
1989 "verdict": "approve", "next_action": "merge", "summary": "fine"
1990 }))
1991 .unwrap();
1992 assert!(r.findings.is_empty());
1993 }
1994
1995 #[test]
1996 fn a_null_reason_is_an_empty_string_not_a_failure() {
1997 let v: TriageVerdict = serde_json::from_value(serde_json::json!({
1998 "issue": 1, "worth_doing": true, "reason": null,
1999 "complexity": "s", "depends_on": [], "risk": "low"
2000 }))
2001 .unwrap();
2002 assert_eq!("", v.reason);
2003 }
2004
2005 #[test]
2006 fn unknown_severity_is_an_error_not_a_silent_downgrade() {
2007 let out: Result<Finding, _> = serde_json::from_value(serde_json::json!({
2008 "severity": "showstopper-maybe", "title": "t", "detail": "d", "file": "a.rs"
2009 }));
2010 assert!(out.is_err());
2011 }
2012
2013 #[test]
2017 fn deciding_not_to_split_is_not_a_failure() {
2018 for status in [Status::Split, Status::Whole] {
2019 let mut run = IssueRun::new(1, "t");
2020 run.status = status;
2021 assert!(run.succeeded(), "{status}");
2022 }
2023 }
2024
2025 #[test]
2026 fn status_round_trips_through_json() {
2027 let run = IssueRun::new(4, "t");
2028 let text = serde_json::to_string(&run).unwrap();
2029 let back: IssueRun = serde_json::from_str(&text).unwrap();
2030 assert_eq!(Status::Pending, back.status);
2031 }
2032
2033 #[test]
2036 fn a_look_whose_head_moved_did_not_do_its_job() {
2037 let mut run = IssueRun::new(4, "t");
2038 run.status = Status::Moved;
2039 assert!(!run.succeeded());
2040 let text = serde_json::to_string(&run).unwrap();
2041 assert!(text.contains("\"moved\""), "{text}");
2042 let back: IssueRun = serde_json::from_str(&text).unwrap();
2043 assert_eq!(Status::Moved, back.status);
2044 }
2045
2046 fn live(pull: &str, branch: Option<&str>) -> LiveHead {
2047 LiveHead {
2048 pull: pull.into(),
2049 branch: branch.map(String::from),
2050 }
2051 }
2052
2053 #[test]
2056 fn a_head_is_settled_only_once_the_pull_request_has_caught_up_with_its_branch() {
2057 assert_eq!(None, live("fb3a7ab", Some("2d5e2b5")).settled());
2058 assert_eq!(Some("2d5e2b5"), live("2d5e2b5", Some("2d5e2b5")).settled());
2059 assert_eq!(Some("2d5e2b5"), live("2d5e2b5", Some("2D5E2B5")).settled());
2060 assert_eq!(Some("fb3a7ab"), live("fb3a7ab", None).settled());
2062 }
2063
2064 #[test]
2065 fn a_head_moved_from_the_reviewed_one_names_the_newer_commit() {
2066 assert_eq!(None, live("fb3a7ab", Some("fb3a7ab")).moved_from("fb3a7ab"));
2067 assert_eq!(None, live("FB3A7AB", None).moved_from("fb3a7ab"));
2068 assert_eq!(
2070 Some("c493635"),
2071 live("2d5e2b5", Some("c493635")).moved_from("fb3a7ab")
2072 );
2073 assert_eq!(
2074 Some("c493635"),
2075 live("fb3a7ab", Some("c493635")).moved_from("fb3a7ab")
2076 );
2077 assert_eq!(Some("2d5e2b5"), live("2d5e2b5", None).moved_from("fb3a7ab"));
2078 assert_eq!(
2079 Some("2d5e2b5"),
2080 live("2d5e2b5", Some("fb3a7ab")).moved_from("fb3a7ab")
2081 );
2082 }
2083}
2084
2085#[cfg(test)]
2086mod body_for_prompt_tests {
2087 use super::*;
2088
2089 fn issue(body: &str) -> Issue {
2090 let mut i: Issue = serde_json::from_value(serde_json::json!({
2091 "number": 1, "title": "t", "state": "open", "url": "u"
2092 }))
2093 .expect("an issue");
2094 i.body = Some(body.to_string());
2095 i
2096 }
2097
2098 #[test]
2101 fn an_issue_that_fits_is_handed_over_whole() {
2102 let (body, cut) = issue("The guard is inverted.").body_for_prompt(60_000);
2103 assert_eq!("The guard is inverted.", body);
2104 assert!(!cut);
2105 }
2106
2107 #[test]
2111 fn a_shortened_body_says_so_in_the_text() {
2112 let long = "line of text\n".repeat(500);
2113 let (body, cut) = issue(&long).body_for_prompt(200);
2114 assert!(cut);
2115 assert!(body.contains("Shortened to fit"), "{body}");
2116 assert!(body.len() < long.len());
2117 }
2118
2119 #[test]
2122 fn a_cut_never_leaves_a_code_fence_open() {
2123 let body = format!("intro\n\n```rust\n{}\n```\n", "let x = 1;\n".repeat(200));
2124 let (out, cut) = issue(&body).body_for_prompt(120);
2125 assert!(cut);
2126 assert_eq!(0, out.matches("```").count() % 2, "{out}");
2127 }
2128
2129 #[test]
2131 fn a_cut_lands_on_a_line_boundary() {
2132 let body = "aaaa bbbb cccc\n".repeat(100);
2133 let (out, _) = issue(&body).body_for_prompt(100);
2134 let kept = out.split("\n\n[Shortened").next().expect("the kept part");
2135 assert!(kept.ends_with("cccc"), "{kept:?}");
2136 }
2137}
2138
2139#[cfg(test)]
2140mod review_record_tests {
2141 use super::*;
2142
2143 fn judged() -> Judged {
2144 Judged {
2145 finding: Finding {
2146 severity: Severity::Blocking,
2147 title: "Retry loop never terminates".into(),
2148 detail: "the guard compares against Some(0)".into(),
2149 file: "src/net.rs:88".into(),
2150 in_scope: true,
2151 problem: Some("dropped on the way to the record".into()),
2152 ..Finding::default()
2153 },
2154 raised_by: "claude and codex".into(),
2155 standing: Standing::Corroborated,
2156 counterpoint: None,
2157 defence: Some("stands".into()),
2158 rated: None,
2159 }
2160 }
2161
2162 #[test]
2163 fn a_review_record_round_trips_through_json_and_keeps_its_standing_as_a_word() {
2164 let record = ReviewRecord {
2165 version: REVIEW_RECORD_VERSION,
2166 head: "0123abcdef".into(),
2167 reviewed_at: "2026-10-20T18:04:05Z".into(),
2168 findings: vec![RecordedFinding::from(&judged())],
2169 rechecks: 2,
2170 verdict: Some(ReviewVerdict::RequestChanges),
2171 posted: true,
2172 };
2173 let text = serde_json::to_string_pretty(&record).unwrap();
2174 assert!(text.contains("\"standing\": \"corroborated\""), "{text}");
2175 assert!(text.contains("\"verdict\": \"request_changes\""), "{text}");
2176 assert!(text.contains("\"severity\": \"blocking\""), "{text}");
2177 assert!(!text.contains("problem"), "{text}");
2178 let back: ReviewRecord = serde_json::from_str(&text).unwrap();
2179 assert_eq!(record, back);
2180 assert_eq!("0123abc", back.short_head());
2181 }
2182
2183 #[test]
2184 fn a_record_missing_the_newer_fields_still_reads() {
2185 let text = r#"{"version":1,"head":"abc","reviewed_at":"2026-10-20T18:04:05Z",
2186 "findings":[{"title":"T","severity":"nit","standing":"one_reviewer"}]}"#;
2187 let back: ReviewRecord = serde_json::from_str(text).unwrap();
2188 assert_eq!(0, back.rechecks);
2189 assert!(!back.posted);
2190 assert_eq!(None, back.verdict);
2191 assert!(back.findings[0].in_scope);
2192 assert_eq!(Standing::Unverified, back.findings[0].standing);
2193 assert_eq!("general", back.findings[0].where_at());
2194 }
2195
2196 #[test]
2197 fn a_recorded_finding_turns_back_into_a_judged_finding() {
2198 let original = judged();
2199 let back = RecordedFinding::from(&original).to_judged();
2200 assert_eq!(original.finding.title, back.finding.title);
2201 assert_eq!(original.finding.file, back.finding.file);
2202 assert_eq!(original.finding.severity, back.finding.severity);
2203 assert_eq!(original.raised_by, back.raised_by);
2204 assert_eq!(original.standing, back.standing);
2205 assert_eq!(original.defence, back.defence);
2206 assert_eq!(None, back.finding.problem);
2207 assert!(back.finding.blocks());
2208 }
2209
2210 #[test]
2211 fn a_ruling_tolerates_a_quoted_index_and_a_synonym_outcome() {
2212 let doc: RecheckDoc = serde_json::from_str(
2213 r#"{"summary":"holds","rulings":[{"index":"2","outcome":"Resolved","reasoning":"line 4"}],"findings":[]}"#,
2214 )
2215 .unwrap();
2216 assert_eq!(2, doc.rulings[0].index);
2217 assert_eq!(Ruling::Fixed, doc.rulings[0].outcome);
2218 let doc: RecheckDoc =
2219 serde_json::from_str(r#"{"summary":"","rulings":[],"findings":[]}"#).unwrap();
2220 assert!(doc.rulings.is_empty());
2221 assert_eq!("APPROVE", ReviewVerdict::Approve.api_event());
2222 assert_eq!("changes requested", ReviewVerdict::RequestChanges.words());
2223 }
2224}
2225
2226#[cfg(test)]
2227mod assigned_issue_tests {
2228 use super::*;
2229
2230 fn issue(assignees: &[&str], assigned: &[(&str, &str)]) -> AssignedIssue {
2231 AssignedIssue {
2232 number: 42,
2233 title: "t".into(),
2234 assignees: assignees.iter().map(|s| s.to_string()).collect(),
2235 assigned: assigned
2236 .iter()
2237 .map(|(at, who)| (at.to_string(), who.to_string()))
2238 .collect(),
2239 }
2240 }
2241
2242 #[test]
2243 fn the_newest_assignment_counts_only_for_the_viewer_and_only_while_assigned() {
2244 let both = issue(
2245 &["somebody", "Viewer"],
2246 &[
2247 ("2026-11-01T10:00:00Z", "viewer"),
2248 ("2026-11-03T09:00:00Z", "somebody"),
2249 ("2026-11-02T10:00:00Z", "VIEWER"),
2250 ("not a time", "viewer"),
2251 ],
2252 );
2253 assert_eq!(
2254 Some("2026-11-02T10:00:00Z".to_string()),
2255 both.newest_for("viewer")
2256 );
2257 assert_eq!(
2258 Some("2026-11-03T09:00:00Z".to_string()),
2259 both.newest_for("somebody")
2260 );
2261 let dropped = issue(&["somebody"], &[("2026-11-01T10:00:00Z", "viewer")]);
2263 assert_eq!(None, dropped.newest_for("viewer"));
2264 let silent = issue(&["viewer"], &[]);
2266 assert_eq!(None, silent.newest_for("viewer"));
2267 }
2268}