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 }
191}
192
193impl Complexity {
194 pub fn rank(self) -> u8 {
195 match self {
196 Complexity::S => 0,
197 Complexity::M => 1,
198 Complexity::L => 2,
199 }
200 }
201}
202
203impl Severity {
204 pub fn rank(self) -> u8 {
208 match self {
209 Severity::Nit => 0,
210 Severity::NonBlocking => 1,
211 Severity::Blocking => 2,
212 }
213 }
214
215 pub fn graver(self, other: Self) -> Self {
222 if self.rank() >= other.rank() {
223 self
224 } else {
225 other
226 }
227 }
228}
229
230impl Risk {
231 pub fn rank(self) -> u8 {
232 match self {
233 Risk::Low => 0,
234 Risk::Med => 1,
235 Risk::High => 2,
236 }
237 }
238}
239
240pub fn de_i64<'de, D: Deserializer<'de>>(d: D) -> Result<i64, D::Error> {
247 struct V;
248 impl<'de> Visitor<'de> for V {
249 type Value = i64;
250 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
251 f.write_str("an issue number")
252 }
253 fn visit_i64<E: de::Error>(self, v: i64) -> Result<i64, E> {
254 Ok(v)
255 }
256 fn visit_u64<E: de::Error>(self, v: u64) -> Result<i64, E> {
257 Ok(v as i64)
258 }
259 fn visit_f64<E: de::Error>(self, v: f64) -> Result<i64, E> {
260 Ok(v as i64)
261 }
262 fn visit_str<E: de::Error>(self, v: &str) -> Result<i64, E> {
263 v.trim()
264 .trim_start_matches('#')
265 .parse()
266 .map_err(|_| E::custom(format!("{v} is not a number")))
267 }
268 }
269 d.deserialize_any(V)
270}
271
272fn de_i64_vec<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<i64>, D::Error> {
273 #[derive(Deserialize)]
274 struct One(#[serde(deserialize_with = "de_i64")] i64);
275 let raw = Option::<Vec<One>>::deserialize(d)?;
276 Ok(raw
277 .unwrap_or_default()
278 .into_iter()
279 .map(|One(n)| n)
280 .collect())
281}
282
283pub fn de_bool<'de, D: Deserializer<'de>>(d: D) -> Result<bool, D::Error> {
285 struct V;
286 impl<'de> Visitor<'de> for V {
287 type Value = bool;
288 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
289 f.write_str("a boolean")
290 }
291 fn visit_bool<E: de::Error>(self, v: bool) -> Result<bool, E> {
292 Ok(v)
293 }
294 fn visit_i64<E: de::Error>(self, v: i64) -> Result<bool, E> {
295 Ok(v != 0)
296 }
297 fn visit_u64<E: de::Error>(self, v: u64) -> Result<bool, E> {
298 Ok(v != 0)
299 }
300 fn visit_str<E: de::Error>(self, v: &str) -> Result<bool, E> {
301 match norm_token(v).as_str() {
302 "true" | "yes" | "y" | "1" => Ok(true),
303 "false" | "no" | "n" | "0" => Ok(false),
304 other => Err(E::custom(format!("{other} is not a boolean"))),
305 }
306 }
307 }
308 d.deserialize_any(V)
309}
310
311pub fn de_opt_i64<'de, D: Deserializer<'de>>(d: D) -> Result<Option<i64>, D::Error> {
317 Ok(match Option::<serde_json::Value>::deserialize(d)? {
318 Some(serde_json::Value::Number(n)) => n.as_i64(),
319 Some(serde_json::Value::String(s)) => s.trim().trim_start_matches('#').parse().ok(),
320 _ => None,
321 })
322}
323
324fn de_bool_default_true<'de, D: Deserializer<'de>>(d: D) -> Result<bool, D::Error> {
325 #[derive(Deserialize)]
326 struct Wrap(#[serde(deserialize_with = "de_bool")] bool);
327 Ok(Option::<Wrap>::deserialize(d)?
328 .map(|Wrap(b)| b)
329 .unwrap_or(true))
330}
331
332fn de_string<'de, D: Deserializer<'de>>(d: D) -> Result<String, D::Error> {
333 Ok(Option::<String>::deserialize(d)?.unwrap_or_default())
334}
335
336#[derive(Debug, Clone, Serialize, Deserialize)]
341pub struct TriageVerdict {
342 #[serde(deserialize_with = "de_i64")]
343 pub issue: i64,
344 #[serde(deserialize_with = "de_bool")]
345 pub worth_doing: bool,
346 #[serde(default, deserialize_with = "de_bool")]
349 pub tracker: bool,
350 #[serde(default, deserialize_with = "de_string")]
351 pub reason: String,
352 pub complexity: Complexity,
353 #[serde(default, deserialize_with = "de_i64_vec")]
354 pub depends_on: Vec<i64>,
355 pub risk: Risk,
356}
357
358#[derive(Debug, Clone, Serialize, Deserialize)]
359pub struct TriageResponse {
360 #[serde(default)]
361 pub issues: Vec<TriageVerdict>,
362}
363
364#[derive(Debug, Clone, Serialize, Deserialize)]
366pub struct ScreenVerdict {
367 #[serde(deserialize_with = "de_i64")]
372 pub entry: i64,
373 pub verdict: Screened,
374 #[serde(default, deserialize_with = "de_string")]
375 pub title: String,
376 #[serde(default, deserialize_with = "de_string")]
377 pub reason: String,
378 #[serde(default, deserialize_with = "de_opt_i64")]
380 pub duplicate_of: Option<i64>,
381}
382
383#[derive(Debug, Clone, Serialize, Deserialize)]
384pub struct ScreenResponse {
385 #[serde(default)]
386 pub entries: Vec<ScreenVerdict>,
387}
388
389#[derive(Debug, Clone, Serialize, Deserialize)]
391pub struct CommentVerdict {
392 #[serde(default, deserialize_with = "de_string")]
397 pub ref_id: String,
398 pub ask: Ask,
399 #[serde(default, deserialize_with = "de_string")]
402 pub request: String,
403 #[serde(default, deserialize_with = "de_string")]
406 pub reasoning: String,
407 #[serde(deserialize_with = "de_bool")]
410 pub unambiguous: bool,
411 #[serde(default)]
412 pub new_issue_title: Option<String>,
413 #[serde(default)]
414 pub new_issue_body: Option<String>,
415}
416
417#[derive(Debug, Clone, Serialize, Deserialize)]
418pub struct CheckinDoc {
419 #[serde(default)]
420 pub verdicts: Vec<CommentVerdict>,
421}
422
423#[derive(Debug, Clone, Serialize, Deserialize)]
425pub struct CommentCheck {
426 #[serde(default, deserialize_with = "de_string")]
427 pub ref_id: String,
428 #[serde(deserialize_with = "de_bool")]
429 pub agrees: bool,
430 pub ask: Ask,
432 #[serde(deserialize_with = "de_bool")]
433 pub unambiguous: bool,
434 #[serde(default, deserialize_with = "de_string")]
435 pub reasoning: String,
436}
437
438#[derive(Debug, Clone, Serialize, Deserialize)]
439pub struct CheckDoc {
440 #[serde(default)]
441 pub checks: Vec<CommentCheck>,
442}
443
444#[derive(Debug, Clone, Serialize, Deserialize)]
446pub struct FixOutcome {
447 #[serde(default, deserialize_with = "de_string")]
448 pub ref_id: String,
449 #[serde(deserialize_with = "de_bool")]
453 pub changed: bool,
454 #[serde(default, deserialize_with = "de_string")]
457 pub summary: String,
458}
459
460#[derive(Debug, Clone, Serialize, Deserialize)]
461pub struct FixReport {
462 #[serde(default)]
463 pub done: Vec<FixOutcome>,
464}
465
466#[derive(Debug, Clone, Default, Serialize, Deserialize)]
478pub struct Answered {
479 #[serde(default)]
480 pub version: u32,
481 #[serde(default)]
482 pub seen: BTreeMap<String, String>,
483}
484
485#[derive(Debug, Clone, Serialize, Deserialize)]
486pub struct Finding {
487 pub severity: Severity,
488 #[serde(default, deserialize_with = "de_string")]
489 pub title: String,
490 #[serde(default, deserialize_with = "de_string")]
491 pub detail: String,
492 #[serde(default, deserialize_with = "de_string")]
493 pub file: String,
494 #[serde(default = "yes", deserialize_with = "de_bool_default_true")]
497 pub in_scope: bool,
498
499 #[serde(default)]
507 pub problem: Option<String>,
508 #[serde(default)]
510 pub reproduction: Option<String>,
511 #[serde(default)]
513 pub impact: Option<String>,
514 #[serde(default)]
516 pub expected: Option<String>,
517}
518
519impl Default for Finding {
520 fn default() -> Self {
527 Self {
528 severity: Severity::Nit,
529 title: String::new(),
530 detail: String::new(),
531 file: String::new(),
532 in_scope: true,
533 problem: None,
534 reproduction: None,
535 impact: None,
536 expected: None,
537 }
538 }
539}
540
541impl Finding {
542 pub fn report_sections(&self) -> Vec<(&'static str, &str)> {
545 [
546 ("Problem", self.problem.as_deref()),
547 ("Reproduction", self.reproduction.as_deref()),
548 ("Impact", self.impact.as_deref()),
549 ("Expected behavior", self.expected.as_deref()),
550 ]
551 .into_iter()
552 .filter_map(|(heading, text)| {
553 text.map(str::trim)
554 .filter(|t| !t.is_empty())
555 .map(|t| (heading, t))
556 })
557 .collect()
558 }
559}
560
561fn yes() -> bool {
562 true
563}
564
565impl Finding {
566 pub fn blocks(&self) -> bool {
567 self.severity == Severity::Blocking && self.in_scope
568 }
569
570 pub fn where_at(&self) -> &str {
571 if self.file.trim().is_empty() {
572 "general"
573 } else {
574 self.file.trim()
575 }
576 }
577}
578
579#[derive(Debug, Clone, Serialize, Deserialize)]
580pub struct Review {
581 pub verdict: Verdict,
582 pub next_action: NextAction,
583 #[serde(default, deserialize_with = "de_string")]
584 pub summary: String,
585 #[serde(default)]
586 pub findings: Vec<Finding>,
587}
588
589#[derive(Debug, Clone, Serialize, Deserialize)]
590pub struct Disposition {
591 #[serde(default, deserialize_with = "de_string")]
592 pub title: String,
593 #[serde(default, deserialize_with = "de_string")]
597 pub file: String,
598 pub action: Action,
599 #[serde(default, deserialize_with = "de_string")]
600 pub reasoning: String,
601 #[serde(default)]
602 pub new_issue_title: Option<String>,
603 #[serde(default)]
604 pub new_issue_body: Option<String>,
605}
606
607#[derive(Debug, Clone, Serialize, Deserialize)]
614pub struct Adjudication {
615 #[serde(default, deserialize_with = "de_string")]
616 pub title: String,
617 #[serde(default, deserialize_with = "de_string")]
618 pub file: String,
619 #[serde(deserialize_with = "de_bool")]
622 pub agrees: bool,
623 pub severity: Severity,
625 #[serde(default, deserialize_with = "de_string")]
626 pub reasoning: String,
627}
628
629#[derive(Debug, Clone, Serialize, Deserialize)]
630pub struct AdjudicationDoc {
631 #[serde(default)]
632 pub verdicts: Vec<Adjudication>,
633}
634
635#[derive(Debug, Clone)]
637pub struct Judged {
638 pub finding: Finding,
639 pub raised_by: String,
641 pub standing: Standing,
643 pub counterpoint: Option<String>,
645 pub defence: Option<String>,
650}
651
652#[derive(Debug, Clone, Copy, PartialEq, Eq)]
653pub enum Standing {
654 Corroborated,
656 Confirmed,
658 Disputed,
661 Withdrawn,
663 Unverified,
665}
666
667#[derive(Debug, Clone, Default, Serialize, Deserialize)]
676pub struct Implementation {
677 #[serde(default, deserialize_with = "de_bool")]
679 pub not_worth_doing: bool,
680 #[serde(default, deserialize_with = "de_string")]
683 pub reason: String,
684 #[serde(default, deserialize_with = "de_string")]
686 pub summary: String,
687 #[serde(default, deserialize_with = "de_string")]
690 pub problem: String,
691 #[serde(default)]
693 pub changes: Vec<String>,
694 #[serde(default)]
696 pub testing: Vec<String>,
697 #[serde(default)]
700 pub notes: Option<String>,
701}
702
703#[derive(Debug, Clone, Serialize, Deserialize)]
704pub struct ResponseDoc {
705 #[serde(default, deserialize_with = "de_string")]
706 pub summary: String,
707 #[serde(default)]
708 pub dispositions: Vec<Disposition>,
709}
710
711#[derive(Debug, Clone, Serialize, Deserialize)]
716pub struct PlanItem {
717 pub issue: i64,
718 pub title: String,
719 pub complexity: Complexity,
720 pub risk: Risk,
721 pub depends_on: Vec<i64>,
722 pub reason: String,
723}
724
725#[derive(Debug, Clone, Serialize, Deserialize)]
726pub struct SkippedItem {
727 pub issue: i64,
728 pub title: String,
729 pub reasons: BTreeMap<String, String>,
731 #[serde(default)]
739 pub tracker: bool,
740}
741
742#[derive(Debug, Clone, Serialize, Deserialize)]
743pub struct ContestedItem {
744 pub issue: i64,
745 pub title: String,
746 pub positions: BTreeMap<String, String>,
748 pub reasons: BTreeMap<String, String>,
749 #[serde(default, skip_serializing_if = "Option::is_none")]
750 pub note: Option<String>,
751}
752
753#[derive(Debug, Clone, Default, Serialize, Deserialize)]
754pub struct Plan {
755 #[serde(default)]
756 pub order: Vec<PlanItem>,
757 #[serde(default)]
758 pub skipped: Vec<SkippedItem>,
759 #[serde(default)]
760 pub contested: Vec<ContestedItem>,
761}
762
763#[derive(Debug, Clone, Serialize, Deserialize)]
764pub struct LedgerEntry {
765 pub title: String,
766 pub file: String,
767 pub reasoning: String,
768 pub round: u32,
769 #[serde(default)]
770 pub reraised: u32,
771}
772
773pub type Ledger = BTreeMap<String, LedgerEntry>;
777
778#[derive(Debug, Clone, Serialize, Deserialize)]
779pub struct Dispute {
780 pub title: String,
781 pub reasoning: String,
782}
783
784#[derive(Debug, Clone, Serialize, Deserialize)]
786pub struct IssueRun {
787 pub issue: i64,
788 pub title: String,
789 pub status: Status,
790 #[serde(default, skip_serializing_if = "Option::is_none")]
791 pub pr: Option<String>,
792 #[serde(default)]
793 pub rounds: u32,
794 #[serde(default)]
795 pub disputes: Vec<Dispute>,
796 #[serde(default)]
797 pub filed: Vec<String>,
798 #[serde(default)]
799 pub notes: Vec<String>,
800}
801
802impl IssueRun {
803 pub fn new(issue: i64, title: impl Into<String>) -> Self {
804 Self {
805 issue,
806 title: title.into(),
807 status: Status::Pending,
808 pr: None,
809 rounds: 0,
810 disputes: Vec::new(),
811 filed: Vec::new(),
812 notes: Vec::new(),
813 }
814 }
815
816 pub fn succeeded(&self) -> bool {
821 matches!(
822 self.status,
823 Status::Merged
824 | Status::Approved
825 | Status::Abandoned
826 | Status::Reviewed
827 | Status::Clean
828 | Status::Answered
829 )
830 }
831}
832
833#[derive(Debug, Clone, Serialize, Deserialize)]
835pub struct PersistedState {
836 pub version: u32,
837 pub round: u32,
838 pub next_actor: String,
839 pub status: Status,
840 #[serde(default)]
841 pub ledger: Ledger,
842 #[serde(default)]
843 pub filed: Vec<String>,
844}
845
846pub const STATE_VERSION: u32 = 1;
847
848#[derive(Debug, Clone, Deserialize)]
853pub struct Label {
854 #[serde(default)]
855 pub name: String,
856}
857
858#[derive(Debug, Clone, Deserialize)]
859pub struct Issue {
860 pub number: i64,
861 #[serde(default)]
862 pub title: String,
863 #[serde(default)]
864 pub body: Option<String>,
865 #[serde(default)]
866 pub state: String,
867 #[serde(default)]
868 pub url: String,
869 #[serde(default)]
870 pub labels: Vec<Label>,
871}
872
873impl Issue {
874 pub fn body_text(&self) -> &str {
875 self.body.as_deref().unwrap_or("")
876 }
877
878 pub fn body_for_prompt(&self, max: usize) -> (String, bool) {
890 let body = self.body_text().trim();
891 if body.chars().count() <= max {
892 return (body.to_string(), false);
893 }
894 let clipped: String = body.chars().take(max).collect();
895 let mut kept = match clipped.rfind('\n') {
896 Some(at) => clipped[..at].to_string(),
897 None => clipped,
898 };
899 if kept.matches("```").count() % 2 == 1 {
900 kept.push_str("\n```");
901 }
902 kept.push_str("\n\n[Shortened to fit. The rest of this issue was not included.]");
903 (kept, true)
904 }
905
906 pub fn is_closed(&self) -> bool {
907 self.state.eq_ignore_ascii_case("closed")
908 }
909}
910
911#[derive(Debug, Clone, Deserialize)]
912pub struct PrRef {
913 pub number: i64,
914 #[serde(default)]
915 pub url: String,
916 #[serde(default)]
917 pub title: String,
918}
919
920#[derive(Debug, Clone, Deserialize)]
921pub struct IssueRef {
922 pub number: i64,
923}
924
925#[derive(Debug, Clone, Deserialize)]
926#[serde(rename_all = "camelCase")]
927pub struct PrView {
928 pub number: i64,
929 #[serde(default)]
930 pub url: String,
931 #[serde(default)]
932 pub title: String,
933 #[serde(default)]
934 pub head_ref_name: String,
935 #[serde(default)]
936 pub base_ref_name: String,
937 #[serde(default)]
938 pub state: String,
939 #[serde(default)]
940 pub closing_issues_references: Vec<IssueRef>,
941 #[serde(default)]
944 pub is_cross_repository: bool,
945}
946
947#[derive(Debug, Clone, Copy, PartialEq, Eq)]
950pub enum ItemKind {
951 Issue,
952 Pr,
953}
954
955impl std::fmt::Display for ItemKind {
956 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
957 f.write_str(match self {
958 ItemKind::Issue => "issue",
959 ItemKind::Pr => "pull request",
960 })
961 }
962}
963
964impl PrView {
965 pub fn is_open(&self) -> bool {
966 self.state.eq_ignore_ascii_case("open")
967 }
968}
969
970#[cfg(test)]
971mod tests {
972 use super::*;
973
974 #[test]
975 fn severity_accepts_the_canonical_spelling() {
976 assert_eq!(
977 Some(Severity::NonBlocking),
978 Severity::parse_lenient("non-blocking")
979 );
980 }
981
982 #[test]
983 fn severity_accepts_near_misses() {
984 for text in ["NonBlocking", "non_blocking", " NON-BLOCKING ", "minor"] {
985 assert_eq!(
986 Some(Severity::NonBlocking),
987 Severity::parse_lenient(text),
988 "{text}"
989 );
990 }
991 }
992
993 #[test]
994 fn severity_rejects_nonsense() {
995 assert_eq!(None, Severity::parse_lenient("catastrophic-ish"));
996 }
997
998 #[test]
999 fn complexity_ordering_is_cheapest_first() {
1000 assert!(Complexity::S.rank() < Complexity::M.rank());
1001 assert!(Complexity::M.rank() < Complexity::L.rank());
1002 }
1003
1004 #[test]
1005 fn finding_defaults_to_in_scope() {
1006 let f: Finding = serde_json::from_value(serde_json::json!({
1007 "severity": "blocking", "title": "t", "detail": "d", "file": "a.rs"
1008 }))
1009 .unwrap();
1010 assert!(f.in_scope);
1011 assert!(f.blocks());
1012 }
1013
1014 #[test]
1015 fn out_of_scope_blocking_does_not_block() {
1016 let f: Finding = serde_json::from_value(serde_json::json!({
1017 "severity": "blocking", "title": "t", "detail": "d",
1018 "file": "a.rs", "in_scope": false
1019 }))
1020 .unwrap();
1021 assert!(!f.blocks());
1022 }
1023
1024 #[test]
1025 fn triage_tolerates_a_quoted_issue_number() {
1026 let v: TriageVerdict = serde_json::from_value(serde_json::json!({
1027 "issue": "#42", "worth_doing": "yes", "reason": "r",
1028 "complexity": "medium", "depends_on": ["39"], "risk": "low"
1029 }))
1030 .unwrap();
1031 assert_eq!(42, v.issue);
1032 assert!(v.worth_doing);
1033 assert_eq!(Complexity::M, v.complexity);
1034 assert_eq!(vec![39], v.depends_on);
1035 }
1036
1037 #[test]
1038 fn triage_tolerates_a_missing_depends_on() {
1039 let v: TriageVerdict = serde_json::from_value(serde_json::json!({
1040 "issue": 1, "worth_doing": false, "reason": "r",
1041 "complexity": "s", "risk": "high"
1042 }))
1043 .unwrap();
1044 assert!(v.depends_on.is_empty());
1045 }
1046
1047 #[test]
1048 fn review_tolerates_a_missing_findings_array() {
1049 let r: Review = serde_json::from_value(serde_json::json!({
1050 "verdict": "approve", "next_action": "merge", "summary": "fine"
1051 }))
1052 .unwrap();
1053 assert!(r.findings.is_empty());
1054 }
1055
1056 #[test]
1057 fn a_null_reason_is_an_empty_string_not_a_failure() {
1058 let v: TriageVerdict = serde_json::from_value(serde_json::json!({
1059 "issue": 1, "worth_doing": true, "reason": null,
1060 "complexity": "s", "depends_on": [], "risk": "low"
1061 }))
1062 .unwrap();
1063 assert_eq!("", v.reason);
1064 }
1065
1066 #[test]
1067 fn unknown_severity_is_an_error_not_a_silent_downgrade() {
1068 let out: Result<Finding, _> = serde_json::from_value(serde_json::json!({
1069 "severity": "showstopper-maybe", "title": "t", "detail": "d", "file": "a.rs"
1070 }));
1071 assert!(out.is_err());
1072 }
1073
1074 #[test]
1075 fn status_round_trips_through_json() {
1076 let run = IssueRun::new(4, "t");
1077 let text = serde_json::to_string(&run).unwrap();
1078 let back: IssueRun = serde_json::from_str(&text).unwrap();
1079 assert_eq!(Status::Pending, back.status);
1080 }
1081}
1082
1083#[cfg(test)]
1084mod body_for_prompt_tests {
1085 use super::*;
1086
1087 fn issue(body: &str) -> Issue {
1088 let mut i: Issue = serde_json::from_value(serde_json::json!({
1089 "number": 1, "title": "t", "state": "open", "url": "u"
1090 }))
1091 .expect("an issue");
1092 i.body = Some(body.to_string());
1093 i
1094 }
1095
1096 #[test]
1099 fn an_issue_that_fits_is_handed_over_whole() {
1100 let (body, cut) = issue("The guard is inverted.").body_for_prompt(60_000);
1101 assert_eq!("The guard is inverted.", body);
1102 assert!(!cut);
1103 }
1104
1105 #[test]
1109 fn a_shortened_body_says_so_in_the_text() {
1110 let long = "line of text\n".repeat(500);
1111 let (body, cut) = issue(&long).body_for_prompt(200);
1112 assert!(cut);
1113 assert!(body.contains("Shortened to fit"), "{body}");
1114 assert!(body.len() < long.len());
1115 }
1116
1117 #[test]
1120 fn a_cut_never_leaves_a_code_fence_open() {
1121 let body = format!("intro\n\n```rust\n{}\n```\n", "let x = 1;\n".repeat(200));
1122 let (out, cut) = issue(&body).body_for_prompt(120);
1123 assert!(cut);
1124 assert_eq!(0, out.matches("```").count() % 2, "{out}");
1125 }
1126
1127 #[test]
1129 fn a_cut_lands_on_a_line_boundary() {
1130 let body = "aaaa bbbb cccc\n".repeat(100);
1131 let (out, _) = issue(&body).body_for_prompt(100);
1132 let kept = out.split("\n\n[Shortened").next().expect("the kept part");
1133 assert!(kept.ends_with("cccc"), "{kept:?}");
1134 }
1135}