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, BTreeSet};
9use std::fmt;
10use std::path::{Component, Path};
11
12use anyhow::{Result, bail};
13use serde::{Deserialize, Serialize};
14
15/// A judge's independent ranking of the candidates.
16#[derive(Debug, Clone, Serialize, Deserialize)]
17pub struct Ranking {
18    /// Labels, best first. Must be a permutation of the presented labels.
19    pub ranking: Vec<String>,
20    /// Per-label justification.
21    #[serde(default)]
22    pub reasons: BTreeMap<String, String>,
23    /// Self-reported confidence, 1-5.
24    #[serde(default)]
25    pub confidence: Option<u8>,
26    /// Per-label strengths worth porting onto the winner, written for the
27    /// candidates the judge did not rank first. Optional: a judge that
28    /// names none simply leaves the graft phase nothing to do.
29    #[serde(default, deserialize_with = "lenient_strengths")]
30    pub strengths: BTreeMap<String, Vec<String>>,
31}
32
33/// Read `strengths` without ever failing: this field is optional, so a value of
34/// the wrong shape (`null`, a string, a map of plain strings) must cost the
35/// judge nothing but the strengths. Entries that are not a string array keep
36/// their string members only; anything else is dropped.
37fn lenient_strengths<'de, D>(d: D) -> Result<BTreeMap<String, Vec<String>>, D::Error>
38where
39    D: serde::Deserializer<'de>,
40{
41    let value = serde_json::Value::deserialize(d)?;
42    let mut out = BTreeMap::new();
43    if let serde_json::Value::Object(map) = value {
44        for (label, v) in map {
45            match v {
46                serde_json::Value::Array(items) => {
47                    let list: Vec<String> = items
48                        .into_iter()
49                        .filter_map(|i| i.as_str().map(str::to_owned))
50                        .collect();
51                    if !list.is_empty() {
52                        out.insert(label, list);
53                    }
54                }
55                serde_json::Value::String(s) if !s.trim().is_empty() => {
56                    out.insert(label, vec![s]);
57                }
58                _ => {}
59            }
60        }
61    }
62    Ok(out)
63}
64
65impl Ranking {
66    /// The judge's first choice.
67    pub fn top(&self) -> Option<&str> {
68        self.ranking.first().map(String::as_str)
69    }
70
71    /// Reject a ranking that is not a permutation of `labels`, so a malformed
72    /// verdict is retried instead of silently skewing the tally.
73    pub fn validate(&self, labels: &[char]) -> Result<()> {
74        let mut got: Vec<char> = self
75            .ranking
76            .iter()
77            .filter_map(|s| s.trim().chars().next())
78            .map(|c| c.to_ascii_uppercase())
79            .collect();
80        got.sort_unstable();
81        got.dedup();
82        let mut want: Vec<char> = labels.to_vec();
83        want.sort_unstable();
84        if got != want {
85            bail!(
86                "ranking {:?} is not a permutation of the candidate labels {:?}",
87                self.ranking,
88                labels
89            );
90        }
91        Ok(())
92    }
93
94    /// Normalise labels to single uppercase characters.
95    pub fn normalized(&self) -> Vec<char> {
96        self.ranking
97            .iter()
98            .filter_map(|s| s.trim().chars().next())
99            .map(|c| c.to_ascii_uppercase())
100            .collect()
101    }
102}
103
104/// A judge's final vote, collected privately.
105#[derive(Debug, Clone, Serialize, Deserialize)]
106pub struct FinalVote {
107    /// The winning label, in this judge's view.
108    pub vote: String,
109    /// Why.
110    #[serde(default)]
111    pub reason: String,
112}
113
114impl FinalVote {
115    /// The voted label as a single uppercase char.
116    pub fn label(&self) -> Option<char> {
117        self.vote
118            .trim()
119            .chars()
120            .next()
121            .map(|c| c.to_ascii_uppercase())
122    }
123}
124
125/// How bad a review finding is.
126#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
127#[serde(rename_all = "lowercase")]
128pub enum Severity {
129    /// Cosmetic.
130    Nit,
131    /// Should fix, does not block.
132    Minor,
133    /// Should fix before merge.
134    Major,
135    /// Must fix before merge.
136    Blocker,
137}
138
139impl Severity {
140    /// Does this finding hold the merge?
141    pub fn blocks(self) -> bool {
142        matches!(self, Self::Major | Self::Blocker)
143    }
144}
145
146impl std::fmt::Display for Severity {
147    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
148        f.write_str(match self {
149            Self::Nit => "nit",
150            Self::Minor => "minor",
151            Self::Major => "major",
152            Self::Blocker => "blocker",
153        })
154    }
155}
156
157/// One review finding.
158#[derive(Debug, Clone, Serialize, Deserialize)]
159pub struct Finding {
160    /// Assigned by magi after parsing, e.g. `R1-1-2`. Never trusted from the
161    /// agent, because the fixer's adoption report is keyed by it.
162    #[serde(default)]
163    pub id: String,
164    /// How bad.
165    pub severity: Severity,
166    /// File it concerns.
167    #[serde(default)]
168    pub file: Option<String>,
169    /// Line it concerns.
170    #[serde(default)]
171    pub line: Option<u32>,
172    /// One-line summary.
173    pub title: String,
174    /// The argument.
175    #[serde(default)]
176    pub detail: String,
177}
178
179/// A reviewer seat's verdict on the patch, cast alongside its findings.
180///
181/// Three values, not a boolean, because "fine to proceed" and "fine, but
182/// look at these" are different signals for the operator watching the run —
183/// collapsing them would hide exactly the middle case a lens-based reviewer
184/// is most likely to land on. Ord follows declaration order (least to most
185/// cautious) so a round's [`ReviewVote::worst`] is a plain `max`, the same
186/// trick [`Severity`] uses for `blocks`.
187#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
188#[serde(rename_all = "snake_case")]
189pub enum ReviewVote {
190    /// No reservations.
191    Approve,
192    /// Fine to proceed, but the findings below are worth fixing.
193    ApproveWithFindings,
194    /// Do not proceed as-is.
195    Reject,
196}
197
198impl ReviewVote {
199    /// Operator-facing label, used in events and the report — never
200    /// `Debug`, so a rename of a variant does not silently reword history.
201    pub fn label(self) -> &'static str {
202        match self {
203            Self::Approve => "approve",
204            Self::ApproveWithFindings => "approve with findings",
205            Self::Reject => "reject",
206        }
207    }
208
209    /// The most cautious of a set of votes, or `None` if none were cast.
210    ///
211    /// A round's recorded verdict must never read softer than its most
212    /// cautious seat — the same reason a single blocking finding, not an
213    /// average of severities, decides whether a round is clean.
214    pub fn worst(votes: impl IntoIterator<Item = Self>) -> Option<Self> {
215        votes.into_iter().max()
216    }
217}
218
219/// A reviewer's report.
220#[derive(Debug, Clone, Serialize, Deserialize)]
221pub struct Review {
222    /// Findings, worst first is conventional but not required.
223    #[serde(default)]
224    pub findings: Vec<Finding>,
225    /// Reviewer's overall verdict prose.
226    #[serde(default)]
227    pub summary: String,
228    /// This seat's vote. Required, not defaulted: a reviewer that skips it
229    /// is retried the same as one that skipped `severity` on a finding,
230    /// rather than silently counted as an `approve`.
231    pub vote: ReviewVote,
232}
233
234/// A reviewer seat's revote after a split round, cast once it has read every
235/// seat's findings and votes (still numbered, never named — see
236/// [`crate::prompt::review_reconsider`]).
237#[derive(Debug, Clone, Serialize, Deserialize)]
238pub struct ReviewRevote {
239    /// The seat's revote.
240    pub vote: ReviewVote,
241    /// Why, one or two sentences.
242    #[serde(default)]
243    pub reason: String,
244}
245
246/// The fixer's response to a round of findings.
247#[derive(Debug, Clone, Serialize, Deserialize)]
248pub struct FixReport {
249    /// Finding ids that were acted on.
250    #[serde(default)]
251    pub addressed: Vec<String>,
252    /// Finding ids that were deliberately not acted on, with the reason.
253    #[serde(default)]
254    pub rejected: Vec<Rejection>,
255    /// What changed.
256    #[serde(default)]
257    pub notes: String,
258}
259
260/// A finding the fixer declined, and why.
261#[derive(Debug, Clone, Serialize, Deserialize)]
262pub struct Rejection {
263    /// Finding id.
264    pub id: String,
265    /// Argument for not acting.
266    #[serde(default)]
267    pub why: String,
268}
269
270/// A judge's position during deliberation.
271#[derive(Debug, Clone, Serialize, Deserialize)]
272pub struct Position {
273    /// Where the judge currently stands.
274    #[serde(default)]
275    pub tentative: Option<String>,
276}
277
278/// One advisor's independent design proposal, gathered by
279/// `graph::Runner::advise` before a run's implementer seats begin.
280///
281/// No patch and no plan of tool calls - a design proposal is cheap exactly
282/// because it is a few paragraphs an agent can write without touching the
283/// repository, which is what makes running several of them, on every run,
284/// affordable in a way several full implementations were not.
285#[derive(Debug, Clone, Serialize, Deserialize)]
286pub struct Proposal {
287    /// What to do and how, in the advisor's own words.
288    pub approach: String,
289    /// The one tradeoff this design turns on.
290    pub key_tradeoff: String,
291    /// What could go wrong.
292    #[serde(default)]
293    pub risks: Vec<String>,
294    /// Files or modules the design touches.
295    #[serde(default)]
296    pub touches: Vec<String>,
297    /// Why this earns its complexity over the obvious first draft - the
298    /// question that keeps a proposal from being a restatement of the task.
299    pub why_not_naive: String,
300}
301
302impl Proposal {
303    /// Reject a proposal with an empty field that matters, so a malformed or
304    /// lazy answer is retried instead of silently thinning the panel down to
305    /// prose nobody can act on.
306    pub fn validate(&self) -> Result<()> {
307        for (field, value) in [
308            ("approach", &self.approach),
309            ("key_tradeoff", &self.key_tradeoff),
310            ("why_not_naive", &self.why_not_naive),
311        ] {
312            if value.trim().is_empty() {
313                bail!("`{field}` is empty");
314            }
315        }
316        Ok(())
317    }
318}
319
320/// Extract the last balanced JSON object in `text` that parses as `T`.
321///
322/// Handles fenced blocks, trailing prose, and multiple objects. Strings and
323/// escapes are tracked so a `}` inside a string literal does not close an
324/// object early.
325pub fn extract_json<T: serde::de::DeserializeOwned>(text: &str) -> Result<T> {
326    let bytes = text.as_bytes();
327    let mut spans: Vec<(usize, usize)> = Vec::new();
328    let mut i = 0usize;
329    while i < bytes.len() {
330        if bytes[i] != b'{' {
331            i += 1;
332            continue;
333        }
334        let mut depth = 0usize;
335        let mut in_str = false;
336        let mut escaped = false;
337        let mut j = i;
338        while j < bytes.len() {
339            let c = bytes[j];
340            if in_str {
341                if escaped {
342                    escaped = false;
343                } else if c == b'\\' {
344                    escaped = true;
345                } else if c == b'"' {
346                    in_str = false;
347                }
348            } else {
349                match c {
350                    b'"' => in_str = true,
351                    b'{' => depth += 1,
352                    b'}' => {
353                        depth -= 1;
354                        if depth == 0 {
355                            spans.push((i, j + 1));
356                            break;
357                        }
358                    }
359                    _ => {}
360                }
361            }
362            j += 1;
363        }
364        // Skip past this object's opening brace either way; a truncated object
365        // must not make the scan quadratic on long transcripts.
366        i = if depth == 0 && j < bytes.len() {
367            j + 1
368        } else {
369            i + 1
370        };
371    }
372
373    let mut last_err = None;
374    for (start, end) in spans.iter().rev() {
375        match serde_json::from_str::<T>(&text[*start..*end]) {
376            Ok(v) => return Ok(v),
377            Err(e) => last_err = Some(e),
378        }
379    }
380    match last_err {
381        Some(e) => bail!("no JSON object in the reply matched the expected shape: {e}"),
382        None => bail!("the reply contained no JSON object"),
383    }
384}
385
386/// Pull the text after a `## <heading>` marker, to the end or the next heading.
387///
388/// Used for the prose sections agents are asked to emit alongside their JSON.
389pub fn section(text: &str, heading: &str) -> Option<String> {
390    let want = heading.to_ascii_lowercase();
391    let mut out: Option<String> = None;
392    for line in text.lines() {
393        let trimmed = line.trim();
394        if let Some(rest) = trimmed.strip_prefix("##") {
395            let name = rest.trim_start_matches('#').trim().to_ascii_lowercase();
396            if name == want {
397                out = Some(String::new());
398                continue;
399            }
400            if out.is_some() {
401                break;
402            }
403            continue;
404        }
405        if let Some(buf) = out.as_mut() {
406            buf.push_str(line);
407            buf.push('\n');
408        }
409    }
410    out.map(|s| s.trim().to_owned()).filter(|s| !s.is_empty())
411}
412
413/// The marker `prompt::implement`'s reply format documents for an
414/// implementer that investigated and concluded, with concrete positive
415/// evidence, that no code change belongs in this worktree — see that
416/// prompt's "Reply format" section for the structured JSON schema required
417/// after it.
418pub const NO_CHANGE_NEEDED_MARKER: &str = "NO CHANGE NEEDED:";
419
420/// Declared investigation status in a structured `NO CHANGE NEEDED:` report.
421#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
422#[serde(rename_all = "snake_case")]
423pub enum NoopStatus {
424    /// Every requirement was verified to already be satisfied with nothing left unresolved.
425    AlreadySatisfied,
426    /// Investigation did not finish or could not verify satisfaction.
427    Incomplete,
428    /// Investigation or verification failed.
429    Failed,
430}
431
432/// Concrete category of verification evidence cited by a [`NoopCheck`].
433#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
434#[serde(rename_all = "snake_case")]
435pub enum NoopEvidenceKind {
436    /// A git commit SHA present in the repository's base history.
437    Commit,
438    /// A test or test suite executed to confirm the behavior.
439    Test,
440    /// A command executed to verify repository state or behavior.
441    Command,
442    /// A repository-relative path inspected in the worktree.
443    Path,
444}
445
446impl NoopEvidenceKind {
447    /// Stable lower-case name matching the wire JSON spelling.
448    pub fn as_str(self) -> &'static str {
449        match self {
450            Self::Commit => "commit",
451            Self::Test => "test",
452            Self::Command => "command",
453            Self::Path => "path",
454        }
455    }
456}
457
458impl fmt::Display for NoopEvidenceKind {
459    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
460        f.write_str(self.as_str())
461    }
462}
463
464/// One requirement evaluated by the implementer and the passing check ids that
465/// prove it is already satisfied.
466#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
467#[serde(deny_unknown_fields)]
468pub struct NoopRequirement {
469    /// Short statement of the requirement checked.
470    pub requirement: String,
471    /// Whether this requirement is already satisfied.
472    pub satisfied: bool,
473    /// Check ids (referencing [`NoopCheck::id`]) proving satisfaction.
474    pub evidence: Vec<String>,
475}
476
477/// One concrete verification check actually carried out during investigation.
478#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
479#[serde(deny_unknown_fields)]
480pub struct NoopCheck {
481    /// Unique identifier referenced by [`NoopRequirement::evidence`].
482    pub id: String,
483    /// Evidence kind: `commit`, `test`, `command`, or `path`.
484    pub kind: NoopEvidenceKind,
485    /// What was inspected or executed (commit SHA, test name, command, or repo-relative path).
486    pub target: String,
487    /// How verification was performed.
488    pub method: String,
489    /// Concrete observed output or finding.
490    pub observed: String,
491    /// Whether this check succeeded.
492    pub passed: bool,
493}
494
495/// Structured JSON payload required immediately after [`NO_CHANGE_NEEDED_MARKER`].
496#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
497#[serde(deny_unknown_fields)]
498pub struct VerifiedNoopReport {
499    /// Overall investigation outcome (`already_satisfied`, `incomplete`, or `failed`).
500    pub status: NoopStatus,
501    /// Per-requirement satisfaction assessments referencing concrete checks.
502    pub requirements: Vec<NoopRequirement>,
503    /// Ordered list of concrete verification checks performed.
504    pub checks: Vec<NoopCheck>,
505    /// Remaining unresolved issues; must be empty for `already_satisfied`.
506    pub unresolved: Vec<String>,
507}
508
509impl VerifiedNoopReport {
510    /// Enforce all structural and semantic invariants of an evidence-backed
511    /// no-change declaration.
512    pub fn validate(&self) -> std::result::Result<(), String> {
513        match self.status {
514            NoopStatus::AlreadySatisfied => {}
515            NoopStatus::Incomplete => {
516                return Err(
517                    "status is `incomplete`; investigation did not establish that no change is needed"
518                        .to_owned(),
519                );
520            }
521            NoopStatus::Failed => {
522                return Err("status is `failed`; investigation did not succeed".to_owned());
523            }
524        }
525
526        if !self.unresolved.is_empty() {
527            let items: Vec<&str> = self
528                .unresolved
529                .iter()
530                .map(|s| s.trim())
531                .filter(|s| !s.is_empty())
532                .collect();
533            if items.is_empty() {
534                return Err(format!(
535                    "unresolved list is non-empty ({} blank entry/entries)",
536                    self.unresolved.len()
537                ));
538            }
539            return Err(format!("unresolved item(s) remain: {}", items.join("; ")));
540        }
541
542        if self.checks.is_empty() {
543            return Err("no verification checks were provided".to_owned());
544        }
545
546        let mut checks_by_id: BTreeMap<String, &NoopCheck> = BTreeMap::new();
547        for check in &self.checks {
548            let id = check.id.trim();
549            if id.is_empty() {
550                return Err("a verification check has an empty `id`".to_owned());
551            }
552            let id_key = id.to_ascii_lowercase();
553            if checks_by_id.contains_key(&id_key) {
554                return Err(format!("duplicate check id `{id}`"));
555            }
556
557            let target = check.target.trim();
558            if target.is_empty() || is_placeholder_value(target) {
559                return Err(format!(
560                    "check `{id}` has empty or placeholder `target` (`{target}`)"
561                ));
562            }
563            let method = check.method.trim();
564            if method.is_empty() || is_placeholder_value(method) || is_placeholder_prose(method) {
565                return Err(format!(
566                    "check `{id}` has empty or placeholder `method` (`{method}`)"
567                ));
568            }
569            let observed = check.observed.trim();
570            if observed.is_empty()
571                || is_placeholder_value(observed)
572                || is_placeholder_prose(observed)
573            {
574                return Err(format!(
575                    "check `{id}` has empty or placeholder `observed` (`{observed}`)"
576                ));
577            }
578
579            match check.kind {
580                NoopEvidenceKind::Commit if !is_commit_sha(target) => {
581                    return Err(format!(
582                        "check `{id}` (`commit`) target `{target}` must be a 7-40 character hex commit SHA"
583                    ));
584                }
585                NoopEvidenceKind::Path
586                    if !is_safe_repo_relative_path(strip_path_locator(target)) =>
587                {
588                    return Err(format!(
589                        "check `{id}` (`path`) target `{target}` must be a repository-relative path"
590                    ));
591                }
592                _ => {}
593            }
594
595            if check.passed {
596                if let Some(phrase) = incomplete_admission(method) {
597                    return Err(format!(
598                        "check `{id}` claims `passed: true` but `method` admits incomplete work (`{phrase}`)"
599                    ));
600                }
601                if let Some(phrase) = incomplete_admission(observed) {
602                    return Err(format!(
603                        "check `{id}` claims `passed: true` but `observed` admits incomplete work (`{phrase}`)"
604                    ));
605                }
606            }
607
608            checks_by_id.insert(id_key, check);
609        }
610
611        if let Some(last) = self.checks.last()
612            && !last.passed
613        {
614            return Err(format!(
615                "final verification check `{}` did not pass",
616                last.id.trim()
617            ));
618        }
619
620        if self.requirements.is_empty() {
621            return Err("no requirements were evaluated".to_owned());
622        }
623
624        let mut seen_reqs = BTreeSet::new();
625        for req in &self.requirements {
626            let text = req.requirement.trim();
627            if text.is_empty() || is_placeholder_value(text) {
628                return Err(format!(
629                    "requirement entry has empty or placeholder description (`{text}`)"
630                ));
631            }
632            let req_key = normalize_whitespace_lower(text);
633            if !seen_reqs.insert(req_key) {
634                return Err(format!("duplicate requirement `{text}`"));
635            }
636            if !req.satisfied {
637                return Err(format!("requirement `{text}` is not satisfied"));
638            }
639            if req.evidence.is_empty() {
640                return Err(format!("requirement `{text}` has no supporting evidence"));
641            }
642
643            let mut seen_ev = BTreeSet::new();
644            for raw_id in &req.evidence {
645                let ev_id = raw_id.trim();
646                if ev_id.is_empty() {
647                    return Err(format!(
648                        "requirement `{text}` contains an empty evidence id"
649                    ));
650                }
651                let ev_key = ev_id.to_ascii_lowercase();
652                if !seen_ev.insert(ev_key.clone()) {
653                    return Err(format!(
654                        "requirement `{text}` references duplicate check id `{ev_id}`"
655                    ));
656                }
657                let Some(check) = checks_by_id.get(&ev_key) else {
658                    return Err(format!(
659                        "requirement `{text}` references unknown check `{ev_id}`"
660                    ));
661                };
662                if !check.passed {
663                    return Err(format!(
664                        "contradictory evidence: requirement `{text}` cites failed check `{ev_id}`"
665                    ));
666                }
667            }
668        }
669
670        Ok(())
671    }
672
673    /// Unique checks referenced by [`Self::requirements`], in check order.
674    pub fn cited_checks(&self) -> Vec<&NoopCheck> {
675        let cited: BTreeSet<String> = self
676            .requirements
677            .iter()
678            .flat_map(|r| r.evidence.iter())
679            .map(|id| id.trim().to_ascii_lowercase())
680            .collect();
681        self.checks
682            .iter()
683            .filter(|c| cited.contains(&c.id.trim().to_ascii_lowercase()))
684            .collect()
685    }
686
687    /// Concise, single-line human-readable evidence summary for reports and
688    /// diagnostics.
689    pub fn summary_text(&self) -> String {
690        let checks_by_id: BTreeMap<String, &NoopCheck> = self
691            .checks
692            .iter()
693            .map(|c| (c.id.trim().to_ascii_lowercase(), c))
694            .collect();
695        let parts: Vec<String> = self
696            .requirements
697            .iter()
698            .map(|req| {
699                let ev: Vec<String> = req
700                    .evidence
701                    .iter()
702                    .filter_map(|id| checks_by_id.get(&id.trim().to_ascii_lowercase()))
703                    .map(|c| {
704                        format!(
705                            "{} {}: {}",
706                            c.kind,
707                            collapse_ws(c.target.trim()),
708                            collapse_ws(c.observed.trim())
709                        )
710                    })
711                    .collect();
712                format!(
713                    "{} [{}]",
714                    collapse_ws(req.requirement.trim()),
715                    ev.join("; ")
716                )
717            })
718            .collect();
719        format!("already satisfied: {}", parts.join(" | "))
720    }
721}
722
723/// Strip an optional trailing line/range locator (`:123`, `:123-145`, `:123:4`,
724/// `#L123`, `#L123-L145`) from a repository-relative path reference.
725pub fn strip_path_locator(target: &str) -> &str {
726    let target = target.trim();
727    if let Some((path, frag)) = target.rsplit_once("#L")
728        && !path.is_empty()
729        && is_line_range_fragment(frag)
730    {
731        return path;
732    }
733    if let Some((path, suffix)) = target.rsplit_once(':')
734        && !path.is_empty()
735        && !(path.len() == 1 && path.as_bytes()[0].is_ascii_alphabetic())
736    {
737        // Check `path:line:col` before `path:line`, since `:col` is also all digits.
738        if !suffix.is_empty()
739            && suffix.bytes().all(|b| b.is_ascii_digit())
740            && let Some((base, line)) = path.rsplit_once(':')
741            && !base.is_empty()
742            && !(base.len() == 1 && base.as_bytes()[0].is_ascii_alphabetic())
743            && !line.is_empty()
744            && line.bytes().all(|b| b.is_ascii_digit())
745        {
746            return base;
747        }
748        if is_colon_line_suffix(suffix) {
749            return path;
750        }
751    }
752    target
753}
754
755fn is_line_range_fragment(frag: &str) -> bool {
756    if let Some((a, b)) = frag.split_once('-') {
757        let b = b.strip_prefix('L').unwrap_or(b);
758        !a.is_empty()
759            && !b.is_empty()
760            && a.bytes().all(|c| c.is_ascii_digit())
761            && b.bytes().all(|c| c.is_ascii_digit())
762    } else {
763        !frag.is_empty() && frag.bytes().all(|c| c.is_ascii_digit())
764    }
765}
766
767fn is_colon_line_suffix(suffix: &str) -> bool {
768    if let Some((a, b)) = suffix.split_once('-') {
769        !a.is_empty()
770            && !b.is_empty()
771            && a.bytes().all(|c| c.is_ascii_digit())
772            && b.bytes().all(|c| c.is_ascii_digit())
773    } else {
774        !suffix.is_empty() && suffix.bytes().all(|c| c.is_ascii_digit())
775    }
776}
777
778fn is_commit_sha(s: &str) -> bool {
779    (7..=40).contains(&s.len()) && s.bytes().all(|b| b.is_ascii_hexdigit())
780}
781
782fn is_safe_repo_relative_path(s: &str) -> bool {
783    if s.is_empty() || s.contains('\0') {
784        return false;
785    }
786    if s.starts_with('/') || s.starts_with('\\') {
787        return false;
788    }
789    let bytes = s.as_bytes();
790    if bytes.len() >= 2 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':' {
791        return false;
792    }
793    let mut has_normal = false;
794    for comp in Path::new(s).components() {
795        match comp {
796            Component::Normal(_) => has_normal = true,
797            Component::CurDir => {}
798            Component::ParentDir | Component::RootDir | Component::Prefix(_) => return false,
799        }
800    }
801    has_normal
802}
803
804fn collapse_ws(s: &str) -> String {
805    s.split_whitespace().collect::<Vec<_>>().join(" ")
806}
807
808fn normalize_whitespace_lower(s: &str) -> String {
809    collapse_ws(s).to_ascii_lowercase()
810}
811
812fn is_placeholder_value(s: &str) -> bool {
813    let norm = normalize_whitespace_lower(s);
814    matches!(
815        norm.as_str(),
816        "" | "-"
817            | "--"
818            | "..."
819            | "?"
820            | "???"
821            | "n/a"
822            | "na"
823            | "none"
824            | "null"
825            | "nil"
826            | "tbd"
827            | "todo"
828            | "unknown"
829            | "pending"
830            | "unchecked"
831            | "unverified"
832            | "not run"
833            | "not checked"
834            | "not tested"
835            | "skipped"
836            | "omitted"
837            | "placeholder"
838    )
839}
840
841fn is_placeholder_prose(s: &str) -> bool {
842    let norm = normalize_whitespace_lower(s);
843    matches!(
844        norm.as_str(),
845        "ok" | "okay"
846            | "pass"
847            | "passed"
848            | "passing"
849            | "true"
850            | "yes"
851            | "done"
852            | "checked"
853            | "verified"
854            | "confirmed"
855            | "satisfied"
856            | "same"
857            | "lgtm"
858            | "looks good"
859            | "works"
860            | "good"
861    )
862}
863
864/// Auxiliary defense against passing checks whose prose explicitly admits
865/// incomplete or unverified work. Kept narrow and word-boundary-aware so
866/// legitimate reports describing resolved past failures (e.g. "previously
867/// failed; now passes with 0 failed") or symbol names (e.g.
868/// `has_unconfirmed_command`) are never rejected.
869fn incomplete_admission(s: &str) -> Option<&'static str> {
870    const PHRASES: &[&str] = &[
871        "not established",
872        "remains unresolved",
873        "still unresolved",
874        "left unresolved",
875        "not verified",
876        "not confirmed",
877        "could not verify",
878        "unable to verify",
879        "failed to verify",
880        "could not confirm",
881        "unable to confirm",
882        "failed to confirm",
883        "could not complete",
884        "unable to complete",
885        "did not complete",
886        "not completed",
887        "was not completed",
888        "were not completed",
889        "did not run",
890        "was not run",
891        "were not run",
892        "not executed",
893        "skipped verification",
894        "investigation incomplete",
895        "incomplete investigation",
896        "no verification checks",
897        "no reproduction checks",
898        "no checks were completed",
899        "no checks were run",
900        "inconclusive",
901    ];
902    let norm = normalize_whitespace_lower(s);
903    PHRASES
904        .iter()
905        .copied()
906        .find(|phrase| contains_whole_phrase(&norm, phrase))
907}
908
909fn contains_whole_phrase(haystack: &str, needle: &str) -> bool {
910    let bytes = haystack.as_bytes();
911    let is_word = |b: u8| b.is_ascii_alphanumeric() || b == b'_';
912    let mut start = 0;
913    while let Some(pos) = haystack[start..].find(needle) {
914        let abs = start + pos;
915        let end = abs + needle.len();
916        let before_ok = abs == 0 || !is_word(bytes[abs - 1]);
917        let after_ok = end == bytes.len() || !is_word(bytes[end]);
918        if before_ok && after_ok {
919            return true;
920        }
921        start = abs + 1;
922    }
923    false
924}
925
926/// Strip at most one outer Markdown code fence (` ``` ` or ` ```json `) with no
927/// trailing content after the closing fence.
928fn strip_single_json_fence(body: &str) -> std::result::Result<&str, String> {
929    let trimmed = body.trim();
930    if !trimmed.starts_with("```") {
931        return Ok(trimmed);
932    }
933    let Some((first_line, rest)) = trimmed.split_once('\n') else {
934        return Err("unterminated fenced JSON block after NO CHANGE NEEDED:".to_owned());
935    };
936    let lang = first_line.trim().trim_start_matches('`').trim();
937    if !lang.is_empty() && !lang.eq_ignore_ascii_case("json") {
938        return Err(format!(
939            "unexpected fenced block language `{lang}`; expected a JSON object"
940        ));
941    }
942    let rest_trimmed = rest.trim_end();
943    let Some(inner) = rest_trimmed.strip_suffix("```") else {
944        return Err(
945            "unterminated fenced JSON block or trailing prose after closing fence".to_owned(),
946        );
947    };
948    if !inner.is_empty() && !inner.ends_with('\n') && !inner.ends_with('\r') {
949        return Err("closing fence must sit on its own line".to_owned());
950    }
951    Ok(inner.trim())
952}
953
954/// Strictly parse and validate a `NO CHANGE NEEDED:` declaration from an
955/// implementer's `## SUMMARY` section.
956///
957/// - Returns `None` when the summary does not open with
958///   [`NO_CHANGE_NEEDED_MARKER`] (an ordinary change summary or plain prose
959///   explanation).
960/// - Returns `Some(Ok(report))` only when the payload is a single strict JSON
961///   object matching [`VerifiedNoopReport`] and passing
962///   [`VerifiedNoopReport::validate`].
963/// - Returns `Some(Err(reason))` with a concrete rejection reason when the
964///   summary opened with the marker but failed parsing or validation (legacy
965///   freeform prose, incomplete/failed status, unresolved items, missing or
966///   failed checks, placeholders, duplicate keys/ids, or contradictory claims).
967pub fn parse_verified_noop(
968    summary: &str,
969) -> Option<std::result::Result<VerifiedNoopReport, String>> {
970    let rest = summary.trim_start().strip_prefix(NO_CHANGE_NEEDED_MARKER)?;
971    let body = rest.trim();
972    if body.is_empty() {
973        return Some(Err(
974            "empty NO CHANGE NEEDED declaration with no structured JSON evidence".to_owned(),
975        ));
976    }
977    let json_text = match strip_single_json_fence(body) {
978        Ok(s) => s,
979        Err(e) => return Some(Err(e)),
980    };
981    if !json_text.starts_with('{') || !json_text.ends_with('}') {
982        return Some(Err(
983            "expected a single JSON object after NO CHANGE NEEDED:; prose-only or legacy declarations are rejected"
984                .to_owned(),
985        ));
986    }
987    let report: VerifiedNoopReport = match serde_json::from_str(json_text) {
988        Ok(r) => r,
989        Err(e) => {
990            return Some(Err(format!(
991                "invalid structured JSON after NO CHANGE NEEDED:: {e}"
992            )));
993        }
994    };
995    if let Err(reason) = report.validate() {
996        return Some(Err(reason));
997    }
998    Some(Ok(report))
999}
1000
1001/// Pull the validated evidence summary out of an implementer's `## SUMMARY`
1002/// section when it opens with [`NO_CHANGE_NEEDED_MARKER`] and passes strict
1003/// structured validation.
1004///
1005/// Returns `None` for an ordinary bullet-list summary, and also for any
1006/// malformed, legacy prose-only, incomplete, contradictory, or unsupported
1007/// declaration. Whether the declaration is trusted against repository state and
1008/// CLI command evidence is [`crate::graph`]'s adoption guard's call.
1009pub fn verified_noop(summary: &str) -> Option<String> {
1010    parse_verified_noop(summary)?
1011        .ok()
1012        .map(|report| report.summary_text())
1013}
1014
1015#[cfg(test)]
1016mod tests {
1017    use super::*;
1018
1019    #[test]
1020    fn severity_has_explicit_operator_labels() {
1021        for (severity, label) in [
1022            (Severity::Nit, "nit"),
1023            (Severity::Minor, "minor"),
1024            (Severity::Major, "major"),
1025            (Severity::Blocker, "blocker"),
1026        ] {
1027            assert_eq!(severity.to_string(), label);
1028        }
1029    }
1030
1031    #[test]
1032    fn malformed_strengths_never_cost_the_ranking() {
1033        for bad in [
1034            "null",
1035            r#"{"B":"one point"}"#,
1036            r#""x""#,
1037            r#"[1]"#,
1038            r#"{"B":[1,"ok"]}"#,
1039        ] {
1040            let text = format!(r#"{{"ranking":["A","B"],"strengths":{bad}}}"#);
1041            let r: Ranking = extract_json(&text).unwrap();
1042            assert_eq!(r.ranking, ["A", "B"]);
1043        }
1044    }
1045
1046    #[test]
1047    fn fenced_block_is_found() {
1048        let text = "Here is my verdict.\n\n```json\n{\"ranking\":[\"B\",\"A\"]}\n```\n";
1049        let r: Ranking = extract_json(text).unwrap();
1050        assert_eq!(r.top(), Some("B"));
1051    }
1052
1053    #[test]
1054    fn last_matching_object_wins_over_an_earlier_example() {
1055        let text = concat!(
1056            "The format is {\"ranking\":[\"X\"]} for illustration.\n",
1057            "```json\n{\"ranking\":[\"C\",\"A\",\"B\"],\"confidence\":4}\n```\n",
1058            "Happy to elaborate.\n"
1059        );
1060        let r: Ranking = extract_json(text).unwrap();
1061        assert_eq!(r.normalized(), ['C', 'A', 'B']);
1062        assert_eq!(r.confidence, Some(4));
1063    }
1064
1065    #[test]
1066    fn braces_inside_strings_do_not_close_the_object() {
1067        let text = r#"{"ranking":["A"],"reasons":{"A":"uses format!(\"{}\", x) safely}"}}"#;
1068        let r: Ranking = extract_json(text).unwrap();
1069        assert_eq!(r.top(), Some("A"));
1070        assert!(r.reasons["A"].contains("format!"));
1071    }
1072
1073    #[test]
1074    fn objects_of_the_wrong_shape_are_skipped() {
1075        let text = concat!(
1076            "```json\n{\"ranking\":[\"A\",\"B\"]}\n```\n",
1077            "and some telemetry: {\"tokens\":123}\n"
1078        );
1079        let r: Ranking = extract_json(text).unwrap();
1080        assert_eq!(r.normalized(), ['A', 'B']);
1081    }
1082
1083    #[test]
1084    fn no_json_is_an_error_not_a_default() {
1085        let err = extract_json::<Ranking>("I decline to produce JSON.").unwrap_err();
1086        assert!(err.to_string().contains("no JSON object"));
1087    }
1088
1089    #[test]
1090    fn truncated_object_does_not_hang() {
1091        let err = extract_json::<Ranking>("{\"ranking\": [\"A\"").unwrap_err();
1092        assert!(err.to_string().contains("no JSON object"));
1093    }
1094
1095    #[test]
1096    fn ranking_validation_rejects_a_non_permutation() {
1097        let r = Ranking {
1098            ranking: vec!["A".to_owned(), "A".to_owned()],
1099            reasons: BTreeMap::new(),
1100            confidence: None,
1101            strengths: BTreeMap::new(),
1102        };
1103        assert!(r.validate(&['A', 'B', 'C']).is_err());
1104
1105        let r = Ranking {
1106            ranking: vec!["c".to_owned(), "B".to_owned(), "A".to_owned()],
1107            reasons: BTreeMap::new(),
1108            confidence: None,
1109            strengths: BTreeMap::new(),
1110        };
1111        r.validate(&['A', 'B', 'C']).expect("case is normalised");
1112        assert_eq!(r.normalized(), ['C', 'B', 'A']);
1113    }
1114
1115    #[test]
1116    fn final_vote_label_is_normalised() {
1117        let v: FinalVote = extract_json(r#"{"vote":" b ","reason":"tests"}"#).unwrap();
1118        assert_eq!(v.label(), Some('B'));
1119    }
1120
1121    #[test]
1122    fn severity_blocking_is_major_and_up() {
1123        assert!(Severity::Blocker.blocks());
1124        assert!(Severity::Major.blocks());
1125        assert!(!Severity::Minor.blocks());
1126        assert!(!Severity::Nit.blocks());
1127        assert!(Severity::Blocker > Severity::Nit);
1128    }
1129
1130    #[test]
1131    fn review_parses_with_optional_fields_missing() {
1132        let r: Review = extract_json(
1133            r#"{"vote":"reject","findings":[{"severity":"blocker","title":"panics on empty input"}]}"#,
1134        )
1135        .unwrap();
1136        assert_eq!(r.findings.len(), 1);
1137        assert!(r.findings[0].file.is_none());
1138        assert_eq!(r.findings[0].id, "");
1139        assert_eq!(r.vote, ReviewVote::Reject);
1140    }
1141
1142    #[test]
1143    fn review_without_a_vote_is_rejected_rather_than_defaulted() {
1144        let err = extract_json::<Review>(r#"{"findings":[]}"#).unwrap_err();
1145        assert!(err.to_string().contains("no JSON object"), "{err}");
1146    }
1147
1148    #[test]
1149    fn review_vote_worst_is_the_most_cautious() {
1150        assert_eq!(
1151            ReviewVote::worst([ReviewVote::Approve, ReviewVote::Reject, ReviewVote::Approve]),
1152            Some(ReviewVote::Reject)
1153        );
1154        assert_eq!(
1155            ReviewVote::worst([ReviewVote::Approve, ReviewVote::ApproveWithFindings]),
1156            Some(ReviewVote::ApproveWithFindings)
1157        );
1158        assert_eq!(ReviewVote::worst(Vec::<ReviewVote>::new()), None);
1159    }
1160
1161    #[test]
1162    fn review_revote_parses_the_reconsideration_shape() {
1163        let r: ReviewRevote =
1164            extract_json(r#"{"vote":"approve","reason":"the other findings do not hold"}"#)
1165                .unwrap();
1166        assert_eq!(r.vote, ReviewVote::Approve);
1167        assert_eq!(r.reason, "the other findings do not hold");
1168    }
1169
1170    #[test]
1171    fn fix_report_parses_rejections() {
1172        let f: FixReport = extract_json(
1173            r#"{"addressed":["R1-1-1"],"rejected":[{"id":"R1-2-1","why":"not reachable"}]}"#,
1174        )
1175        .unwrap();
1176        assert_eq!(f.addressed, ["R1-1-1"]);
1177        assert_eq!(f.rejected[0].id, "R1-2-1");
1178    }
1179
1180    #[test]
1181    fn proposal_parses_with_optional_fields_missing() {
1182        let p: Proposal = extract_json(
1183            r#"{"approach":"do X","key_tradeoff":"simpler now, slower later","why_not_naive":"the naive version corrupts state under a retry"}"#,
1184        )
1185        .unwrap();
1186        assert!(p.risks.is_empty());
1187        assert!(p.touches.is_empty());
1188        p.validate()
1189            .expect("a proposal with only required fields is valid");
1190    }
1191
1192    #[test]
1193    fn proposal_validation_rejects_an_empty_required_field() {
1194        let p = Proposal {
1195            approach: String::new(),
1196            key_tradeoff: "t".to_owned(),
1197            risks: Vec::new(),
1198            touches: Vec::new(),
1199            why_not_naive: "w".to_owned(),
1200        };
1201        let err = p.validate().unwrap_err();
1202        assert!(err.to_string().contains("approach"));
1203    }
1204
1205    #[test]
1206    fn sections_are_sliced_by_heading() {
1207        let text = "## SUMMARY\nchanged the retry loop.\nadded a test.\n\n## NOTES\nignore me\n";
1208        assert_eq!(
1209            section(text, "summary").unwrap(),
1210            "changed the retry loop.\nadded a test."
1211        );
1212        assert_eq!(section(text, "notes").unwrap(), "ignore me");
1213        assert!(section(text, "missing").is_none());
1214    }
1215
1216    const REGRESSION_QUOTED_SUMMARY: &str = "NO CHANGE NEEDED: Not established. No source changes, commit, or reproduction checks were completed. The reported Git configuration lock contention remains unresolved.";
1217
1218    fn valid_noop_json() -> &'static str {
1219        r#"{"status":"already_satisfied","requirements":[{"requirement":"retry loop already fixed on base","satisfied":true,"evidence":["c1","c2"]}],"checks":[{"id":"c1","kind":"commit","target":"b32cfc4","method":"git merge-base --is-ancestor b32cfc4 HEAD","observed":"exit 0; b32cfc4 is on main and fixes the retry loop","passed":true},{"id":"c2","kind":"test","target":"retry_loop_recovers","method":"cargo test --lib retry_loop_recovers","observed":"test result: ok. 1 passed; 0 failed","passed":true}],"unresolved":[]}"#
1220    }
1221
1222    #[test]
1223    fn structured_no_change_needed_report_yields_validated_evidence() {
1224        let inline = format!("NO CHANGE NEEDED: {}", valid_noop_json());
1225        let report = parse_verified_noop(&inline)
1226            .expect("marker present")
1227            .expect("valid structured report");
1228        assert_eq!(report.status, NoopStatus::AlreadySatisfied);
1229        let summary = verified_noop(&inline).expect("valid report yields summary");
1230        assert!(summary.contains("b32cfc4"), "{summary}");
1231        assert!(summary.contains("retry_loop_recovers"), "{summary}");
1232
1233        let fenced = format!("NO CHANGE NEEDED:\n```json\n{}\n```\n", valid_noop_json());
1234        assert!(
1235            verified_noop(&fenced).is_some(),
1236            "single fenced json block must be accepted"
1237        );
1238    }
1239
1240    #[test]
1241    fn operational_regression_quoted_response_is_rejected() {
1242        let err = parse_verified_noop(REGRESSION_QUOTED_SUMMARY)
1243            .expect("marker present")
1244            .expect_err("incomplete prose response must be rejected");
1245        assert!(err.contains("single JSON object"), "{err}");
1246        assert!(verified_noop(REGRESSION_QUOTED_SUMMARY).is_none());
1247
1248        // Even if the exact regression text is stuffed into a valid-shaped JSON
1249        // object claiming `already_satisfied` and `passed: true`, auxiliary
1250        // contradiction detection rejects it.
1251        let stuffed = r#"NO CHANGE NEEDED: {"status":"already_satisfied","requirements":[{"requirement":"resolve git lock contention","satisfied":true,"evidence":["c1"]}],"checks":[{"id":"c1","kind":"command","target":"git config --list","method":"ran investigation","observed":"Not established. No source changes, commit, or reproduction checks were completed. The reported Git configuration lock contention remains unresolved.","passed":true}],"unresolved":[]}"#;
1252        let err = parse_verified_noop(stuffed)
1253            .expect("marker present")
1254            .expect_err("stuffed incomplete admission must be rejected");
1255        assert!(err.contains("admits incomplete work"), "{err}");
1256        assert!(verified_noop(stuffed).is_none());
1257    }
1258
1259    #[test]
1260    fn legacy_freeform_and_empty_no_change_declarations_are_rejected() {
1261        let legacy = "NO CHANGE NEEDED: already fixed by b32cfc4, which is on main \
1262                      (git merge-base --is-ancestor confirms it).";
1263        assert!(matches!(parse_verified_noop(legacy), Some(Err(_))));
1264        assert!(verified_noop(legacy).is_none());
1265        assert!(matches!(
1266            parse_verified_noop("NO CHANGE NEEDED:"),
1267            Some(Err(_))
1268        ));
1269        assert!(matches!(
1270            parse_verified_noop("NO CHANGE NEEDED:   \n  "),
1271            Some(Err(_))
1272        ));
1273    }
1274
1275    #[test]
1276    fn an_ordinary_summary_is_not_verified() {
1277        assert!(parse_verified_noop("- changed the retry loop.\n- added a test.").is_none());
1278        assert!(verified_noop("- changed the retry loop.\n- added a test.").is_none());
1279        // The marker only counts leading the section, not mentioned in passing.
1280        assert!(
1281            parse_verified_noop("I considered NO CHANGE NEEDED: but wrote a fix instead.")
1282                .is_none()
1283        );
1284    }
1285
1286    #[test]
1287    fn incomplete_failed_unresolved_or_unverified_reports_are_rejected() {
1288        let cases = [
1289            (
1290                "incomplete status",
1291                r#"NO CHANGE NEEDED: {"status":"incomplete","requirements":[{"requirement":"req","satisfied":true,"evidence":["c1"]}],"checks":[{"id":"c1","kind":"path","target":"src/graph.rs","method":"read src/graph.rs","observed":"read file contents","passed":true}],"unresolved":[]}"#,
1292                "incomplete",
1293            ),
1294            (
1295                "failed status",
1296                r#"NO CHANGE NEEDED: {"status":"failed","requirements":[{"requirement":"req","satisfied":true,"evidence":["c1"]}],"checks":[{"id":"c1","kind":"path","target":"src/graph.rs","method":"read src/graph.rs","observed":"read file contents","passed":true}],"unresolved":[]}"#,
1297                "failed",
1298            ),
1299            (
1300                "unresolved items",
1301                r#"NO CHANGE NEEDED: {"status":"already_satisfied","requirements":[{"requirement":"req","satisfied":true,"evidence":["c1"]}],"checks":[{"id":"c1","kind":"path","target":"src/graph.rs","method":"read src/graph.rs","observed":"read file contents","passed":true}],"unresolved":["Git lock contention remains unresolved"]}"#,
1302                "unresolved",
1303            ),
1304            (
1305                "empty checks",
1306                r#"NO CHANGE NEEDED: {"status":"already_satisfied","requirements":[{"requirement":"req","satisfied":true,"evidence":["c1"]}],"checks":[],"unresolved":[]}"#,
1307                "no verification checks",
1308            ),
1309            (
1310                "empty requirements",
1311                r#"NO CHANGE NEEDED: {"status":"already_satisfied","requirements":[],"checks":[{"id":"c1","kind":"path","target":"src/graph.rs","method":"read src/graph.rs","observed":"read file contents","passed":true}],"unresolved":[]}"#,
1312                "no requirements",
1313            ),
1314            (
1315                "unsatisfied requirement",
1316                r#"NO CHANGE NEEDED: {"status":"already_satisfied","requirements":[{"requirement":"req","satisfied":false,"evidence":["c1"]}],"checks":[{"id":"c1","kind":"path","target":"src/graph.rs","method":"read src/graph.rs","observed":"read file contents","passed":true}],"unresolved":[]}"#,
1317                "not satisfied",
1318            ),
1319            (
1320                "requirement citing failed check",
1321                r#"NO CHANGE NEEDED: {"status":"already_satisfied","requirements":[{"requirement":"req","satisfied":true,"evidence":["c1"]}],"checks":[{"id":"c1","kind":"test","target":"lock_test","method":"cargo test --lib lock_test","observed":"FAILED (exit 101)","passed":false},{"id":"c2","kind":"path","target":"src/graph.rs","method":"read src/graph.rs","observed":"contains lock helper","passed":true}],"unresolved":[]}"#,
1322                "contradictory evidence",
1323            ),
1324            (
1325                "final check failed",
1326                r#"NO CHANGE NEEDED: {"status":"already_satisfied","requirements":[{"requirement":"req","satisfied":true,"evidence":["c1"]}],"checks":[{"id":"c1","kind":"path","target":"src/graph.rs","method":"read src/graph.rs","observed":"contains lock helper","passed":true},{"id":"c2","kind":"test","target":"lock_test","method":"cargo test --lib lock_test","observed":"FAILED (exit 101)","passed":false}],"unresolved":[]}"#,
1327                "final verification check",
1328            ),
1329            (
1330                "unknown check reference",
1331                r#"NO CHANGE NEEDED: {"status":"already_satisfied","requirements":[{"requirement":"req","satisfied":true,"evidence":["c9"]}],"checks":[{"id":"c1","kind":"path","target":"src/graph.rs","method":"read src/graph.rs","observed":"contains lock helper","passed":true}],"unresolved":[]}"#,
1332                "unknown check",
1333            ),
1334            (
1335                "placeholder observed",
1336                r#"NO CHANGE NEEDED: {"status":"already_satisfied","requirements":[{"requirement":"req","satisfied":true,"evidence":["c1"]}],"checks":[{"id":"c1","kind":"path","target":"src/graph.rs","method":"read src/graph.rs","observed":"ok","passed":true}],"unresolved":[]}"#,
1337                "placeholder",
1338            ),
1339            (
1340                "duplicate check id",
1341                r#"NO CHANGE NEEDED: {"status":"already_satisfied","requirements":[{"requirement":"req","satisfied":true,"evidence":["c1"]}],"checks":[{"id":"c1","kind":"path","target":"src/graph.rs","method":"read src/graph.rs","observed":"found guard","passed":true},{"id":"c1","kind":"path","target":"src/run.rs","method":"read src/run.rs","observed":"found struct","passed":true}],"unresolved":[]}"#,
1342                "duplicate check id",
1343            ),
1344            (
1345                "duplicate json key",
1346                r#"NO CHANGE NEEDED: {"status":"incomplete","status":"already_satisfied","requirements":[{"requirement":"req","satisfied":true,"evidence":["c1"]}],"checks":[{"id":"c1","kind":"path","target":"src/graph.rs","method":"read src/graph.rs","observed":"found guard","passed":true}],"unresolved":[]}"#,
1347                "duplicate field",
1348            ),
1349            (
1350                "unknown json field",
1351                r#"NO CHANGE NEEDED: {"status":"already_satisfied","extra":1,"requirements":[{"requirement":"req","satisfied":true,"evidence":["c1"]}],"checks":[{"id":"c1","kind":"path","target":"src/graph.rs","method":"read src/graph.rs","observed":"found guard","passed":true}],"unresolved":[]}"#,
1352                "unknown field",
1353            ),
1354            (
1355                "trailing second json object",
1356                r#"NO CHANGE NEEDED: {"status":"already_satisfied","requirements":[{"requirement":"req","satisfied":true,"evidence":["c1"]}],"checks":[{"id":"c1","kind":"path","target":"src/graph.rs","method":"read src/graph.rs","observed":"found guard","passed":true}],"unresolved":[]} {"extra":true}"#,
1357                "trailing",
1358            ),
1359            (
1360                "non-sha commit target",
1361                r#"NO CHANGE NEEDED: {"status":"already_satisfied","requirements":[{"requirement":"req","satisfied":true,"evidence":["c1"]}],"checks":[{"id":"c1","kind":"commit","target":"HEAD","method":"git log -1 HEAD","observed":"commit exists on HEAD","passed":true}],"unresolved":[]}"#,
1362                "hex commit SHA",
1363            ),
1364            (
1365                "parent traversal path target",
1366                r#"NO CHANGE NEEDED: {"status":"already_satisfied","requirements":[{"requirement":"req","satisfied":true,"evidence":["c1"]}],"checks":[{"id":"c1","kind":"path","target":"../outside.rs","method":"read file","observed":"found text","passed":true}],"unresolved":[]}"#,
1367                "repository-relative path",
1368            ),
1369        ];
1370
1371        for (label, input, want) in cases {
1372            let err = parse_verified_noop(input)
1373                .unwrap_or_else(|| panic!("{label}: expected marker match"))
1374                .expect_err(&format!("{label}: expected rejection"));
1375            assert!(
1376                err.contains(want),
1377                "{label}: expected error containing `{want}`, got `{err}`"
1378            );
1379        }
1380    }
1381
1382    #[test]
1383    fn resolved_past_failure_and_earlier_exploratory_failure_are_accepted() {
1384        let input = r#"NO CHANGE NEEDED: {"status":"already_satisfied","requirements":[{"requirement":"previous unconfirmed command bug is fixed","satisfied":true,"evidence":["c2","c3"]}],"checks":[{"id":"c1","kind":"command","target":"git show deadbeef","method":"git show deadbeef","observed":"initial lookup failed: old commit id was from another branch","passed":false},{"id":"c2","kind":"commit","target":"b32cfc4","method":"git merge-base --is-ancestor b32cfc4 HEAD","observed":"exit 0; previously failed lock issue was fixed by b32cfc4 on main","passed":true},{"id":"c3","kind":"test","target":"has_unconfirmed_command","method":"cargo test --lib has_unconfirmed_command","observed":"test result: ok. 3 passed; 0 failed","passed":true}],"unresolved":[]}"#;
1385        let report = parse_verified_noop(input)
1386            .expect("marker present")
1387            .expect("resolved past failure + passing final check must be accepted");
1388        assert_eq!(report.cited_checks().len(), 2);
1389        assert!(verified_noop(input).is_some());
1390    }
1391
1392    #[test]
1393    fn path_locator_stripping_keeps_clean_relative_paths_and_rejects_drive_letters() {
1394        assert_eq!(strip_path_locator("src/graph.rs:123"), "src/graph.rs");
1395        assert_eq!(strip_path_locator("src/graph.rs:123-145"), "src/graph.rs");
1396        assert_eq!(strip_path_locator("src/graph.rs:123:4"), "src/graph.rs");
1397        assert_eq!(strip_path_locator("src/graph.rs#L123"), "src/graph.rs");
1398        assert_eq!(strip_path_locator("src/graph.rs#L10-L20"), "src/graph.rs");
1399        assert!(!is_safe_repo_relative_path(strip_path_locator(
1400            "C:/tmp/a.rs"
1401        )));
1402        assert!(!is_safe_repo_relative_path(strip_path_locator(
1403            "/etc/hosts"
1404        )));
1405        assert!(is_safe_repo_relative_path(strip_path_locator(
1406            "src/graph.rs:42"
1407        )));
1408    }
1409}