Skip to main content

magi/
verdict.rs

1//! Structured answers extracted from free-form agent output.
2//!
3//! Agents are asked to end with a fenced `json` block. They mostly do, and
4//! sometimes they narrate afterwards, emit two blocks, or wrap the object in
5//! prose. [`extract_json`] therefore scans for *every* balanced top-level
6//! object in the text and returns the last one that deserializes into the type
7//! the caller wants, rather than trusting a single regex to find the right one.
8use std::collections::BTreeMap;
9
10use anyhow::{Result, bail};
11use serde::{Deserialize, Serialize};
12
13/// A judge's independent ranking of the candidates.
14#[derive(Debug, Clone, Serialize, Deserialize)]
15pub struct Ranking {
16    /// Labels, best first. Must be a permutation of the presented labels.
17    pub ranking: Vec<String>,
18    /// Per-label justification.
19    #[serde(default)]
20    pub reasons: BTreeMap<String, String>,
21    /// Self-reported confidence, 1-5.
22    #[serde(default)]
23    pub confidence: Option<u8>,
24    /// Per-label strengths worth porting onto the winner, written for the
25    /// candidates the judge did not rank first. Optional: a judge that
26    /// names none simply leaves the graft phase nothing to do.
27    #[serde(default, deserialize_with = "lenient_strengths")]
28    pub strengths: BTreeMap<String, Vec<String>>,
29}
30
31/// Read `strengths` without ever failing: this field is optional, so a value of
32/// the wrong shape (`null`, a string, a map of plain strings) must cost the
33/// judge nothing but the strengths. Entries that are not a string array keep
34/// their string members only; anything else is dropped.
35fn lenient_strengths<'de, D>(d: D) -> Result<BTreeMap<String, Vec<String>>, D::Error>
36where
37    D: serde::Deserializer<'de>,
38{
39    let value = serde_json::Value::deserialize(d)?;
40    let mut out = BTreeMap::new();
41    if let serde_json::Value::Object(map) = value {
42        for (label, v) in map {
43            match v {
44                serde_json::Value::Array(items) => {
45                    let list: Vec<String> = items
46                        .into_iter()
47                        .filter_map(|i| i.as_str().map(str::to_owned))
48                        .collect();
49                    if !list.is_empty() {
50                        out.insert(label, list);
51                    }
52                }
53                serde_json::Value::String(s) if !s.trim().is_empty() => {
54                    out.insert(label, vec![s]);
55                }
56                _ => {}
57            }
58        }
59    }
60    Ok(out)
61}
62
63impl Ranking {
64    /// The judge's first choice.
65    pub fn top(&self) -> Option<&str> {
66        self.ranking.first().map(String::as_str)
67    }
68
69    /// Reject a ranking that is not a permutation of `labels`, so a malformed
70    /// verdict is retried instead of silently skewing the tally.
71    pub fn validate(&self, labels: &[char]) -> Result<()> {
72        let mut got: Vec<char> = self
73            .ranking
74            .iter()
75            .filter_map(|s| s.trim().chars().next())
76            .map(|c| c.to_ascii_uppercase())
77            .collect();
78        got.sort_unstable();
79        got.dedup();
80        let mut want: Vec<char> = labels.to_vec();
81        want.sort_unstable();
82        if got != want {
83            bail!(
84                "ranking {:?} is not a permutation of the candidate labels {:?}",
85                self.ranking,
86                labels
87            );
88        }
89        Ok(())
90    }
91
92    /// Normalise labels to single uppercase characters.
93    pub fn normalized(&self) -> Vec<char> {
94        self.ranking
95            .iter()
96            .filter_map(|s| s.trim().chars().next())
97            .map(|c| c.to_ascii_uppercase())
98            .collect()
99    }
100}
101
102/// A judge's final vote, collected privately.
103#[derive(Debug, Clone, Serialize, Deserialize)]
104pub struct FinalVote {
105    /// The winning label, in this judge's view.
106    pub vote: String,
107    /// Why.
108    #[serde(default)]
109    pub reason: String,
110}
111
112impl FinalVote {
113    /// The voted label as a single uppercase char.
114    pub fn label(&self) -> Option<char> {
115        self.vote
116            .trim()
117            .chars()
118            .next()
119            .map(|c| c.to_ascii_uppercase())
120    }
121}
122
123/// How bad a review finding is.
124#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
125#[serde(rename_all = "lowercase")]
126pub enum Severity {
127    /// Cosmetic.
128    Nit,
129    /// Should fix, does not block.
130    Minor,
131    /// Should fix before merge.
132    Major,
133    /// Must fix before merge.
134    Blocker,
135}
136
137impl Severity {
138    /// Does this finding hold the merge?
139    pub fn blocks(self) -> bool {
140        matches!(self, Self::Major | Self::Blocker)
141    }
142}
143
144/// One review finding.
145#[derive(Debug, Clone, Serialize, Deserialize)]
146pub struct Finding {
147    /// Assigned by magi after parsing, e.g. `R1-1-2`. Never trusted from the
148    /// agent, because the fixer's adoption report is keyed by it.
149    #[serde(default)]
150    pub id: String,
151    /// How bad.
152    pub severity: Severity,
153    /// File it concerns.
154    #[serde(default)]
155    pub file: Option<String>,
156    /// Line it concerns.
157    #[serde(default)]
158    pub line: Option<u32>,
159    /// One-line summary.
160    pub title: String,
161    /// The argument.
162    #[serde(default)]
163    pub detail: String,
164}
165
166/// A reviewer seat's verdict on the patch, cast alongside its findings.
167///
168/// Three values, not a boolean, because "fine to proceed" and "fine, but
169/// look at these" are different signals for the operator watching the run —
170/// collapsing them would hide exactly the middle case a lens-based reviewer
171/// is most likely to land on. Ord follows declaration order (least to most
172/// cautious) so a round's [`ReviewVote::worst`] is a plain `max`, the same
173/// trick [`Severity`] uses for `blocks`.
174#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
175#[serde(rename_all = "snake_case")]
176pub enum ReviewVote {
177    /// No reservations.
178    Approve,
179    /// Fine to proceed, but the findings below are worth fixing.
180    ApproveWithFindings,
181    /// Do not proceed as-is.
182    Reject,
183}
184
185impl ReviewVote {
186    /// Operator-facing label, used in events and the report — never
187    /// `Debug`, so a rename of a variant does not silently reword history.
188    pub fn label(self) -> &'static str {
189        match self {
190            Self::Approve => "approve",
191            Self::ApproveWithFindings => "approve with findings",
192            Self::Reject => "reject",
193        }
194    }
195
196    /// The most cautious of a set of votes, or `None` if none were cast.
197    ///
198    /// A round's recorded verdict must never read softer than its most
199    /// cautious seat — the same reason a single blocking finding, not an
200    /// average of severities, decides whether a round is clean.
201    pub fn worst(votes: impl IntoIterator<Item = Self>) -> Option<Self> {
202        votes.into_iter().max()
203    }
204}
205
206/// A reviewer's report.
207#[derive(Debug, Clone, Serialize, Deserialize)]
208pub struct Review {
209    /// Findings, worst first is conventional but not required.
210    #[serde(default)]
211    pub findings: Vec<Finding>,
212    /// Reviewer's overall verdict prose.
213    #[serde(default)]
214    pub summary: String,
215    /// This seat's vote. Required, not defaulted: a reviewer that skips it
216    /// is retried the same as one that skipped `severity` on a finding,
217    /// rather than silently counted as an `approve`.
218    pub vote: ReviewVote,
219}
220
221/// A reviewer seat's revote after a split round, cast once it has read every
222/// seat's findings and votes (still numbered, never named — see
223/// [`crate::prompt::review_reconsider`]).
224#[derive(Debug, Clone, Serialize, Deserialize)]
225pub struct ReviewRevote {
226    /// The seat's revote.
227    pub vote: ReviewVote,
228    /// Why, one or two sentences.
229    #[serde(default)]
230    pub reason: String,
231}
232
233/// The fixer's response to a round of findings.
234#[derive(Debug, Clone, Serialize, Deserialize)]
235pub struct FixReport {
236    /// Finding ids that were acted on.
237    #[serde(default)]
238    pub addressed: Vec<String>,
239    /// Finding ids that were deliberately not acted on, with the reason.
240    #[serde(default)]
241    pub rejected: Vec<Rejection>,
242    /// What changed.
243    #[serde(default)]
244    pub notes: String,
245}
246
247/// A finding the fixer declined, and why.
248#[derive(Debug, Clone, Serialize, Deserialize)]
249pub struct Rejection {
250    /// Finding id.
251    pub id: String,
252    /// Argument for not acting.
253    #[serde(default)]
254    pub why: String,
255}
256
257/// A judge's position during deliberation.
258#[derive(Debug, Clone, Serialize, Deserialize)]
259pub struct Position {
260    /// Where the judge currently stands.
261    #[serde(default)]
262    pub tentative: Option<String>,
263}
264
265/// One advisor's independent design proposal, gathered by
266/// `graph::Runner::advise` before a run's implementer seats begin.
267///
268/// No patch and no plan of tool calls - a design proposal is cheap exactly
269/// because it is a few paragraphs an agent can write without touching the
270/// repository, which is what makes running several of them, on every run,
271/// affordable in a way several full implementations were not.
272#[derive(Debug, Clone, Serialize, Deserialize)]
273pub struct Proposal {
274    /// What to do and how, in the advisor's own words.
275    pub approach: String,
276    /// The one tradeoff this design turns on.
277    pub key_tradeoff: String,
278    /// What could go wrong.
279    #[serde(default)]
280    pub risks: Vec<String>,
281    /// Files or modules the design touches.
282    #[serde(default)]
283    pub touches: Vec<String>,
284    /// Why this earns its complexity over the obvious first draft - the
285    /// question that keeps a proposal from being a restatement of the task.
286    pub why_not_naive: String,
287}
288
289impl Proposal {
290    /// Reject a proposal with an empty field that matters, so a malformed or
291    /// lazy answer is retried instead of silently thinning the panel down to
292    /// prose nobody can act on.
293    pub fn validate(&self) -> Result<()> {
294        for (field, value) in [
295            ("approach", &self.approach),
296            ("key_tradeoff", &self.key_tradeoff),
297            ("why_not_naive", &self.why_not_naive),
298        ] {
299            if value.trim().is_empty() {
300                bail!("`{field}` is empty");
301            }
302        }
303        Ok(())
304    }
305}
306
307/// Extract the last balanced JSON object in `text` that parses as `T`.
308///
309/// Handles fenced blocks, trailing prose, and multiple objects. Strings and
310/// escapes are tracked so a `}` inside a string literal does not close an
311/// object early.
312pub fn extract_json<T: serde::de::DeserializeOwned>(text: &str) -> Result<T> {
313    let bytes = text.as_bytes();
314    let mut spans: Vec<(usize, usize)> = Vec::new();
315    let mut i = 0usize;
316    while i < bytes.len() {
317        if bytes[i] != b'{' {
318            i += 1;
319            continue;
320        }
321        let mut depth = 0usize;
322        let mut in_str = false;
323        let mut escaped = false;
324        let mut j = i;
325        while j < bytes.len() {
326            let c = bytes[j];
327            if in_str {
328                if escaped {
329                    escaped = false;
330                } else if c == b'\\' {
331                    escaped = true;
332                } else if c == b'"' {
333                    in_str = false;
334                }
335            } else {
336                match c {
337                    b'"' => in_str = true,
338                    b'{' => depth += 1,
339                    b'}' => {
340                        depth -= 1;
341                        if depth == 0 {
342                            spans.push((i, j + 1));
343                            break;
344                        }
345                    }
346                    _ => {}
347                }
348            }
349            j += 1;
350        }
351        // Skip past this object's opening brace either way; a truncated object
352        // must not make the scan quadratic on long transcripts.
353        i = if depth == 0 && j < bytes.len() {
354            j + 1
355        } else {
356            i + 1
357        };
358    }
359
360    let mut last_err = None;
361    for (start, end) in spans.iter().rev() {
362        match serde_json::from_str::<T>(&text[*start..*end]) {
363            Ok(v) => return Ok(v),
364            Err(e) => last_err = Some(e),
365        }
366    }
367    match last_err {
368        Some(e) => bail!("no JSON object in the reply matched the expected shape: {e}"),
369        None => bail!("the reply contained no JSON object"),
370    }
371}
372
373/// Pull the text after a `## <heading>` marker, to the end or the next heading.
374///
375/// Used for the prose sections agents are asked to emit alongside their JSON.
376pub fn section(text: &str, heading: &str) -> Option<String> {
377    let want = heading.to_ascii_lowercase();
378    let mut out: Option<String> = None;
379    for line in text.lines() {
380        let trimmed = line.trim();
381        if let Some(rest) = trimmed.strip_prefix("##") {
382            let name = rest.trim_start_matches('#').trim().to_ascii_lowercase();
383            if name == want {
384                out = Some(String::new());
385                continue;
386            }
387            if out.is_some() {
388                break;
389            }
390            continue;
391        }
392        if let Some(buf) = out.as_mut() {
393            buf.push_str(line);
394            buf.push('\n');
395        }
396    }
397    out.map(|s| s.trim().to_owned()).filter(|s| !s.is_empty())
398}
399
400/// The marker `prompt::implement`'s reply format documents for an
401/// implementer that investigated and concluded, with evidence, that no code
402/// change belongs in this worktree — see that prompt's "Reply format"
403/// section for the exact wording asked for.
404pub const NO_CHANGE_NEEDED_MARKER: &str = "NO CHANGE NEEDED:";
405
406/// Pull the evidence out of an implementer's `## SUMMARY` section when it
407/// opens with [`NO_CHANGE_NEEDED_MARKER`].
408///
409/// Returns `None` for an ordinary bullet-list summary, and also for a
410/// marker with nothing after it — an unsupported claim must read exactly
411/// like a candidate that never made one, not like a verified one with an
412/// empty reason. This only recognises the *declaration*; whether it is
413/// trusted is [`crate::graph`]'s adoption guard's call, made from evidence
414/// this function cannot see (the CLI's own exit status, whether the tree is
415/// really empty, whether a command went unconfirmed).
416pub fn verified_noop(summary: &str) -> Option<String> {
417    let evidence = summary.trim_start().strip_prefix(NO_CHANGE_NEEDED_MARKER)?;
418    let evidence = evidence.trim();
419    (!evidence.is_empty()).then(|| evidence.to_owned())
420}
421
422#[cfg(test)]
423mod tests {
424    use super::*;
425
426    #[test]
427    fn malformed_strengths_never_cost_the_ranking() {
428        for bad in [
429            "null",
430            r#"{"B":"one point"}"#,
431            r#""x""#,
432            r#"[1]"#,
433            r#"{"B":[1,"ok"]}"#,
434        ] {
435            let text = format!(r#"{{"ranking":["A","B"],"strengths":{bad}}}"#);
436            let r: Ranking = extract_json(&text).unwrap();
437            assert_eq!(r.ranking, ["A", "B"]);
438        }
439    }
440
441    #[test]
442    fn fenced_block_is_found() {
443        let text = "Here is my verdict.\n\n```json\n{\"ranking\":[\"B\",\"A\"]}\n```\n";
444        let r: Ranking = extract_json(text).unwrap();
445        assert_eq!(r.top(), Some("B"));
446    }
447
448    #[test]
449    fn last_matching_object_wins_over_an_earlier_example() {
450        let text = concat!(
451            "The format is {\"ranking\":[\"X\"]} for illustration.\n",
452            "```json\n{\"ranking\":[\"C\",\"A\",\"B\"],\"confidence\":4}\n```\n",
453            "Happy to elaborate.\n"
454        );
455        let r: Ranking = extract_json(text).unwrap();
456        assert_eq!(r.normalized(), ['C', 'A', 'B']);
457        assert_eq!(r.confidence, Some(4));
458    }
459
460    #[test]
461    fn braces_inside_strings_do_not_close_the_object() {
462        let text = r#"{"ranking":["A"],"reasons":{"A":"uses format!(\"{}\", x) safely}"}}"#;
463        let r: Ranking = extract_json(text).unwrap();
464        assert_eq!(r.top(), Some("A"));
465        assert!(r.reasons["A"].contains("format!"));
466    }
467
468    #[test]
469    fn objects_of_the_wrong_shape_are_skipped() {
470        let text = concat!(
471            "```json\n{\"ranking\":[\"A\",\"B\"]}\n```\n",
472            "and some telemetry: {\"tokens\":123}\n"
473        );
474        let r: Ranking = extract_json(text).unwrap();
475        assert_eq!(r.normalized(), ['A', 'B']);
476    }
477
478    #[test]
479    fn no_json_is_an_error_not_a_default() {
480        let err = extract_json::<Ranking>("I decline to produce JSON.").unwrap_err();
481        assert!(err.to_string().contains("no JSON object"));
482    }
483
484    #[test]
485    fn truncated_object_does_not_hang() {
486        let err = extract_json::<Ranking>("{\"ranking\": [\"A\"").unwrap_err();
487        assert!(err.to_string().contains("no JSON object"));
488    }
489
490    #[test]
491    fn ranking_validation_rejects_a_non_permutation() {
492        let r = Ranking {
493            ranking: vec!["A".to_owned(), "A".to_owned()],
494            reasons: BTreeMap::new(),
495            confidence: None,
496            strengths: BTreeMap::new(),
497        };
498        assert!(r.validate(&['A', 'B', 'C']).is_err());
499
500        let r = Ranking {
501            ranking: vec!["c".to_owned(), "B".to_owned(), "A".to_owned()],
502            reasons: BTreeMap::new(),
503            confidence: None,
504            strengths: BTreeMap::new(),
505        };
506        r.validate(&['A', 'B', 'C']).expect("case is normalised");
507        assert_eq!(r.normalized(), ['C', 'B', 'A']);
508    }
509
510    #[test]
511    fn final_vote_label_is_normalised() {
512        let v: FinalVote = extract_json(r#"{"vote":" b ","reason":"tests"}"#).unwrap();
513        assert_eq!(v.label(), Some('B'));
514    }
515
516    #[test]
517    fn severity_blocking_is_major_and_up() {
518        assert!(Severity::Blocker.blocks());
519        assert!(Severity::Major.blocks());
520        assert!(!Severity::Minor.blocks());
521        assert!(!Severity::Nit.blocks());
522        assert!(Severity::Blocker > Severity::Nit);
523    }
524
525    #[test]
526    fn review_parses_with_optional_fields_missing() {
527        let r: Review = extract_json(
528            r#"{"vote":"reject","findings":[{"severity":"blocker","title":"panics on empty input"}]}"#,
529        )
530        .unwrap();
531        assert_eq!(r.findings.len(), 1);
532        assert!(r.findings[0].file.is_none());
533        assert_eq!(r.findings[0].id, "");
534        assert_eq!(r.vote, ReviewVote::Reject);
535    }
536
537    #[test]
538    fn review_without_a_vote_is_rejected_rather_than_defaulted() {
539        let err = extract_json::<Review>(r#"{"findings":[]}"#).unwrap_err();
540        assert!(err.to_string().contains("no JSON object"), "{err}");
541    }
542
543    #[test]
544    fn review_vote_worst_is_the_most_cautious() {
545        assert_eq!(
546            ReviewVote::worst([ReviewVote::Approve, ReviewVote::Reject, ReviewVote::Approve]),
547            Some(ReviewVote::Reject)
548        );
549        assert_eq!(
550            ReviewVote::worst([ReviewVote::Approve, ReviewVote::ApproveWithFindings]),
551            Some(ReviewVote::ApproveWithFindings)
552        );
553        assert_eq!(ReviewVote::worst(Vec::<ReviewVote>::new()), None);
554    }
555
556    #[test]
557    fn review_revote_parses_the_reconsideration_shape() {
558        let r: ReviewRevote =
559            extract_json(r#"{"vote":"approve","reason":"the other findings do not hold"}"#)
560                .unwrap();
561        assert_eq!(r.vote, ReviewVote::Approve);
562        assert_eq!(r.reason, "the other findings do not hold");
563    }
564
565    #[test]
566    fn fix_report_parses_rejections() {
567        let f: FixReport = extract_json(
568            r#"{"addressed":["R1-1-1"],"rejected":[{"id":"R1-2-1","why":"not reachable"}]}"#,
569        )
570        .unwrap();
571        assert_eq!(f.addressed, ["R1-1-1"]);
572        assert_eq!(f.rejected[0].id, "R1-2-1");
573    }
574
575    #[test]
576    fn proposal_parses_with_optional_fields_missing() {
577        let p: Proposal = extract_json(
578            r#"{"approach":"do X","key_tradeoff":"simpler now, slower later","why_not_naive":"the naive version corrupts state under a retry"}"#,
579        )
580        .unwrap();
581        assert!(p.risks.is_empty());
582        assert!(p.touches.is_empty());
583        p.validate()
584            .expect("a proposal with only required fields is valid");
585    }
586
587    #[test]
588    fn proposal_validation_rejects_an_empty_required_field() {
589        let p = Proposal {
590            approach: String::new(),
591            key_tradeoff: "t".to_owned(),
592            risks: Vec::new(),
593            touches: Vec::new(),
594            why_not_naive: "w".to_owned(),
595        };
596        let err = p.validate().unwrap_err();
597        assert!(err.to_string().contains("approach"));
598    }
599
600    #[test]
601    fn sections_are_sliced_by_heading() {
602        let text = "## SUMMARY\nchanged the retry loop.\nadded a test.\n\n## NOTES\nignore me\n";
603        assert_eq!(
604            section(text, "summary").unwrap(),
605            "changed the retry loop.\nadded a test."
606        );
607        assert_eq!(section(text, "notes").unwrap(), "ignore me");
608        assert!(section(text, "missing").is_none());
609    }
610
611    #[test]
612    fn no_change_needed_marker_yields_its_evidence() {
613        let summary = "NO CHANGE NEEDED: already fixed by b32cfc4, which is on main \
614                        (git merge-base --is-ancestor confirms it).";
615        assert_eq!(
616            verified_noop(summary).unwrap(),
617            "already fixed by b32cfc4, which is on main (git merge-base --is-ancestor \
618             confirms it)."
619        );
620    }
621
622    #[test]
623    fn no_change_needed_marker_with_no_evidence_is_not_verified() {
624        assert!(verified_noop("NO CHANGE NEEDED:").is_none());
625        assert!(verified_noop("NO CHANGE NEEDED:   \n  ").is_none());
626    }
627
628    #[test]
629    fn an_ordinary_summary_is_not_verified() {
630        assert!(verified_noop("- changed the retry loop.\n- added a test.").is_none());
631        // The marker only counts leading the section, not mentioned in passing.
632        assert!(verified_noop("I considered NO CHANGE NEEDED: but wrote a fix instead.").is_none());
633    }
634}