Skip to main content

spar/
model.rs

1//! The shapes that cross the boundary between spar and a model, and the shapes
2//! spar keeps for itself.
3//!
4//! Everything a model produces is parsed leniently: an LLM that answers
5//! "medium" where the schema said "med" is not a reason to abandon a run that
6//! has already spent real money. Anything genuinely unrecognisable is still an
7//! error, because silently downgrading a blocking finding is worse than
8//! stopping.
9
10use 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            /// Accept the canonical spelling, any listed alias, and any
41            /// difference in case, spacing, hyphens, or underscores.
42            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    /// How much work an issue is. Drives ordering: cheap unblocking work first.
86    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    /// How likely a change here is to break something.
95    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    /// Only `Blocking` gates a merge. This is the whole defence against the
104    /// nitpick spiral: a competent reviewer can always find something, so
105    /// "no objections remaining" is not a stopping condition but "no blocking
106    /// objections" is.
107    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    /// What a formal pull request review says. `Verdict` is what a model
123    /// answers; this is what spar submits, and spar never asks a model for it.
124    /// It is derived from the findings: approve when nothing blocks, request
125    /// changes when something both reviewers count does.
126    pub enum ReviewVerdict {
127        Approve = "approve" | "approved",
128        RequestChanges = "request_changes" | "changes_requested" | "request-changes",
129    }
130}
131
132impl ReviewVerdict {
133    /// The `event` the reviews API submits it as.
134    pub fn api_event(self) -> &'static str {
135        match self {
136            ReviewVerdict::Approve => "APPROVE",
137            ReviewVerdict::RequestChanges => "REQUEST_CHANGES",
138        }
139    }
140
141    /// The words that stand in for the badge when GitHub will not take the
142    /// verdict itself, on the viewer's own pull request.
143    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    /// A reviewer's point gets exactly one of these. Refutation is a first
161    /// class outcome, not friction: an agent that accepts every comment to get
162    /// approved produces worse code, not better.
163    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    /// What spar should do about one comment somebody left.
172    ///
173    /// Every value maps to exactly one action, which is the point: a verdict
174    /// that needs a second field to decide what it means is one that gets
175    /// decided differently in two places.
176    pub enum Ask {
177        /// A change is asked for, it is right, and it belongs on this branch.
178        /// Make it, push it, say so, and resolve the thread.
179        Implement = "implement" | "do" | "accept" | "fix",
180        /// Right, but really its own piece of work. File it, say where it went.
181        Defer = "defer" | "file_issue" | "filed_issue" | "out_of_scope" | "followup",
182        /// Should not be made. Reply with the reason, leave the thread open.
183        Decline = "decline" | "refute" | "reject" | "disagree" | "wontfix",
184        /// A question rather than a request. Answer it in words.
185        Answer = "answer" | "question" | "reply" | "clarify",
186        /// Nothing is being asked. Praise, or a thread they settled themselves.
187        Nothing = "nothing" | "none" | "no_request" | "noop" | "skip",
188    }
189}
190
191string_enum! {
192    /// What one screening pass decided about one recorded follow-up.
193    ///
194    /// Only `StillRelevant` files anything. The other three all take the entry
195    /// out of the queue, which is why the prompt asks for a reason and the log
196    /// prints it: they are the verdicts nobody sees the working for.
197    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    /// Terminal state of one issue or one resumed PR.
207    pub enum Status {
208        Pending = "pending",
209        Abandoned = "abandoned",
210        Approved = "approved",
211        Merged = "merged",
212        Escalated = "escalated",
213        Error = "error",
214        /// Review only: findings were produced and posted, nothing was changed.
215        Reviewed = "reviewed",
216        /// Review only: both reviewers found nothing that blocks a merge.
217        Clean = "clean",
218        /// Check-in: comments were read and answered.
219        Answered = "answered",
220        /// Split: the item was broken into parts, which were filed or opened.
221        Split = "split",
222        /// Split: read, and left as one piece.
223        Whole = "whole",
224        /// Review only: the head moved while it was read, or GitHub had not
225        /// caught up with a push yet, so nothing was posted. It runs again on
226        /// the new head.
227        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    /// How badly it matters, independent of the order the variants happen to
243    /// be declared in. Relying on derived `Ord` here would silently invert the
244    /// moment somebody reorders the enum.
245    pub fn rank(self) -> u8 {
246        match self {
247            Severity::Nit => 0,
248            Severity::NonBlocking => 1,
249            Severity::Blocking => 2,
250        }
251    }
252
253    /// The graver of two judgements.
254    ///
255    /// Two reviewers disagreeing about severity is resolved upward on purpose:
256    /// advice that under-reports a real defect is worse than advice that
257    /// over-reports a small one.
258    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
277// ---------------------------------------------------------------------------
278// Lenient scalar helpers
279// ---------------------------------------------------------------------------
280
281/// An integer that may arrive as a number, a float, or a quoted string, with or
282/// without a leading `#`.
283pub 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
320/// A boolean that may arrive as `true`, `"true"`, `"yes"`, or `1`.
321pub 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
348/// An optional number that may arrive as 412, "412", "#412", null, or "none".
349///
350/// Anything unparseable yields None rather than failing. A duplicate pointer is
351/// decoration on a verdict that stands without it, and taking a whole batch down
352/// over one stray string costs a second full repo pass to learn nothing.
353pub 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
361/// A list of strings that may arrive as null or be missing entirely.
362fn 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// ---------------------------------------------------------------------------
379// What the models return
380// ---------------------------------------------------------------------------
381
382#[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    /// The issue holds context for work filed elsewhere. Never opened, and
389    /// never closed either.
390    #[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/// One agent's ruling on one entry in the local follow-up queue.
407#[derive(Debug, Clone, Serialize, Deserialize)]
408pub struct ScreenVerdict {
409    /// The entry's position in the list it was given, from 1.
410    ///
411    /// Matched back by index rather than by title, because the entries are
412    /// spar's own data and so can carry a handle a model cannot paraphrase.
413    #[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    /// The open issue a duplicate points at.
421    ///
422    /// Kept apart from `duplicate_of_entry`, because one number cannot say
423    /// which it is and the two are acted on differently: an issue already
424    /// exists, while a sibling entry may itself be dropped or fail to file.
425    #[serde(default, deserialize_with = "de_opt_i64")]
426    pub duplicate_of_issue: Option<i64>,
427    /// The number of another entry in the same list a duplicate points at.
428    #[serde(default, deserialize_with = "de_opt_i64")]
429    pub duplicate_of_entry: Option<i64>,
430}
431
432impl ScreenVerdict {
433    /// Whether this verdict names anything at all as the thing that covers it.
434    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/// One agent's ruling on whether one open item is worth splitting at all.
446///
447/// The cheap screen the bare `spar split` runs over a whole queue, so that two
448/// agent calls per item are only spent on the ones where the answer might be
449/// yes.
450#[derive(Debug, Clone, Serialize, Deserialize)]
451pub struct SplitScreen {
452    /// The issue or pull request number, which is spar's own data and so cannot
453    /// be paraphrased back wrong.
454    #[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/// One piece of a proposed decomposition.
469#[derive(Debug, Clone, Default, Serialize, Deserialize)]
470pub struct SplitPart {
471    #[serde(default, deserialize_with = "de_string")]
472    pub title: String,
473    /// The issue body, or the rationale for a pull request slice.
474    #[serde(default, deserialize_with = "de_string")]
475    pub body: String,
476    /// The paths this slice carries. Empty for an issue split, where there is
477    /// no diff to partition.
478    #[serde(default, deserialize_with = "de_string_vec")]
479    pub files: Vec<String>,
480}
481
482/// One agent's decomposition of an issue or a pull request.
483///
484/// Deliberately one proposal rather than two. Two agents asked to decompose the
485/// same thing return two decompositions that cannot be reconciled mechanically,
486/// and reconciling them is a third judgement nobody asked for.
487#[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    /// Whether the parts are sequential, so each is based on its predecessor
494    /// rather than on the base branch. A property of the change, not of the
495    /// repository, which is why it rides on the proposal.
496    #[serde(default, deserialize_with = "de_bool")]
497    pub stacked: bool,
498    #[serde(default)]
499    pub parts: Vec<SplitPart>,
500}
501
502/// The second agent's ruling on the first one's decomposition.
503#[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    /// Part numbers, from 1, that should not be split out.
510    #[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/// One agent's judgement of one comment somebody left on a pull request.
517#[derive(Debug, Clone, Serialize, Deserialize)]
518pub struct CommentVerdict {
519    /// The handle spar printed beside the comment, copied back so the answer
520    /// can be matched to it. Not a title: a finding's title is the only handle
521    /// there is because findings are model authored, but a comment is spar's
522    /// own data, so it gets one that cannot be paraphrased or collided.
523    #[serde(default, deserialize_with = "de_string")]
524    pub ref_id: String,
525    pub ask: Ask,
526    /// What is being asked for, in one sentence, in the agent's own words.
527    /// How spar checks the comment was understood before acting on it.
528    #[serde(default, deserialize_with = "de_string")]
529    pub request: String,
530    /// The whole argument. For a decline this is posted in the thread, so it is
531    /// written for the person who raised the point.
532    #[serde(default, deserialize_with = "de_string")]
533    pub reasoning: String,
534    /// False when the comment could be read more than one way. spar answers an
535    /// ambiguous comment in words and never guesses at a commit.
536    #[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/// The second agent's ruling on the first one's call.
551#[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    /// What this agent would do. It has to say implement alongside
558    /// `agrees` before anything is implemented: the two coming apart is the
559    /// model contradicting itself, and that resolves toward saying rather than
560    /// doing.
561    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/// What the fix pass did about one comment.
575#[derive(Debug, Clone, Serialize, Deserialize)]
576pub struct FixOutcome {
577    #[serde(default, deserialize_with = "de_string")]
578    pub ref_id: String,
579    /// False when the change turned out to be wrong once the code was open.
580    /// Declining here is a better answer than making a change you now believe
581    /// is a mistake.
582    #[serde(deserialize_with = "de_bool")]
583    pub changed: bool,
584    /// One sentence naming what changed, or why it was left alone. Posted in
585    /// the thread, so it is written for the person who asked.
586    #[serde(default, deserialize_with = "de_string")]
587    pub summary: String,
588    /// The paths this comment's change touched, checked against the diff so a
589    /// reply never claims a fix that is not in it.
590    #[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/// What spar has already answered on one pull request or issue.
601///
602/// Keyed by thread or comment, valued by the newest message in it that spar did
603/// not write. A thread that has moved since spar answered carries a different
604/// value and is read again, which is what makes "they replied to my reply"
605/// work. GitHub's own resolved flag covers the threads spar fixed; this covers
606/// the ones it argued with, which stay open on purpose and would otherwise be
607/// re-argued once per run, forever.
608///
609/// Written only after a reply has posted. A run that could not post is a run
610/// that has not answered, and recording it as answered would lose the comment.
611#[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    /// Who answers one question an issue puts to the viewer.
621    pub enum QuestionKind {
622        /// A question of fact that the code, the issue, or what it links can
623        /// settle. spar may answer it, once both agents have checked it.
624        Answer = "answer" | "factual" | "fact" | "spar",
625        /// It asks the viewer to decide, commit, own, schedule, approve, or
626        /// give a view, or it could not be checked. Only the viewer answers it.
627        Yours = "yours" | "person" | "decision" | "human" | "unverified",
628    }
629}
630
631/// One question an issue puts to the viewer, as the drafting agent read it.
632#[derive(Debug, Clone, Serialize, Deserialize)]
633pub struct Question {
634    /// The handle spar printed beside the mention it came from.
635    #[serde(default, deserialize_with = "de_string")]
636    pub ref_id: String,
637    /// The question, quoted from the issue, or as close to it as reads alone.
638    #[serde(default, deserialize_with = "de_string")]
639    pub question: String,
640    pub kind: QuestionKind,
641    /// The reply as it would be posted. For a question that is the viewer's,
642    /// a starting point for them, which spar never posts.
643    #[serde(default, deserialize_with = "de_string")]
644    pub answer: String,
645    /// What the answer rests on: paths with lines, or links.
646    #[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/// The second agent's ruling on one drafted answer.
659#[derive(Debug, Clone, Serialize, Deserialize)]
660pub struct QuestionCheck {
661    /// The handle spar gave the question: q1, q2.
662    #[serde(default, deserialize_with = "de_string")]
663    pub id: String,
664    /// True only when this agent checked the answer and it is right, complete,
665    /// and fit to post as the viewer's.
666    #[serde(deserialize_with = "de_bool")]
667    pub agrees: bool,
668    /// Who this agent says should answer it. Both agents have to say answer
669    /// before spar does: the two coming apart resolves toward the viewer.
670    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    /// Questions put to the viewer that the draft left out.
680    #[serde(default, deserialize_with = "de_string_vec")]
681    pub missed: Vec<String>,
682}
683
684/// What `spar answer` has done on one issue, in `.spar/state/answer-N.json`.
685///
686/// Every mention that was judged is kept, whether it was answered, left for
687/// the viewer, or asked nothing, keyed `body` or `comment:{id}`. A mention is
688/// judged once: an edit to it, or the thread moving under spar's own reply,
689/// is not a new question, and treating either as one is how a reply answers
690/// itself. A mention whose run failed is not kept, so it is tried again.
691#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
692pub struct AnswerRecord {
693    #[serde(default)]
694    pub version: u32,
695    /// Mention key to what became of it.
696    #[serde(default)]
697    pub judged: BTreeMap<String, String>,
698    /// Runs `spar listen` started since a person last ran `spar answer` here.
699    #[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    /// A real problem that this PR did not cause. Those become follow-ups
713    /// rather than review comments, so they cannot gate an unrelated merge.
714    #[serde(default = "yes", deserialize_with = "de_bool_default_true")]
715    pub in_scope: bool,
716
717    // -- the parts of a bug report ---------------------------------------
718    //
719    // Filled when a finding is going to become an issue somebody picks up
720    // cold. `detail` is the one line the pull request thread shows; these are
721    // what a person needs when the thread is not in front of them. All
722    // optional: a finding that stays in the thread has no use for them.
723    /// What is wrong, with the specifics.
724    #[serde(default)]
725    pub problem: Option<String>,
726    /// Steps to reproduce it, and what actually happens.
727    #[serde(default)]
728    pub reproduction: Option<String>,
729    /// What it costs somebody.
730    #[serde(default)]
731    pub impact: Option<String>,
732    /// What it should do instead.
733    #[serde(default)]
734    pub expected: Option<String>,
735}
736
737impl Default for Finding {
738    /// A blank finding, for building one field at a time.
739    ///
740    /// Severity is spelled out here rather than derived, because a severity
741    /// arriving by default is exactly the mistake this codebase refuses
742    /// elsewhere: it is the field that decides whether a merge is gated, and
743    /// the least severe value is the only safe thing to assume.
744    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    /// The parts of a bug report this finding carries, in the order they are
761    /// written, skipping the ones it does not.
762    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}
806
807#[derive(Debug, Clone, Serialize, Deserialize)]
808pub struct Disposition {
809    #[serde(default, deserialize_with = "de_string")]
810    pub title: String,
811    /// Carried so a refutation lands on the same ledger key the reviewer's
812    /// finding will hash to next round. Without it the re-litigation guard
813    /// silently never fires for any finding that names a file.
814    #[serde(default, deserialize_with = "de_string")]
815    pub file: String,
816    pub action: Action,
817    #[serde(default, deserialize_with = "de_string")]
818    pub reasoning: String,
819    #[serde(default)]
820    pub new_issue_title: Option<String>,
821    #[serde(default)]
822    pub new_issue_body: Option<String>,
823}
824
825/// What a reviewer did about one of its own findings when it chose to fix them.
826///
827/// The other three editing calls return a structured report. This one returned
828/// free text, and three things were inferred from it: that every finding was
829/// fixed, what the commit subject should be, and that the author had nothing to
830/// answer. A reviewer that fixed two of three points and said so in prose had
831/// all three recorded as fixed.
832#[derive(Debug, Clone, Serialize, Deserialize)]
833pub struct OwnFix {
834    #[serde(default, deserialize_with = "de_string")]
835    pub title: String,
836    /// Carried for the same reason a disposition carries it: the ledger key has
837    /// to be the one the finding hashes to.
838    #[serde(default, deserialize_with = "de_string")]
839    pub file: String,
840    #[serde(deserialize_with = "de_bool")]
841    pub fixed: bool,
842    #[serde(default, deserialize_with = "de_string")]
843    pub reason: String,
844}
845
846#[derive(Debug, Clone, Serialize, Deserialize)]
847pub struct OwnFixDoc {
848    #[serde(default, deserialize_with = "de_string")]
849    pub summary: String,
850    #[serde(default)]
851    pub fixes: Vec<OwnFix>,
852}
853
854/// One reviewer's judgement of a finding the *other* reviewer raised.
855///
856/// This is the whole point of review only mode. A finding both models raise
857/// independently is worth a maintainer's attention; a finding one raised and
858/// the other examined and rejected is usually not, and saying so is more useful
859/// than forwarding both.
860#[derive(Debug, Clone, Serialize, Deserialize)]
861pub struct Adjudication {
862    #[serde(default, deserialize_with = "de_string")]
863    pub title: String,
864    #[serde(default, deserialize_with = "de_string")]
865    pub file: String,
866    /// Whether the defect is real, judged by reading the code rather than by
867    /// deferring to the other reviewer.
868    #[serde(deserialize_with = "de_bool")]
869    pub agrees: bool,
870    /// This reviewer's own view of how badly it matters.
871    pub severity: Severity,
872    #[serde(default, deserialize_with = "de_string")]
873    pub reasoning: String,
874}
875
876#[derive(Debug, Clone, Serialize, Deserialize)]
877pub struct AdjudicationDoc {
878    #[serde(default)]
879    pub verdicts: Vec<Adjudication>,
880}
881
882string_enum! {
883    /// What a second look found about one earlier finding.
884    pub enum Ruling {
885        /// The code now answers the point.
886        Fixed = "fixed" | "resolved" | "addressed" | "done",
887        /// The code did not change for it, and a response showed the point
888        /// was wrong or does not apply.
889        Rebutted = "rebutted" | "refuted" | "answered" | "withdrawn" | "not_a_bug",
890        /// Neither. The point stands, or the change made for it does not
891        /// settle it.
892        Open = "open" | "still_open" | "unresolved" | "stands" | "unfixed",
893    }
894}
895
896/// One reviewer's ruling on one earlier finding.
897#[derive(Debug, Clone, Serialize, Deserialize)]
898pub struct RecheckRuling {
899    /// The 1-based number the prompt gave the earlier finding. A number rather
900    /// than a title, for the reason the follow-up screen uses one: a model
901    /// rewrites titles, and a number it copies.
902    #[serde(deserialize_with = "de_i64")]
903    pub index: i64,
904    pub outcome: Ruling,
905    #[serde(default, deserialize_with = "de_string")]
906    pub reasoning: String,
907}
908
909/// What one reviewer answers on a second look: a ruling per earlier finding,
910/// and ordinary findings for anything new.
911#[derive(Debug, Clone, Default, Serialize, Deserialize)]
912pub struct RecheckDoc {
913    #[serde(default, deserialize_with = "de_string")]
914    pub summary: String,
915    #[serde(default)]
916    pub rulings: Vec<RecheckRuling>,
917    #[serde(default)]
918    pub findings: Vec<Finding>,
919}
920
921// ---------------------------------------------------------------------------
922// Brainstorming
923// ---------------------------------------------------------------------------
924
925/// One idea from a brainstorm: existing pieces, paired in a way that has not
926/// been done.
927///
928/// `combines` is the load bearing field. The premise of `spar brainstorm` is
929/// that the parts of an answer already exist and have not been put together, so
930/// an idea that cannot name its parts is a wish rather than a proposal, and
931/// `why_new` has to say what the nearest existing thing is rather than assert
932/// novelty.
933#[derive(Debug, Clone, Default, Serialize, Deserialize)]
934pub struct Idea {
935    #[serde(default, deserialize_with = "de_string")]
936    pub title: String,
937    /// The existing techniques, primitives, results, or patterns this pairs.
938    #[serde(default, deserialize_with = "de_string_vec")]
939    pub combines: Vec<String>,
940    #[serde(default, deserialize_with = "de_string")]
941    pub how_it_works: String,
942    /// The nearest thing that already exists, and how this differs from it.
943    #[serde(default, deserialize_with = "de_string")]
944    pub why_new: String,
945    #[serde(default, deserialize_with = "de_string")]
946    pub enables: String,
947    #[serde(default, deserialize_with = "de_string")]
948    pub risks: String,
949    /// The cheapest thing that would show whether it works.
950    #[serde(default, deserialize_with = "de_string")]
951    pub first_experiment: String,
952}
953
954#[derive(Debug, Clone, Default, Serialize, Deserialize)]
955pub struct IdeasDoc {
956    #[serde(default)]
957    pub ideas: Vec<Idea>,
958}
959
960string_enum! {
961    /// What one agent does with an idea the other proposed.
962    pub enum CrossKind {
963        Build = "build" | "extend" | "improve" | "combine",
964        Challenge = "challenge" | "reject" | "exists" | "object",
965        Keep = "keep" | "agree" | "accept" | "fine",
966    }
967}
968
969/// One agent's ruling on an idea the *other* agent proposed.
970#[derive(Debug, Clone, Serialize, Deserialize)]
971pub struct CrossVerdict {
972    /// The number the idea was given in the list, so the ruling can be matched
973    /// back to it. Titles are not used for this: a model rewrites them.
974    #[serde(default, deserialize_with = "de_i64")]
975    pub idea: i64,
976    pub verdict: CrossKind,
977    #[serde(default, deserialize_with = "de_string")]
978    pub reason: String,
979    /// The revised idea, when the verdict is build.
980    #[serde(default)]
981    pub build: Option<Idea>,
982}
983
984#[derive(Debug, Clone, Default, Serialize, Deserialize)]
985pub struct CrossDoc {
986    #[serde(default)]
987    pub verdicts: Vec<CrossVerdict>,
988}
989
990/// What the agent that proposed a challenged idea says to the objection.
991#[derive(Debug, Clone, Serialize, Deserialize)]
992pub struct Defence {
993    #[serde(default, deserialize_with = "de_i64")]
994    pub idea: i64,
995    /// True to stand by it with specifics, false to withdraw it.
996    #[serde(deserialize_with = "de_bool")]
997    pub stands: bool,
998    #[serde(default, deserialize_with = "de_string")]
999    pub reply: String,
1000}
1001
1002/// The last round's answer: defences for the agent's own challenged ideas, and
1003/// its ranking of everything still standing.
1004#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1005pub struct ConvergeDoc {
1006    #[serde(default)]
1007    pub defences: Vec<Defence>,
1008    /// Idea numbers, best first.
1009    #[serde(default, deserialize_with = "de_i64_vec")]
1010    pub ranking: Vec<i64>,
1011}
1012
1013/// A finding after both reviewers have had their say.
1014#[derive(Debug, Clone)]
1015pub struct Judged {
1016    pub finding: Finding,
1017    /// Who first raised it.
1018    pub raised_by: String,
1019    /// How it ended up.
1020    pub standing: Standing,
1021    /// The other reviewer's reasoning, when they had something to say.
1022    pub counterpoint: Option<String>,
1023    /// What the reviewer who raised it said when the objection came back.
1024    /// Kept apart from the objection: running both together behind a single
1025    /// "the other says" turns the most valuable content in the comment into
1026    /// one unreadable sentence.
1027    pub defence: Option<String>,
1028    /// The other reviewer's own severity, when the cross-check had it agree
1029    /// the defect is real. Not kept in the review record: the counterpoint
1030    /// says it in words, and nothing after the cross-check reads it.
1031    pub rated: Option<Severity>,
1032}
1033
1034string_enum! {
1035    /// How a finding stands after both reviewers have had their say. A word
1036    /// rather than a bare enum because the review record keeps it on disk.
1037    pub enum Standing {
1038        /// Both reviewers raised it independently. The strongest signal there is.
1039        Corroborated = "corroborated" | "both",
1040        /// One raised it, the other read the code and agreed.
1041        Confirmed = "confirmed",
1042        /// One raised it, the other read the code and rejected it, and it survived
1043        /// a rebuttal. Or the other agreed it is real but not on whether it
1044        /// blocks. A person decides.
1045        Disputed = "disputed",
1046        /// Raised, rejected, and withdrawn by the reviewer who raised it.
1047        Withdrawn = "withdrawn",
1048        /// Raised with nobody left to check it, because the round budget ran out.
1049        Unverified = "unverified" | "one_reviewer",
1050    }
1051}
1052
1053/// What the implementor did, and what the pull request body is built from.
1054///
1055/// Structured for the reason every other exchange here is structured: a model
1056/// asked for a description writes a paragraph about having written one, while a
1057/// model asked for a problem, a change list, and a way to check them answers
1058/// each of those. The body's substance comes from the fields being asked for
1059/// separately, and its brevity from spar composing them rather than the model
1060/// narrating.
1061#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1062pub struct Implementation {
1063    /// The issue should not be implemented. No changes, and `reason` says why.
1064    #[serde(default, deserialize_with = "de_bool")]
1065    pub not_worth_doing: bool,
1066    /// Only when declining. Posted on the issue, so it is written for whoever
1067    /// opened it rather than for the harness.
1068    #[serde(default, deserialize_with = "de_string")]
1069    pub reason: String,
1070    /// One sentence saying what changed. Leads the body.
1071    #[serde(default, deserialize_with = "de_string")]
1072    pub summary: String,
1073    /// What was actually wrong, as understood after reading the code. Not a
1074    /// restatement of the issue: the reviewer can follow the link.
1075    #[serde(default, deserialize_with = "de_string")]
1076    pub problem: String,
1077    /// One line per change that alters behaviour.
1078    #[serde(default)]
1079    pub changes: Vec<String>,
1080    /// How a reviewer confirms the change works.
1081    #[serde(default)]
1082    pub testing: Vec<String>,
1083    /// Anything the reviewer would otherwise have to ask about: a deliberate
1084    /// omission, a decision worth defending, a risk. Usually nothing.
1085    #[serde(default)]
1086    pub notes: Option<String>,
1087}
1088
1089#[derive(Debug, Clone, Serialize, Deserialize)]
1090pub struct ResponseDoc {
1091    #[serde(default, deserialize_with = "de_string")]
1092    pub summary: String,
1093    #[serde(default)]
1094    pub dispositions: Vec<Disposition>,
1095}
1096
1097// ---------------------------------------------------------------------------
1098// What spar keeps
1099// ---------------------------------------------------------------------------
1100
1101#[derive(Debug, Clone, Serialize, Deserialize)]
1102pub struct PlanItem {
1103    pub issue: i64,
1104    pub title: String,
1105    pub complexity: Complexity,
1106    pub risk: Risk,
1107    pub depends_on: Vec<i64>,
1108    pub reason: String,
1109}
1110
1111#[derive(Debug, Clone, Serialize, Deserialize)]
1112pub struct SkippedItem {
1113    pub issue: i64,
1114    pub title: String,
1115    /// Keyed by agent name, so the plan file says who said what.
1116    pub reasons: BTreeMap<String, String>,
1117    /// An umbrella or epic, which spar comments on and leaves open.
1118    ///
1119    /// Set when *either* agent said so, unlike everything else here, which
1120    /// needs both. Closing already requires agreement, on the principle that
1121    /// one agent's opinion is not enough to close somebody's report; one agent
1122    /// saying the issue is not finished is the same principle from the other
1123    /// side.
1124    #[serde(default)]
1125    pub tracker: bool,
1126}
1127
1128#[derive(Debug, Clone, Serialize, Deserialize)]
1129pub struct ContestedItem {
1130    pub issue: i64,
1131    pub title: String,
1132    /// Agent name to "do" or "skip".
1133    pub positions: BTreeMap<String, String>,
1134    pub reasons: BTreeMap<String, String>,
1135    #[serde(default, skip_serializing_if = "Option::is_none")]
1136    pub note: Option<String>,
1137}
1138
1139/// An issue triage disagreed about, remembered between runs.
1140///
1141/// A disagreement is the one triage outcome that needs a person, and it was
1142/// also the one that reached them least reliably: a log line suppressed by
1143/// `--quiet`, an entry in `plan.json`, and two calls spent on it again on every
1144/// later run.
1145#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1146pub struct Contested {
1147    #[serde(default)]
1148    pub title: String,
1149    /// Agent name to "do" or "skip".
1150    #[serde(default)]
1151    pub positions: BTreeMap<String, String>,
1152    #[serde(default)]
1153    pub reasons: BTreeMap<String, String>,
1154}
1155
1156#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1157pub struct Plan {
1158    #[serde(default)]
1159    pub order: Vec<PlanItem>,
1160    #[serde(default)]
1161    pub skipped: Vec<SkippedItem>,
1162    #[serde(default)]
1163    pub contested: Vec<ContestedItem>,
1164}
1165
1166string_enum! {
1167    /// How a point stands, one round to the next.
1168    ///
1169    /// Three of these are endings: the code will not change for the point here,
1170    /// so raising it again only spends a round. They do not mean the same thing
1171    /// to a person, which is why `Dropped` is not folded into `Filed`: only
1172    /// `Filed` promises that somewhere holds the point.
1173    ///
1174    /// `Fixed` is not an ending. The code changed, the change is the author's
1175    /// claim about the point, and nothing has checked it. It is here because the
1176    /// ledger is the only thing a later round reads, and recording nothing for a
1177    /// fix left it holding only the points the reviewer lost. Six fix rounds
1178    /// across two pull requests produced no entry at all, and the guard that
1179    /// ends an argument had nothing to match.
1180    pub enum Settled {
1181        Refuted = "refuted" | "refute" | "rejected",
1182        Filed = "filed" | "filed_issue" | "filed-issue" | "out_of_scope",
1183        Dropped = "dropped" | "not_filed" | "not-filed" | "unfiled",
1184        Fixed = "fixed" | "fix" | "changed",
1185    }
1186}
1187
1188impl Default for Settled {
1189    /// State written before the ledger held anything but refutations.
1190    fn default() -> Self {
1191        Settled::Refuted
1192    }
1193}
1194
1195/// What one attempt to record a follow-up actually did.
1196///
1197/// The distinction the ledger needs. A point written down somewhere is settled
1198/// and tracked; a point deliberately not written down is settled and untracked;
1199/// a point that failed to be written down is not settled at all, and saying it
1200/// was loses it. A single `Option<String>` collapsed all three into "no URL".
1201#[derive(Debug, Clone, PartialEq, Eq)]
1202pub enum Followup {
1203    /// A tracker issue or a local note now carries it. The string is what a
1204    /// reader is shown: an issue URL, or a note line.
1205    Recorded(String),
1206    /// Something already covers it and nothing was written: a closed issue, or
1207    /// a note the local queue still holds. There is a reference to point at,
1208    /// but no new work to hand anyone.
1209    Covered(String),
1210    /// Deliberately not recorded, with the reason. Follow-ups are off, or the
1211    /// run has spent its cap.
1212    Dropped(&'static str),
1213    /// Nothing was written and nothing covers it. The point is still open, so
1214    /// the next round is free to try again.
1215    Failed,
1216}
1217
1218impl Followup {
1219    /// The reference to add to the run's filed list, when there is a live one.
1220    ///
1221    /// `Covered` is deliberately excluded: a closed issue reported as filed
1222    /// goes back into a wave to be implemented again.
1223    pub fn url(&self) -> Option<&str> {
1224        match self {
1225            Followup::Recorded(url) => Some(url),
1226            _ => None,
1227        }
1228    }
1229}
1230
1231#[derive(Debug, Clone, Serialize, Deserialize)]
1232pub struct LedgerEntry {
1233    pub title: String,
1234    pub file: String,
1235    pub reasoning: String,
1236    pub round: u32,
1237    #[serde(default)]
1238    pub reraised: u32,
1239    #[serde(default)]
1240    pub outcome: Settled,
1241}
1242
1243/// Settled points, keyed by the review loop's finding identity. Ordered so the settled block in a
1244/// prompt is stable between rounds, which keeps prompt caches warm and diffs
1245/// readable.
1246pub type Ledger = BTreeMap<String, LedgerEntry>;
1247
1248#[derive(Debug, Clone, Serialize, Deserialize)]
1249pub struct Dispute {
1250    pub title: String,
1251    #[serde(default, deserialize_with = "de_string")]
1252    pub file: String,
1253    pub reasoning: String,
1254}
1255
1256/// The outcome of working one issue, or resuming one PR.
1257#[derive(Debug, Clone, Serialize, Deserialize)]
1258pub struct IssueRun {
1259    pub issue: i64,
1260    pub title: String,
1261    pub status: Status,
1262    #[serde(default, skip_serializing_if = "Option::is_none")]
1263    pub pr: Option<String>,
1264    #[serde(default)]
1265    pub rounds: u32,
1266    #[serde(default)]
1267    pub disputes: Vec<Dispute>,
1268    #[serde(default)]
1269    pub filed: Vec<String>,
1270    /// Real points a reviewer judged smaller than another round.
1271    ///
1272    /// Nothing else carries them. The round comment is off under the default
1273    /// `pr_comments = "outcome"` and a non-blocking finding is not filed under
1274    /// the default `file_non_blocking = false`, so without this the severity
1275    /// ladder is a way to make a finding disappear rather than a way to stop it
1276    /// costing a round. Silence on a pull request should mean nothing was
1277    /// found, not that nothing was gated.
1278    #[serde(default)]
1279    pub noted: Vec<Finding>,
1280    #[serde(default)]
1281    pub notes: Vec<String>,
1282    /// Runtime circuit breaker after an external follow-up write could not be
1283    /// verified. A later invocation rechecks GitHub before any new write.
1284    #[serde(skip)]
1285    pub followup_writes_uncertain: bool,
1286}
1287
1288impl IssueRun {
1289    pub fn new(issue: i64, title: impl Into<String>) -> Self {
1290        Self {
1291            issue,
1292            title: title.into(),
1293            status: Status::Pending,
1294            pr: None,
1295            rounds: 0,
1296            disputes: Vec::new(),
1297            filed: Vec::new(),
1298            noted: Vec::new(),
1299            notes: Vec::new(),
1300            followup_writes_uncertain: false,
1301        }
1302    }
1303
1304    /// Whether this outcome counts as the run having done its job.
1305    ///
1306    /// A review that produced findings did its job: the findings are the
1307    /// product, and a PR needing work is not a failure of the reviewer.
1308    pub fn succeeded(&self) -> bool {
1309        matches!(
1310            self.status,
1311            Status::Merged
1312                | Status::Approved
1313                | Status::Abandoned
1314                | Status::Reviewed
1315                | Status::Clean
1316                | Status::Answered
1317                // A split that correctly decided nothing needed splitting did
1318                // its job. Without Whole here, `spar split` over a tidy queue
1319                // exits non-zero, which in a script reads as a failure.
1320                | Status::Split
1321                | Status::Whole
1322        )
1323    }
1324}
1325
1326/// Everything needed to pick a review back up, including on another machine.
1327#[derive(Debug, Clone, Serialize, Deserialize)]
1328pub struct PersistedState {
1329    pub version: u32,
1330    /// Monotonic checkpoint order for writes within this repository.
1331    #[serde(default)]
1332    pub checkpoint: u64,
1333    pub round: u32,
1334    pub next_actor: String,
1335    pub status: Status,
1336    /// Published pull request head to which this checkpoint applies.
1337    #[serde(default, skip_serializing_if = "String::is_empty")]
1338    pub pr_head: String,
1339    #[serde(default)]
1340    pub ledger: Ledger,
1341    #[serde(default)]
1342    pub filed: Vec<String>,
1343    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1344    pub open_findings: Vec<Finding>,
1345    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1346    pub disputes: Vec<Dispute>,
1347    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1348    pub noted: Vec<Finding>,
1349}
1350
1351pub const STATE_VERSION: u32 = 2;
1352
1353/// One finding as the review record keeps it: enough to list it again, rule on
1354/// it, and post it, and nothing a model is not asked for. The parts of a bug
1355/// report a `Finding` may carry are for an issue filed from it, which a record
1356/// never does.
1357#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1358pub struct RecordedFinding {
1359    pub title: String,
1360    #[serde(default)]
1361    pub file: String,
1362    pub severity: Severity,
1363    #[serde(default)]
1364    pub detail: String,
1365    #[serde(default = "yes")]
1366    pub in_scope: bool,
1367    #[serde(default)]
1368    pub raised_by: String,
1369    pub standing: Standing,
1370    #[serde(default, skip_serializing_if = "Option::is_none")]
1371    pub counterpoint: Option<String>,
1372    #[serde(default, skip_serializing_if = "Option::is_none")]
1373    pub defence: Option<String>,
1374}
1375
1376impl RecordedFinding {
1377    pub fn blocks(&self) -> bool {
1378        self.severity == Severity::Blocking && self.in_scope
1379    }
1380
1381    pub fn where_at(&self) -> &str {
1382        if self.file.trim().is_empty() {
1383            "general"
1384        } else {
1385            self.file.trim()
1386        }
1387    }
1388
1389    /// Back to the in-memory shape, for the renderer and the record that
1390    /// follows a second look.
1391    pub fn to_judged(&self) -> Judged {
1392        Judged {
1393            finding: Finding {
1394                severity: self.severity,
1395                title: self.title.clone(),
1396                detail: self.detail.clone(),
1397                file: self.file.clone(),
1398                in_scope: self.in_scope,
1399                ..Finding::default()
1400            },
1401            raised_by: self.raised_by.clone(),
1402            standing: self.standing,
1403            counterpoint: self.counterpoint.clone(),
1404            defence: self.defence.clone(),
1405            rated: None,
1406        }
1407    }
1408}
1409
1410impl From<&Judged> for RecordedFinding {
1411    fn from(j: &Judged) -> Self {
1412        Self {
1413            title: j.finding.title.clone(),
1414            file: j.finding.file.clone(),
1415            severity: j.finding.severity,
1416            detail: j.finding.detail.clone(),
1417            in_scope: j.finding.in_scope,
1418            raised_by: j.raised_by.clone(),
1419            standing: j.standing,
1420            counterpoint: j.counterpoint.clone(),
1421            defence: j.defence.clone(),
1422        }
1423    }
1424}
1425
1426/// What `spar review` leaves behind, and what a second look reads and rewrites.
1427///
1428/// `spar review` used to leave nothing machine readable: not the commit it
1429/// read, not the points it raised. There was therefore nothing to check a later
1430/// push against, and the only second look possible was a first look again.
1431#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1432pub struct ReviewRecord {
1433    pub version: u32,
1434    /// The commit the review worktree had checked out when the reviewers read
1435    /// it. From `git rev-parse HEAD` there, never from a second `gh` call.
1436    pub head: String,
1437    /// When the review began, in the one shape GitHub returns,
1438    /// `2026-10-20T18:04:05Z`, so it compares with a comment's `created_at`
1439    /// as a string. The start rather than the end, so a reply made while a
1440    /// long review ran still counts as new on the next look.
1441    pub reviewed_at: String,
1442    #[serde(default)]
1443    pub findings: Vec<RecordedFinding>,
1444    /// Second looks taken so far, which `[listen] max_rechecks` caps.
1445    #[serde(default)]
1446    pub rechecks: u32,
1447    /// The formal verdict posted, when one was. None for a plain comment.
1448    #[serde(default, skip_serializing_if = "Option::is_none")]
1449    pub verdict: Option<ReviewVerdict>,
1450    /// Whether the review reached the pull request. A dry run's record is kept
1451    /// so `spar post` can complete it, but nobody has seen its findings, so it
1452    /// does not count as a review to take a second look after.
1453    #[serde(default)]
1454    pub posted: bool,
1455}
1456
1457pub const REVIEW_RECORD_VERSION: u32 = 1;
1458
1459impl ReviewRecord {
1460    pub fn short_head(&self) -> &str {
1461        let end = self.head.len().min(7);
1462        &self.head[..end]
1463    }
1464
1465    /// The points a second look rules on: everything but what was withdrawn.
1466    pub fn open_points(&self) -> impl Iterator<Item = &RecordedFinding> {
1467        self.findings
1468            .iter()
1469            .filter(|f| f.standing != Standing::Withdrawn)
1470    }
1471}
1472
1473/// A finding placed on the line it is about, to travel with a review.
1474///
1475/// `line` is on the new side of the diff, and `start_line`, when there is one,
1476/// makes it a range ending there. Both are lines GitHub will accept: it refuses
1477/// the whole review if any comment names a line the diff does not show.
1478#[derive(Debug, Clone, PartialEq, Eq)]
1479pub struct InlineComment {
1480    pub path: String,
1481    pub line: u32,
1482    pub start_line: Option<u32>,
1483    pub body: String,
1484}
1485
1486// ---------------------------------------------------------------------------
1487// What gh returns
1488// ---------------------------------------------------------------------------
1489
1490#[derive(Debug, Clone, Deserialize)]
1491pub struct Label {
1492    #[serde(default)]
1493    pub name: String,
1494}
1495
1496#[derive(Debug, Clone, Deserialize, Default)]
1497pub struct Author {
1498    #[serde(default)]
1499    pub login: String,
1500}
1501
1502/// A login, never empty. A deleted account is null on GitHub and becomes
1503/// `ghost`, which no trust setting but `anyone` will act on.
1504pub fn login_of(author: Option<&Author>) -> &str {
1505    match author.map(|a| a.login.trim()) {
1506        Some(login) if !login.is_empty() => login,
1507        _ => "ghost",
1508    }
1509}
1510
1511/// One top level comment on an issue, as `gh issue view --json comments`
1512/// returns it, oldest first.
1513#[derive(Debug, Clone, Deserialize, Default)]
1514#[serde(rename_all = "camelCase")]
1515pub struct IssueComment {
1516    /// Null when the account was deleted.
1517    #[serde(default)]
1518    pub author: Option<Author>,
1519    #[serde(default)]
1520    pub author_association: String,
1521    /// Whether the authenticated GitHub user wrote this comment.
1522    #[serde(default)]
1523    pub viewer_did_author: bool,
1524    #[serde(default)]
1525    pub body: String,
1526    #[serde(default)]
1527    pub created_at: String,
1528    #[serde(default)]
1529    pub is_minimized: bool,
1530}
1531
1532impl IssueComment {
1533    pub fn login(&self) -> &str {
1534        login_of(self.author.as_ref())
1535    }
1536}
1537
1538#[derive(Debug, Clone, Deserialize)]
1539pub struct Issue {
1540    pub number: i64,
1541    #[serde(default)]
1542    pub title: String,
1543    #[serde(default)]
1544    pub body: Option<String>,
1545    #[serde(default)]
1546    pub state: String,
1547    /// Why it was closed: `completed` or `not_planned`, empty when open or
1548    /// when the field was not asked for.
1549    ///
1550    /// The tracker's tick means the work landed, and a closed issue on its own
1551    /// does not say that. With `close_skipped = true`, the default, an item
1552    /// both agents declined is closed as not planned, and ticking it writes
1553    /// "this was done" into somebody's checklist.
1554    #[serde(default, rename = "stateReason")]
1555    pub state_reason: Option<String>,
1556    #[serde(default)]
1557    pub url: String,
1558    #[serde(default)]
1559    pub labels: Vec<Label>,
1560    /// Who filed it. None when the field was not asked for.
1561    #[serde(default)]
1562    pub author: Option<Author>,
1563    /// What was said on it since it was filed. Empty when the field was not
1564    /// asked for, which a listing of the whole queue never does.
1565    #[serde(default)]
1566    pub comments: Vec<IssueComment>,
1567}
1568
1569impl Issue {
1570    pub fn body_text(&self) -> &str {
1571        self.body.as_deref().unwrap_or("")
1572    }
1573
1574    /// The body as a prompt carries it, and whether anything was left off.
1575    ///
1576    /// Shortened only past `max`, which is sized so that nothing a person
1577    /// wrote ever reaches it. When it does fire the cut is announced in the
1578    /// text itself: an agent handed a fragment with no marker has no way to
1579    /// tell it from an issue that simply ended there, so it judges the part it
1580    /// saw and reports the confidence of having seen all of it.
1581    ///
1582    /// The cut lands on a line boundary, and an unbalanced code fence is closed
1583    /// rather than left hanging. Broken markdown reads as a defect in the issue
1584    /// and costs the model attention to rule out.
1585    pub fn body_for_prompt(&self, max: usize) -> (String, bool) {
1586        let body = self.body_text().trim();
1587        if body.chars().count() <= max {
1588            return (body.to_string(), false);
1589        }
1590        let clipped: String = body.chars().take(max).collect();
1591        let mut kept = match clipped.rfind('\n') {
1592            Some(at) => clipped[..at].to_string(),
1593            None => clipped,
1594        };
1595        if kept.matches("```").count() % 2 == 1 {
1596            kept.push_str("\n```");
1597        }
1598        kept.push_str("\n\n[Shortened to fit. The rest of this issue was not included.]");
1599        (kept, true)
1600    }
1601
1602    pub fn is_closed(&self) -> bool {
1603        self.state.eq_ignore_ascii_case("closed")
1604    }
1605
1606    /// Closed because the work was done, rather than because somebody decided
1607    /// not to do it.
1608    ///
1609    /// An unknown reason counts as completed: GitHub leaves `stateReason`
1610    /// empty on issues closed before it existed, and reading those as declined
1611    /// would leave every old checklist unticked.
1612    pub fn closed_as_completed(&self) -> bool {
1613        self.is_closed() && !self.closed_as_not_planned()
1614    }
1615
1616    pub fn closed_as_not_planned(&self) -> bool {
1617        self.is_closed()
1618            && self
1619                .state_reason
1620                .as_deref()
1621                .is_some_and(|reason| reason.eq_ignore_ascii_case("not_planned"))
1622    }
1623}
1624
1625#[derive(Debug, Clone, Deserialize)]
1626pub struct PrRef {
1627    pub number: i64,
1628    #[serde(default)]
1629    pub url: String,
1630    #[serde(default)]
1631    pub title: String,
1632}
1633
1634#[derive(Debug, Clone, Deserialize)]
1635pub struct IssueRef {
1636    pub number: i64,
1637}
1638
1639/// An open pull request's size, as one listing call reports it.
1640///
1641/// Enough for the screen to say whether a change is worth splitting without
1642/// fetching its head, which would be one network round trip per pull request
1643/// for a question whose answer is usually no.
1644#[derive(Debug, Clone, Default, Deserialize)]
1645#[serde(rename_all = "camelCase")]
1646pub struct PrRow {
1647    pub number: i64,
1648    #[serde(default)]
1649    pub title: String,
1650    #[serde(default)]
1651    pub changed_files: i64,
1652    #[serde(default)]
1653    pub additions: i64,
1654    #[serde(default)]
1655    pub deletions: i64,
1656}
1657
1658impl PrRow {
1659    /// The size, as the screen prompt carries it.
1660    pub fn size(&self) -> String {
1661        format!(
1662            "{} file(s), +{} -{}",
1663            self.changed_files, self.additions, self.deletions
1664        )
1665    }
1666}
1667
1668#[derive(Debug, Clone, Deserialize)]
1669#[serde(rename_all = "camelCase")]
1670pub struct PrView {
1671    pub number: i64,
1672    #[serde(default)]
1673    pub url: String,
1674    #[serde(default)]
1675    pub title: String,
1676    /// The description, which is the author's own account of the change. Read
1677    /// by every pass that judges whether the change does what it claims.
1678    #[serde(default)]
1679    pub body: String,
1680    #[serde(default)]
1681    pub head_ref_name: String,
1682    #[serde(default)]
1683    pub base_ref_name: String,
1684    #[serde(default)]
1685    pub state: String,
1686    #[serde(default)]
1687    pub closing_issues_references: Vec<IssueRef>,
1688    /// True when the PR's head branch lives on a fork rather than this
1689    /// repository.
1690    #[serde(default)]
1691    pub is_cross_repository: bool,
1692    /// Who owns the repository the head branch is in: for a pull request
1693    /// from a fork, the fork's owner. That is what tells the authenticated
1694    /// user's own fork, which spar can push to, from anybody else's.
1695    #[serde(default)]
1696    pub head_repository_owner: Option<Author>,
1697    /// The repository the head branch is in.
1698    #[serde(default)]
1699    pub head_repository: Option<HeadRepository>,
1700}
1701
1702#[derive(Debug, Clone, Default, Deserialize)]
1703pub struct HeadRepository {
1704    #[serde(default)]
1705    pub name: String,
1706}
1707
1708/// The fields a sweep reads from `gh pr list` and `gh pr view`: enough to
1709/// notice a head that moved, a review request, an assignment, and a close.
1710pub const PR_SWEEP_FIELDS: &str =
1711    "number,title,headRefOid,updatedAt,author,isDraft,isCrossRepository,reviewRequests,assignees,state";
1712
1713/// One row of `gh pr list --json PR_SWEEP_FIELDS`, or of `gh pr view` with
1714/// the same fields.
1715#[derive(Debug, Clone, Default, Deserialize)]
1716#[serde(rename_all = "camelCase")]
1717pub struct PrSweepRow {
1718    pub number: i64,
1719    #[serde(default)]
1720    pub title: String,
1721    #[serde(default)]
1722    pub head_ref_oid: String,
1723    #[serde(default)]
1724    pub updated_at: String,
1725    #[serde(default)]
1726    pub author: Option<Author>,
1727    #[serde(default)]
1728    pub is_draft: bool,
1729    #[serde(default)]
1730    pub is_cross_repository: bool,
1731    #[serde(default)]
1732    pub review_requests: Vec<Login>,
1733    #[serde(default)]
1734    pub assignees: Vec<Login>,
1735    /// OPEN, CLOSED, or MERGED.
1736    #[serde(default)]
1737    pub state: String,
1738}
1739
1740/// A user in a `reviewRequests` or `assignees` array. A team entry has `name`
1741/// and `slug` instead, which reads as an empty login and never matches the
1742/// viewer.
1743#[derive(Debug, Clone, Default, Deserialize)]
1744pub struct Login {
1745    #[serde(default)]
1746    pub login: String,
1747    /// A team's `org/slug`, as gh gives it. Empty for a user.
1748    #[serde(default)]
1749    pub slug: String,
1750}
1751
1752/// One review request from a pull request's timeline: when it was made, and
1753/// who it asked, a user by `login` or a team by `slug` as in `Login`.
1754#[derive(Debug, Clone, Default)]
1755pub struct ReviewRequested {
1756    pub at: String,
1757    pub who: Login,
1758}
1759
1760/// Issues and pull requests share one number sequence per repository, so a
1761/// number names exactly one of them and spar can work out which.
1762#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1763#[serde(rename_all = "lowercase")]
1764pub enum ItemKind {
1765    Issue,
1766    Pr,
1767}
1768
1769impl std::fmt::Display for ItemKind {
1770    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1771        f.write_str(match self {
1772            ItemKind::Issue => "issue",
1773            ItemKind::Pr => "pull request",
1774        })
1775    }
1776}
1777
1778impl PrView {
1779    pub fn is_open(&self) -> bool {
1780        self.state.eq_ignore_ascii_case("open")
1781    }
1782}
1783
1784/// Where a pull request's head stands right now, asked two ways.
1785///
1786/// GitHub moves a pull request to a pushed commit some time after the push,
1787/// usually seconds and sometimes minutes, and until then `headRefOid` and
1788/// `refs/pull/N/head` both name the commit before it. The branch itself moves
1789/// with the push. A look that trusted the pull request alone read the commit
1790/// before a push, and by the time it posted its verdict was two pushes old.
1791#[derive(Debug, Clone, PartialEq, Eq)]
1792pub struct LiveHead {
1793    /// The head GitHub's pull request names.
1794    pub pull: String,
1795    /// Where the branch is, for a branch in this repository. None for a fork,
1796    /// whose branch `origin` does not have.
1797    pub branch: Option<String>,
1798}
1799
1800impl LiveHead {
1801    /// The head, once the pull request and its branch agree on it.
1802    pub fn settled(&self) -> Option<&str> {
1803        match &self.branch {
1804            Some(branch) if !branch.eq_ignore_ascii_case(&self.pull) => None,
1805            _ => Some(&self.pull),
1806        }
1807    }
1808
1809    /// The newer head when either differs from the one a look read. The
1810    /// branch is asked first, since it moves before the pull request does.
1811    pub fn moved_from(&self, reviewed: &str) -> Option<&str> {
1812        self.branch
1813            .as_deref()
1814            .filter(|branch| !branch.eq_ignore_ascii_case(reviewed))
1815            .or_else(|| (!self.pull.eq_ignore_ascii_case(reviewed)).then_some(self.pull.as_str()))
1816    }
1817}
1818
1819#[cfg(test)]
1820mod tests {
1821    use super::*;
1822
1823    #[test]
1824    fn severity_accepts_the_canonical_spelling() {
1825        assert_eq!(
1826            Some(Severity::NonBlocking),
1827            Severity::parse_lenient("non-blocking")
1828        );
1829    }
1830
1831    #[test]
1832    fn severity_accepts_near_misses() {
1833        for text in ["NonBlocking", "non_blocking", " NON-BLOCKING ", "minor"] {
1834            assert_eq!(
1835                Some(Severity::NonBlocking),
1836                Severity::parse_lenient(text),
1837                "{text}"
1838            );
1839        }
1840    }
1841
1842    #[test]
1843    fn severity_rejects_nonsense() {
1844        assert_eq!(None, Severity::parse_lenient("catastrophic-ish"));
1845    }
1846
1847    #[test]
1848    fn complexity_ordering_is_cheapest_first() {
1849        assert!(Complexity::S.rank() < Complexity::M.rank());
1850        assert!(Complexity::M.rank() < Complexity::L.rank());
1851    }
1852
1853    #[test]
1854    fn finding_defaults_to_in_scope() {
1855        let f: Finding = serde_json::from_value(serde_json::json!({
1856            "severity": "blocking", "title": "t", "detail": "d", "file": "a.rs"
1857        }))
1858        .unwrap();
1859        assert!(f.in_scope);
1860        assert!(f.blocks());
1861    }
1862
1863    #[test]
1864    fn out_of_scope_blocking_does_not_block() {
1865        let f: Finding = serde_json::from_value(serde_json::json!({
1866            "severity": "blocking", "title": "t", "detail": "d",
1867            "file": "a.rs", "in_scope": false
1868        }))
1869        .unwrap();
1870        assert!(!f.blocks());
1871    }
1872
1873    #[test]
1874    fn triage_tolerates_a_quoted_issue_number() {
1875        let v: TriageVerdict = serde_json::from_value(serde_json::json!({
1876            "issue": "#42", "worth_doing": "yes", "reason": "r",
1877            "complexity": "medium", "depends_on": ["39"], "risk": "low"
1878        }))
1879        .unwrap();
1880        assert_eq!(42, v.issue);
1881        assert!(v.worth_doing);
1882        assert_eq!(Complexity::M, v.complexity);
1883        assert_eq!(vec![39], v.depends_on);
1884    }
1885
1886    #[test]
1887    fn triage_tolerates_a_missing_depends_on() {
1888        let v: TriageVerdict = serde_json::from_value(serde_json::json!({
1889            "issue": 1, "worth_doing": false, "reason": "r",
1890            "complexity": "s", "risk": "high"
1891        }))
1892        .unwrap();
1893        assert!(v.depends_on.is_empty());
1894    }
1895
1896    #[test]
1897    fn review_tolerates_a_missing_findings_array() {
1898        let r: Review = serde_json::from_value(serde_json::json!({
1899            "verdict": "approve", "next_action": "merge", "summary": "fine"
1900        }))
1901        .unwrap();
1902        assert!(r.findings.is_empty());
1903    }
1904
1905    #[test]
1906    fn a_null_reason_is_an_empty_string_not_a_failure() {
1907        let v: TriageVerdict = serde_json::from_value(serde_json::json!({
1908            "issue": 1, "worth_doing": true, "reason": null,
1909            "complexity": "s", "depends_on": [], "risk": "low"
1910        }))
1911        .unwrap();
1912        assert_eq!("", v.reason);
1913    }
1914
1915    #[test]
1916    fn unknown_severity_is_an_error_not_a_silent_downgrade() {
1917        let out: Result<Finding, _> = serde_json::from_value(serde_json::json!({
1918            "severity": "showstopper-maybe", "title": "t", "detail": "d", "file": "a.rs"
1919        }));
1920        assert!(out.is_err());
1921    }
1922
1923    /// A `spar split` that correctly decided nothing needed splitting did its
1924    /// job. Without both of these in `succeeded`, it exits non-zero over a tidy
1925    /// queue, which in a script reads as a failure.
1926    #[test]
1927    fn deciding_not_to_split_is_not_a_failure() {
1928        for status in [Status::Split, Status::Whole] {
1929            let mut run = IssueRun::new(1, "t");
1930            run.status = status;
1931            assert!(run.succeeded(), "{status}");
1932        }
1933    }
1934
1935    #[test]
1936    fn status_round_trips_through_json() {
1937        let run = IssueRun::new(4, "t");
1938        let text = serde_json::to_string(&run).unwrap();
1939        let back: IssueRun = serde_json::from_str(&text).unwrap();
1940        assert_eq!(Status::Pending, back.status);
1941    }
1942
1943    /// Nothing was posted, so a script that runs `spar review` has something
1944    /// to try again.
1945    #[test]
1946    fn a_look_whose_head_moved_did_not_do_its_job() {
1947        let mut run = IssueRun::new(4, "t");
1948        run.status = Status::Moved;
1949        assert!(!run.succeeded());
1950        let text = serde_json::to_string(&run).unwrap();
1951        assert!(text.contains("\"moved\""), "{text}");
1952        let back: IssueRun = serde_json::from_str(&text).unwrap();
1953        assert_eq!(Status::Moved, back.status);
1954    }
1955
1956    fn live(pull: &str, branch: Option<&str>) -> LiveHead {
1957        LiveHead {
1958            pull: pull.into(),
1959            branch: branch.map(String::from),
1960        }
1961    }
1962
1963    /// A branch can be at the pushed commit for minutes while its pull request
1964    /// still names the one before.
1965    #[test]
1966    fn a_head_is_settled_only_once_the_pull_request_has_caught_up_with_its_branch() {
1967        assert_eq!(None, live("fb3a7ab", Some("2d5e2b5")).settled());
1968        assert_eq!(Some("2d5e2b5"), live("2d5e2b5", Some("2d5e2b5")).settled());
1969        assert_eq!(Some("2d5e2b5"), live("2d5e2b5", Some("2D5E2B5")).settled());
1970        // A fork's branch is not on origin, so the pull request is all there is.
1971        assert_eq!(Some("fb3a7ab"), live("fb3a7ab", None).settled());
1972    }
1973
1974    #[test]
1975    fn a_head_moved_from_the_reviewed_one_names_the_newer_commit() {
1976        assert_eq!(None, live("fb3a7ab", Some("fb3a7ab")).moved_from("fb3a7ab"));
1977        assert_eq!(None, live("FB3A7AB", None).moved_from("fb3a7ab"));
1978        // The branch moves first, so it is the newer of the two.
1979        assert_eq!(
1980            Some("c493635"),
1981            live("2d5e2b5", Some("c493635")).moved_from("fb3a7ab")
1982        );
1983        assert_eq!(
1984            Some("c493635"),
1985            live("fb3a7ab", Some("c493635")).moved_from("fb3a7ab")
1986        );
1987        assert_eq!(Some("2d5e2b5"), live("2d5e2b5", None).moved_from("fb3a7ab"));
1988        assert_eq!(
1989            Some("2d5e2b5"),
1990            live("2d5e2b5", Some("fb3a7ab")).moved_from("fb3a7ab")
1991        );
1992    }
1993}
1994
1995#[cfg(test)]
1996mod body_for_prompt_tests {
1997    use super::*;
1998
1999    fn issue(body: &str) -> Issue {
2000        let mut i: Issue = serde_json::from_value(serde_json::json!({
2001            "number": 1, "title": "t", "state": "open", "url": "u"
2002        }))
2003        .expect("an issue");
2004        i.body = Some(body.to_string());
2005        i
2006    }
2007
2008    /// The case that is every real issue: nothing is touched and nothing is
2009    /// claimed to be.
2010    #[test]
2011    fn an_issue_that_fits_is_handed_over_whole() {
2012        let (body, cut) = issue("The guard is inverted.").body_for_prompt(60_000);
2013        assert_eq!("The guard is inverted.", body);
2014        assert!(!cut);
2015    }
2016
2017    /// A fragment with no marker is indistinguishable from an issue that ended
2018    /// there, so the agent judges what it saw with the confidence of having
2019    /// seen everything. That is what the silent caps did.
2020    #[test]
2021    fn a_shortened_body_says_so_in_the_text() {
2022        let long = "line of text\n".repeat(500);
2023        let (body, cut) = issue(&long).body_for_prompt(200);
2024        assert!(cut);
2025        assert!(body.contains("Shortened to fit"), "{body}");
2026        assert!(body.len() < long.len());
2027    }
2028
2029    /// Broken markdown reads as a defect in the issue, and costs the model
2030    /// attention to rule out.
2031    #[test]
2032    fn a_cut_never_leaves_a_code_fence_open() {
2033        let body = format!("intro\n\n```rust\n{}\n```\n", "let x = 1;\n".repeat(200));
2034        let (out, cut) = issue(&body).body_for_prompt(120);
2035        assert!(cut);
2036        assert_eq!(0, out.matches("```").count() % 2, "{out}");
2037    }
2038
2039    /// Cutting mid-word turns the last thing the agent reads into nonsense.
2040    #[test]
2041    fn a_cut_lands_on_a_line_boundary() {
2042        let body = "aaaa bbbb cccc\n".repeat(100);
2043        let (out, _) = issue(&body).body_for_prompt(100);
2044        let kept = out.split("\n\n[Shortened").next().expect("the kept part");
2045        assert!(kept.ends_with("cccc"), "{kept:?}");
2046    }
2047}
2048
2049#[cfg(test)]
2050mod review_record_tests {
2051    use super::*;
2052
2053    fn judged() -> Judged {
2054        Judged {
2055            finding: Finding {
2056                severity: Severity::Blocking,
2057                title: "Retry loop never terminates".into(),
2058                detail: "the guard compares against Some(0)".into(),
2059                file: "src/net.rs:88".into(),
2060                in_scope: true,
2061                problem: Some("dropped on the way to the record".into()),
2062                ..Finding::default()
2063            },
2064            raised_by: "claude and codex".into(),
2065            standing: Standing::Corroborated,
2066            counterpoint: None,
2067            defence: Some("stands".into()),
2068            rated: None,
2069        }
2070    }
2071
2072    #[test]
2073    fn a_review_record_round_trips_through_json_and_keeps_its_standing_as_a_word() {
2074        let record = ReviewRecord {
2075            version: REVIEW_RECORD_VERSION,
2076            head: "0123abcdef".into(),
2077            reviewed_at: "2026-10-20T18:04:05Z".into(),
2078            findings: vec![RecordedFinding::from(&judged())],
2079            rechecks: 2,
2080            verdict: Some(ReviewVerdict::RequestChanges),
2081            posted: true,
2082        };
2083        let text = serde_json::to_string_pretty(&record).unwrap();
2084        assert!(text.contains("\"standing\": \"corroborated\""), "{text}");
2085        assert!(text.contains("\"verdict\": \"request_changes\""), "{text}");
2086        assert!(text.contains("\"severity\": \"blocking\""), "{text}");
2087        assert!(!text.contains("problem"), "{text}");
2088        let back: ReviewRecord = serde_json::from_str(&text).unwrap();
2089        assert_eq!(record, back);
2090        assert_eq!("0123abc", back.short_head());
2091    }
2092
2093    #[test]
2094    fn a_record_missing_the_newer_fields_still_reads() {
2095        let text = r#"{"version":1,"head":"abc","reviewed_at":"2026-10-20T18:04:05Z",
2096            "findings":[{"title":"T","severity":"nit","standing":"one_reviewer"}]}"#;
2097        let back: ReviewRecord = serde_json::from_str(text).unwrap();
2098        assert_eq!(0, back.rechecks);
2099        assert!(!back.posted);
2100        assert_eq!(None, back.verdict);
2101        assert!(back.findings[0].in_scope);
2102        assert_eq!(Standing::Unverified, back.findings[0].standing);
2103        assert_eq!("general", back.findings[0].where_at());
2104    }
2105
2106    #[test]
2107    fn a_recorded_finding_turns_back_into_a_judged_finding() {
2108        let original = judged();
2109        let back = RecordedFinding::from(&original).to_judged();
2110        assert_eq!(original.finding.title, back.finding.title);
2111        assert_eq!(original.finding.file, back.finding.file);
2112        assert_eq!(original.finding.severity, back.finding.severity);
2113        assert_eq!(original.raised_by, back.raised_by);
2114        assert_eq!(original.standing, back.standing);
2115        assert_eq!(original.defence, back.defence);
2116        assert_eq!(None, back.finding.problem);
2117        assert!(back.finding.blocks());
2118    }
2119
2120    #[test]
2121    fn a_ruling_tolerates_a_quoted_index_and_a_synonym_outcome() {
2122        let doc: RecheckDoc = serde_json::from_str(
2123            r#"{"summary":"holds","rulings":[{"index":"2","outcome":"Resolved","reasoning":"line 4"}],"findings":[]}"#,
2124        )
2125        .unwrap();
2126        assert_eq!(2, doc.rulings[0].index);
2127        assert_eq!(Ruling::Fixed, doc.rulings[0].outcome);
2128        let doc: RecheckDoc =
2129            serde_json::from_str(r#"{"summary":"","rulings":[],"findings":[]}"#).unwrap();
2130        assert!(doc.rulings.is_empty());
2131        assert_eq!("APPROVE", ReviewVerdict::Approve.api_event());
2132        assert_eq!("changes requested", ReviewVerdict::RequestChanges.words());
2133    }
2134}