diff --git a/README.md b/README.md index 25b8097..eb9f906 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,15 @@ command preserves the real index and applies the usual secret preflight. It cannot be combined with pushed-commit, range or pull-request review. Read all recorded runs with `proofline history --repo owner/name --pr 7`. +`proofline diff --repo owner/name --pr 7` compares the two newest recorded runs, +matching findings by their retained fingerprint. It prints New, Resolved, +Persisting, and Uncorrelated findings, plus a Not comparable section, and +`--json` emits the same comparison as data: the repository, pull request, both +run numbers and statuses, and the four lists. A run that is still `PENDING` or +`RUNNING` refuses the diff, because its empty assessments are not a result. If +either run is `INCOMPLETE`, `FAILED` or `STOPPED`, or one side lacks a CODE +assessment, the affected lane is reported as not comparable rather than as +resolved, and the command exits 2. `proofline rerun REVIEW_ID` requests the original immutable subject and waits; `--no-wait` returns its link. Reruns require `reviews:rerun`. `proofline guidance --repo owner/name` requires `guidance:read`. diff --git a/src/api.rs b/src/api.rs index f908670..8dbe787 100644 --- a/src/api.rs +++ b/src/api.rs @@ -424,6 +424,41 @@ impl Api { .await } + /// One page of a pull request's runs, newest first. + pub(crate) async fn pull_request_history( + &self, + repository: &str, + number: u64, + cursor: Option<&str>, + ) -> Result { + let mut url = self.url(&["reviews", "pr", repository, &number.to_string()]); + if let Some(cursor) = cursor { + url.query_pairs_mut().append_pair("cursor", cursor); + } + let raw = self.get(url).await?; + serde_json::from_value(raw).map_err(|error| self.http.protocol(error.to_string())) + } + + /// One recorded run of a pull request, by its run number. + pub(crate) async fn pull_request_run( + &self, + repository: &str, + number: u64, + run: u64, + ) -> Result { + let raw = self + .get(self.url(&[ + "reviews", + "pr", + repository, + &number.to_string(), + "runs", + &run.to_string(), + ])) + .await?; + serde_json::from_value(raw).map_err(|error| self.http.protocol(error.to_string())) + } + pub(crate) async fn guidance(&self, repository: Uuid) -> Result { self.get(self.url(&["repositories", &repository.to_string(), "review-guidance"])) .await diff --git a/src/lib.rs b/src/lib.rs index 6096711..f58a22a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -109,6 +109,8 @@ enum Command { Rerun(tools::RerunArgs), /// List the recorded runs of a pull request. History(tools::HistoryArgs), + /// Compare the findings of a pull request's two newest runs. + Diff(tools::DiffArgs), /// Read the repository review guidance as JSON. Guidance(RepositoryArgs), /// Read a bounded, untrusted finding fix prompt as JSON. @@ -485,6 +487,10 @@ pub async fn run(cli: Cli, token: Option) -> anyhow::Result { + let api = connect(Http::new(origin)?, token, cli.org).await?; + tools::diff(&api, &args).await + } Command::Guidance(args) => { let api = connect(Http::new(origin)?, token, cli.org).await?; let (_, repository) = connected_repository(&api, &args).await?; diff --git a/src/tools.rs b/src/tools.rs index 962f633..65046ff 100644 --- a/src/tools.rs +++ b/src/tools.rs @@ -1,11 +1,17 @@ //! Native operations on the existing token API. +use std::collections::HashMap; use std::io::{IsTerminal as _, Write as _}; use anyhow::{Context as _, bail}; use clap::{Args, Subcommand, ValueEnum}; +use url::Url; use uuid::Uuid; -use crate::{OutputArgs, OutputFormat, RepositoryArgs, Verdict, api::Api, say, show}; +use crate::model::{Finding, ReviewDetail}; +use crate::outcome::{self, Outcome}; +use crate::severity::Severity; +use crate::text::one_line; +use crate::{OutputArgs, OutputFormat, RepositoryArgs, Verdict, api::Api, render, say, show}; #[derive(Debug, Args)] pub(crate) struct RerunArgs { @@ -25,6 +31,565 @@ pub(crate) struct HistoryArgs { pub repository: RepositoryArgs, } +#[derive(Debug, Args)] +pub(crate) struct DiffArgs { + #[arg(long)] + pub pr: u64, + #[command(flatten)] + pub repository: RepositoryArgs, + #[command(flatten)] + pub output: DiffOutput, +} + +#[derive(Debug, Args)] +pub(crate) struct DiffOutput { + /// Print JSON instead of text. + #[arg(long)] + pub json: bool, +} + +#[derive(Debug, Clone, Copy)] +enum Lane { + Environment, + Code, +} + +impl Lane { + const fn name(self) -> &'static str { + match self { + Self::Environment => "environment", + Self::Code => "CODE", + } + } +} + +#[derive(Debug)] +struct LaneFindings<'a> { + previous: Vec<&'a Finding>, + current: Vec<&'a Finding>, +} + +#[derive(Debug)] +struct LaneState<'a> { + lane: Lane, + findings: LaneFindings<'a>, + reasons: Vec, +} + +#[derive(Debug)] +struct Uncomparable<'a> { + lane: Lane, + reasons: Vec, + findings: Vec<(u64, &'a Finding)>, +} + +#[derive(Debug, Default)] +struct Classification<'a> { + new: Vec<&'a Finding>, + resolved: Vec<&'a Finding>, + persisting: Vec<(&'a Finding, &'a Finding)>, + uncorrelated: Vec<(u64, &'a Finding)>, +} + +#[derive(Debug)] +struct FindingsDiff<'a> { + previous_run: u64, + current_run: u64, + previous_status: Outcome, + current_status: Outcome, + new: Vec<&'a Finding>, + resolved: Vec<&'a Finding>, + persisting: Vec<(&'a Finding, &'a Finding)>, + uncorrelated: Vec<(u64, &'a Finding)>, + uncomparable: Vec>, +} + +fn environment_findings(review: &ReviewDetail) -> Vec<&Finding> { + review + .assessments + .iter() + .flat_map(|assessment| assessment.findings.iter()) + .collect() +} + +fn code_findings(review: &ReviewDetail) -> Vec<&Finding> { + outcome::code_assessment(review) + .map(|code| code.findings.iter().collect()) + .unwrap_or_default() +} + +fn split_fingerprints(findings: Vec<&Finding>) -> (HashMap<&str, &Finding>, Vec<&Finding>) { + let mut fingerprinted = HashMap::new(); + let mut uncorrelated = Vec::new(); + for finding in findings { + match finding.finding_fingerprint.as_deref() { + Some(fingerprint) => { + fingerprinted.entry(fingerprint).or_insert(finding); + } + None => uncorrelated.push(finding), + } + } + (fingerprinted, uncorrelated) +} + +fn compare_findings(a: &Finding, b: &Finding) -> std::cmp::Ordering { + Severity::parse(&b.severity) + .cmp(&Severity::parse(&a.severity)) + .then_with(|| a.claim.cmp(&b.claim)) + .then_with(|| a.id.cmp(&b.id)) +} + +fn sort_by_severity(findings: &mut [&Finding]) { + findings.sort_by(|a, b| compare_findings(a, b)); +} + +fn sort_tagged(findings: &mut [(u64, &Finding)]) { + findings + .sort_by(|(a_run, a), (b_run, b)| a_run.cmp(b_run).then_with(|| compare_findings(a, b))); +} + +fn classify_lane<'a>( + findings: LaneFindings<'a>, + previous_run: u64, + current_run: u64, +) -> Classification<'a> { + let (previous_by_fingerprint, previous_uncorrelated) = split_fingerprints(findings.previous); + let (current_by_fingerprint, current_uncorrelated) = split_fingerprints(findings.current); + + let mut new = Vec::new(); + let mut persisting = Vec::new(); + for (fingerprint, finding) in ¤t_by_fingerprint { + match previous_by_fingerprint.get(*fingerprint) { + Some(before) => persisting.push((*before, *finding)), + None => new.push(*finding), + } + } + + let mut resolved = Vec::new(); + for (fingerprint, finding) in &previous_by_fingerprint { + if !current_by_fingerprint.contains_key(*fingerprint) { + resolved.push(*finding); + } + } + + let mut uncorrelated: Vec<(u64, &Finding)> = previous_uncorrelated + .into_iter() + .map(|finding| (previous_run, finding)) + .chain( + current_uncorrelated + .into_iter() + .map(|finding| (current_run, finding)), + ) + .collect(); + + sort_by_severity(&mut new); + sort_by_severity(&mut resolved); + persisting.sort_by(|(_, a), (_, b)| compare_findings(a, b)); + sort_tagged(&mut uncorrelated); + + Classification { + new, + resolved, + persisting, + uncorrelated, + } +} + +fn environment_lane<'a>( + previous_run: u64, + previous: &'a ReviewDetail, + current_run: u64, + current: &'a ReviewDetail, +) -> Option> { + let previous_present = previous.assessment_count > 0 || !previous.assessments.is_empty(); + let current_present = current.assessment_count > 0 || !current.assessments.is_empty(); + if !previous_present && !current_present { + return None; + } + let mut reasons = Vec::new(); + if previous_present != current_present { + let missing = if previous_present { + current_run + } else { + previous_run + }; + reasons.push(format!("run {missing} has no environment assessment")); + } + if previous_present { + environment_reasons(previous_run, previous, &mut reasons); + } + if current_present { + environment_reasons(current_run, current, &mut reasons); + } + Some(LaneState { + lane: Lane::Environment, + findings: LaneFindings { + previous: environment_findings(previous), + current: environment_findings(current), + }, + reasons, + }) +} + +fn environment_reasons(run: u64, review: &ReviewDetail, reasons: &mut Vec) { + match review.status.as_str() { + "COMPLETED" | "INCOMPLETE" => {} + status => reasons.push(format!("run {run} is {}", one_line(status))), + } + if usize::try_from(review.assessment_count).ok() != Some(review.assessments.len()) { + reasons.push(format!( + "run {run} has not recorded every environment assessment" + )); + } + for assessment in &review.assessments { + if let Some(gaps) = outcome::gap(assessment) { + reasons.push(format!( + "run {run} environment {} is incomplete: {}", + one_line(&assessment.environment_display_name), + one_line(&gaps.join(", ")) + )); + } + } +} + +fn code_lane<'a>( + previous_run: u64, + previous: &'a ReviewDetail, + current_run: u64, + current: &'a ReviewDetail, +) -> Option> { + let previous_present = previous.code_assessment.is_some(); + let current_present = current.code_assessment.is_some(); + if !previous_present && !current_present { + return None; + } + let mut reasons = Vec::new(); + if previous_present != current_present { + let missing = if previous_present { + current_run + } else { + previous_run + }; + reasons.push(format!("run {missing} has no CODE assessment")); + } + if previous_present { + code_reasons(previous_run, previous, &mut reasons); + } + if current_present { + code_reasons(current_run, current, &mut reasons); + } + Some(LaneState { + lane: Lane::Code, + findings: LaneFindings { + previous: code_findings(previous), + current: code_findings(current), + }, + reasons, + }) +} + +fn code_reasons(run: u64, review: &ReviewDetail, reasons: &mut Vec) { + match review.status.as_str() { + "COMPLETED" | "INCOMPLETE" => {} + status => reasons.push(format!("run {run} is {}", one_line(status))), + } + if matches!(review.status.as_str(), "FAILED" | "STOPPED") { + return; + } + match outcome::code_assessment(review) { + None => reasons.push(format!("run {run} CODE result is unavailable")), + Some(code) => { + if let Some(gap) = outcome::code_gap(code) { + reasons.push(format!("run {run} CODE is incomplete: {}", one_line(gap))); + } + } + } +} + +fn compare<'a>( + previous_run: u64, + previous: &'a ReviewDetail, + previous_status: Outcome, + current_run: u64, + current: &'a ReviewDetail, + current_status: Outcome, +) -> FindingsDiff<'a> { + let mut diff = FindingsDiff { + previous_run, + current_run, + previous_status, + current_status, + new: Vec::new(), + resolved: Vec::new(), + persisting: Vec::new(), + uncorrelated: Vec::new(), + uncomparable: Vec::new(), + }; + + for lane in [ + environment_lane(previous_run, previous, current_run, current), + code_lane(previous_run, previous, current_run, current), + ] + .into_iter() + .flatten() + { + if lane.reasons.is_empty() { + let classified = classify_lane(lane.findings, previous_run, current_run); + diff.new.extend(classified.new); + diff.resolved.extend(classified.resolved); + diff.persisting.extend(classified.persisting); + diff.uncorrelated.extend(classified.uncorrelated); + } else { + let mut findings: Vec<(u64, &Finding)> = lane + .findings + .previous + .into_iter() + .map(|finding| (previous_run, finding)) + .chain( + lane.findings + .current + .into_iter() + .map(|finding| (current_run, finding)), + ) + .collect(); + sort_tagged(&mut findings); + diff.uncomparable.push(Uncomparable { + lane: lane.lane, + reasons: lane.reasons, + findings, + }); + } + } + + sort_by_severity(&mut diff.new); + sort_by_severity(&mut diff.resolved); + diff.persisting + .sort_by(|(_, a), (_, b)| compare_findings(a, b)); + sort_tagged(&mut diff.uncorrelated); + diff +} + +fn write_finding(out: &mut Vec, run: Option, finding: &Finding) { + let tag = run.map_or_else(String::new, |run| format!("run {run} ")); + out.push(format!( + " {tag}{:<8} {} {}", + one_line(&finding.severity), + one_line(&finding.risk_domain), + one_line(&finding.claim) + )); + for place in render::location(finding) { + out.push(format!(" at {place}")); + } +} + +fn text( + name: &str, + number: u64, + diff: &FindingsDiff<'_>, + previous_url: &Url, + current_url: &Url, +) -> String { + let mut out = vec![ + format!( + "{} #{number}: run {} (previous, {}) vs run {} (latest, {})", + one_line(name), + diff.previous_run, + diff.previous_status.as_str(), + diff.current_run, + diff.current_status.as_str() + ), + format!(" run {}: {previous_url}", diff.previous_run), + format!(" run {}: {current_url}", diff.current_run), + ]; + + if !diff.uncomparable.is_empty() { + out.push(String::new()); + out.push("Not comparable:".to_owned()); + for lane in &diff.uncomparable { + out.push(format!(" {}:", lane.lane.name())); + for reason in &lane.reasons { + out.push(format!(" {reason}")); + } + for (run, finding) in &lane.findings { + write_finding(&mut out, Some(*run), finding); + } + } + } + + out.push(String::new()); + out.push(format!("New ({}):", diff.new.len())); + for finding in &diff.new { + write_finding(&mut out, None, finding); + } + + out.push(String::new()); + out.push(format!("Resolved ({}):", diff.resolved.len())); + for finding in &diff.resolved { + write_finding(&mut out, None, finding); + } + + out.push(String::new()); + out.push(format!("Persisting ({}):", diff.persisting.len())); + for (before, after) in &diff.persisting { + write_finding(&mut out, None, after); + if before.severity != after.severity { + out.push(format!(" was {}", one_line(&before.severity))); + } + } + + out.push(String::new()); + out.push(format!("Uncorrelated ({}):", diff.uncorrelated.len())); + for (run, finding) in &diff.uncorrelated { + write_finding(&mut out, Some(*run), finding); + } + + out.push(String::new()); + out.join("\n") +} + +fn diff_json(name: &str, number: u64, diff: &FindingsDiff<'_>) -> serde_json::Value { + let new: Vec<_> = diff + .new + .iter() + .map(|finding| serde_json::json!(finding)) + .collect(); + let resolved: Vec<_> = diff + .resolved + .iter() + .map(|finding| serde_json::json!(finding)) + .collect(); + let persisting: Vec<_> = diff + .persisting + .iter() + .map(|(before, after)| serde_json::json!({"before": before, "after": after})) + .collect(); + let uncorrelated: Vec<_> = diff + .uncorrelated + .iter() + .map(|(run, finding)| serde_json::json!({"run": run, "finding": finding})) + .collect(); + let not_comparable: Vec<_> = diff + .uncomparable + .iter() + .map(|lane| { + let findings: Vec<_> = lane + .findings + .iter() + .map(|(run, finding)| serde_json::json!({"run": run, "finding": finding})) + .collect(); + serde_json::json!({ + "lane": lane.lane.name(), + "reasons": lane.reasons, + "findings": findings, + }) + }) + .collect(); + + serde_json::json!({ + "repository": name, + "pull_request": number, + "from": diff.previous_run, + "to": diff.current_run, + "from_status": diff.previous_status.as_str(), + "to_status": diff.current_status.as_str(), + "new": new, + "resolved": resolved, + "persisting": persisting, + "uncorrelated": uncorrelated, + "not_comparable": not_comparable, + }) +} + +pub(crate) async fn diff(api: &Api, args: &DiffArgs) -> anyhow::Result { + let name = crate::repository_name(&args.repository).await?; + let mut runs = Vec::new(); + let mut cursor: Option = None; + for _ in 0..crate::SEARCH_PAGES { + let page = api + .pull_request_history(&name, args.pr, cursor.as_deref()) + .await?; + runs.extend( + page.items + .iter() + .filter_map(|item| item.run_number) + .filter_map(|run| u64::try_from(run).ok()), + ); + runs.sort_unstable(); + runs.dedup(); + if !page.truncated { + break; + } + match page.next_cursor { + Some(next) if cursor.as_deref() != Some(&next) => cursor = Some(next), + _ => break, + } + } + let Some((¤t_run, earlier)) = runs.split_last() else { + bail!( + "{} #{} has no recorded runs to compare", + one_line(&name), + args.pr + ); + }; + let Some(&previous_run) = earlier.last() else { + bail!( + "{} #{} has only run {current_run}; a diff needs two runs", + one_line(&name), + args.pr + ); + }; + let previous = api.pull_request_run(&name, args.pr, previous_run).await?; + let current = api.pull_request_run(&name, args.pr, current_run).await?; + let Some(previous_status) = outcome::terminal(&previous) else { + bail!( + "{} #{} run {previous_run} has not finished", + one_line(&name), + args.pr + ); + }; + let Some(current_status) = outcome::terminal(¤t) else { + bail!( + "{} #{} run {current_run} has not finished", + one_line(&name), + args.pr + ); + }; + let diff = compare( + previous_run, + &previous, + previous_status, + current_run, + ¤t, + current_status, + ); + + let mut stdout = std::io::stdout().lock(); + if args.output.json { + writeln!( + stdout, + "{}", + serde_json::to_string_pretty(&diff_json(&name, args.pr, &diff))? + )?; + } else { + let previous_url = api.review_url(previous.id); + let current_url = api.review_url(current.id); + writeln!( + stdout, + "{}", + text(&name, args.pr, &diff, &previous_url, ¤t_url) + )?; + } + + if previous_status == Outcome::Completed + && current_status == Outcome::Completed + && diff.uncomparable.is_empty() + { + Ok(Verdict::Done) + } else { + Ok(Verdict::NotComplete) + } +} + #[derive(Debug, Clone, Copy, ValueEnum)] enum Dataset { Reviews, @@ -213,3 +778,248 @@ pub(crate) async fn session(api: &Api, command: SessionCommand) -> anyhow::Resul }; json(&value) } + +#[cfg(test)] +mod tests { + use super::*; + use crate::model::{ + Assessment, Checks, CodeAssessment, CodeAssessmentRead, CodeAssessmentStatus, + }; + + fn review_with(status: &str, assessment_status: &str, findings: Vec) -> ReviewDetail { + ReviewDetail { + id: Uuid::nil(), + kind: "PULL_REQUEST".to_owned(), + status: status.to_owned(), + assessment_count: 1, + assessments: vec![Assessment { + id: Uuid::nil(), + environment_display_name: "production".to_owned(), + status: assessment_status.to_owned(), + findings, + checks: Checks { + receipt_recorded: true, + status: "READY".to_owned(), + families: Vec::new(), + }, + incompleteness_kind: (assessment_status != "COMPLETED") + .then(|| "WORLD_UNAVAILABLE".to_owned()), + reason_codes: None, + release_evidence_gap: None, + }], + code_assessment: None, + base_commit_sha: None, + head_commit_sha: Some("0123456789abcdef0123456789abcdef01234567".to_owned()), + open_items: None, + pull_request_number: Some(42), + repository_full_name: Some("acme/app".to_owned()), + run_number: Some(1), + subjects: Vec::new(), + local_reverifications: Vec::new(), + } + } + + fn review(findings: Vec) -> ReviewDetail { + review_with("COMPLETED", "COMPLETED", findings) + } + + fn code_review(finding: Finding) -> ReviewDetail { + let mut review = review_with("COMPLETED", "COMPLETED", Vec::new()); + let base = "0123456789abcdef0123456789abcdef01234567".to_owned(); + let head = "89abcdef0123456789abcdef0123456789abcdef".to_owned(); + review.assessment_count = 0; + review.assessments = Vec::new(); + review.base_commit_sha = Some(base.clone()); + review.head_commit_sha = Some(head.clone()); + review.code_assessment = Some(CodeAssessmentRead::Recorded(CodeAssessment { + id: Uuid::nil(), + status: CodeAssessmentStatus::Completed, + base_commit_sha: base, + head_commit_sha: head, + findings: vec![finding], + incompleteness_kind: None, + })); + review + } + + fn finding(severity: &str, fingerprint: Option<&str>, claim: &str) -> Finding { + Finding { + id: Uuid::nil(), + finding_fingerprint: fingerprint.map(str::to_owned), + severity: severity.to_owned(), + risk_domain: "data_integrity".to_owned(), + claim: claim.to_owned(), + impact: "orders are lost".to_owned(), + lifecycle_state: "ACTIVE".to_owned(), + remediation: None, + evidence_refs: Vec::new(), + } + } + + fn url(run: u64) -> Url { + Url::parse(&format!( + "https://proofline.sh/orgs/by-id/o/reviews/run-{run}" + )) + .unwrap() + } + + #[test] + fn fingerprints_sort_findings_into_new_resolved_persisting_and_uncorrelated() { + let previous = review(vec![ + finding("WARNING", Some("keep"), "still there"), + finding("SERIOUS", Some("fixed"), "was fixed"), + finding("WARNING", None, "previous unknown"), + ]); + let current = review(vec![ + finding("SERIOUS", Some("keep"), "still there"), + finding("WARNING", Some("new"), "brand new"), + finding("NOTE", None, "current unknown"), + ]); + + let diff = compare( + 2, + &previous, + Outcome::Completed, + 3, + ¤t, + Outcome::Completed, + ); + + assert_eq!( + diff.new + .iter() + .map(|f| f.claim.as_str()) + .collect::>(), + ["brand new"] + ); + assert_eq!( + diff.resolved + .iter() + .map(|f| f.claim.as_str()) + .collect::>(), + ["was fixed"] + ); + assert_eq!(diff.persisting.len(), 1); + assert_eq!(diff.persisting[0].0.severity, "WARNING"); + assert_eq!(diff.persisting[0].1.severity, "SERIOUS"); + assert_eq!( + diff.uncorrelated + .iter() + .map(|(run, f)| (*run, f.claim.as_str())) + .collect::>(), + [(2, "previous unknown"), (3, "current unknown")] + ); + } + + #[test] + fn an_incomplete_environment_is_not_compared() { + let previous = review(vec![finding("SERIOUS", Some("keep"), "still there")]); + let current = review_with("INCOMPLETE", "INCOMPLETE", Vec::new()); + + let diff = compare( + 2, + &previous, + Outcome::Completed, + 3, + ¤t, + Outcome::Incomplete, + ); + + assert!(diff.resolved.is_empty()); + assert_eq!(diff.uncomparable.len(), 1); + assert!(matches!(diff.uncomparable[0].lane, Lane::Environment)); + assert_eq!( + diff.uncomparable[0] + .findings + .iter() + .map(|(run, finding)| (*run, finding.claim.as_str())) + .collect::>(), + [(2, "still there")] + ); + } + + #[test] + fn a_missing_code_lane_is_not_compared() { + let previous = code_review(finding("SERIOUS", Some("code"), "code issue")); + let current = review(Vec::new()); + + let diff = compare( + 2, + &previous, + Outcome::Completed, + 3, + ¤t, + Outcome::Completed, + ); + + assert!(diff.new.is_empty()); + assert!(diff.resolved.is_empty()); + let code = diff + .uncomparable + .iter() + .find(|lane| matches!(lane.lane, Lane::Code)) + .expect("the CODE lane is not comparable"); + assert!( + code.reasons + .iter() + .any(|reason| reason.contains("has no CODE assessment")) + ); + } + + #[test] + fn a_missing_environment_lane_is_not_compared() { + let previous = review(vec![finding("SERIOUS", Some("env"), "env issue")]); + let mut current = review(Vec::new()); + current.assessment_count = 0; + current.assessments = Vec::new(); + + let diff = compare( + 2, + &previous, + Outcome::Completed, + 3, + ¤t, + Outcome::Completed, + ); + + assert!(diff.resolved.is_empty()); + assert_eq!(diff.uncomparable.len(), 1); + assert!(matches!(diff.uncomparable[0].lane, Lane::Environment)); + assert!( + diff.uncomparable[0] + .reasons + .iter() + .any(|reason| reason.contains("has no environment assessment")) + ); + } + + #[test] + fn text_prints_all_four_labels_and_a_changed_severity() { + let previous = review(vec![finding("WARNING", Some("keep"), "still there")]); + let current = review(vec![ + finding("SERIOUS", Some("keep"), "still there"), + finding("WARNING", None, "cannot correlate"), + ]); + + let diff = compare( + 2, + &previous, + Outcome::Completed, + 3, + ¤t, + Outcome::Completed, + ); + let output = text("acme/app", 42, &diff, &url(2), &url(3)); + + for label in [ + "New (0):", + "Resolved (0):", + "Persisting (1):", + "Uncorrelated (1):", + ] { + assert!(output.contains(label), "{output}"); + } + assert!(output.contains("was WARNING"), "{output}"); + assert!(output.contains("run 3"), "{output}"); + } +} diff --git a/src/update.rs b/src/update.rs index 76273ab..4e22853 100644 --- a/src/update.rs +++ b/src/update.rs @@ -122,6 +122,7 @@ fn suggestion(cache: &Cache, args: &[std::ffi::OsString], interactive: bool) -> | "setup" ) ) || arg == "history" + || arg == "diff" || arg == "guidance" || arg == "fix-prompt" || arg == "export" diff --git a/tests/http.rs b/tests/http.rs index b65ed37..9f46ed3 100644 --- a/tests/http.rs +++ b/tests/http.rs @@ -2188,3 +2188,343 @@ async fn fix_commands_preserve_context_and_never_retry_verification() { assert_eq!(calls.lock().unwrap().len(), 4); server.abort(); } + +fn diff_summary(run: i64) -> Value { + json!({ + "id": Uuid::from_u128(run as u128), + "kind": "PULL_REQUEST", + "status": "COMPLETED", + "created_at": "2026-11-01T00:00:00Z", + "head_commit_sha": null, + "pull_request_number": 7, + "repository_id": REPOSITORY, + "run_number": run, + }) +} + +fn diff_finding(fingerprint: Option<&str>, severity: &str, claim: &str) -> Value { + json!({ + "id": Uuid::nil(), + "finding_fingerprint": fingerprint, + "severity": severity, + "risk_domain": "data_integrity", + "claim": claim, + "impact": "orders are lost", + "lifecycle_state": "ACTIVE", + "remediation": null, + "evidence_refs": [], + }) +} + +fn diff_detail(run: i64, status: &str, findings: Vec) -> Value { + json!({ + "id": Uuid::from_u128(100 + run as u128), + "kind": "PULL_REQUEST", + "status": status, + "assessment_count": 1, + "assessments": [{ + "id": Uuid::from_u128(200 + run as u128), + "environment_display_name": "production", + "status": status, + "findings": findings, + "checks": { "receipt_recorded": true, "status": "READY", "families": [] }, + "incompleteness_kind": null, + "reason_codes": null, + "release_evidence_gap": null, + }], + "code_assessment": null, + "base_commit_sha": null, + "head_commit_sha": null, + "open_items": null, + "pull_request_number": 7, + "repository_full_name": "acme/web", + "run_number": run, + }) +} + +async fn serve_diff( + runs: Vec, + details: Vec<(u64, Value)>, +) -> (String, tokio::task::JoinHandle<()>) { + let details: Arc> = + Arc::new(details.into_iter().collect()); + let summaries: Vec = runs.iter().map(|run| diff_summary(*run)).collect(); + let app = Router::new() + .route( + &format!("/api/v1/organizations/{ORG}/reviews/pr/{{repository}}/{{number}}"), + get(move |Path((repository, number)): Path<(String, u64)>| { + let summaries = summaries.clone(); + async move { + assert_eq!(repository, "acme/web"); + assert_eq!(number, 7); + Json(json!({ + "items": summaries, + "next_cursor": null, + "truncated": false, + "filters": { "repositories": [{ "id": REPOSITORY, "name": "acme/web" }] }, + })) + } + }), + ) + .route( + &format!( + "/api/v1/organizations/{ORG}/reviews/pr/{{repository}}/{{number}}/runs/{{run}}" + ), + get( + move |Path((_repository, _number, run)): Path<(String, u64, u64)>| { + let details = Arc::clone(&details); + async move { + details.get(&run).map_or_else( + || { + ( + StatusCode::NOT_FOUND, + Json(json!({ + "title": "not found", + "status": 404, + "detail": "no such run", + })), + ) + .into_response() + }, + |detail| Json(detail.clone()).into_response(), + ) + } + }, + ), + ); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let origin = format!("http://{}", listener.local_addr().unwrap()); + let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + (origin, server) +} + +async fn diff_cli(origin: &str, extra: &[&str]) -> std::process::Output { + let mut args = vec!["diff", "--repo", "acme/web", "--pr", "7"]; + args.extend_from_slice(extra); + cli(origin, &args).await +} + +#[tokio::test] +async fn diff_refuses_a_run_that_has_not_finished() { + let (origin, server) = serve_diff( + vec![2, 3], + vec![ + (2, diff_detail(2, "COMPLETED", Vec::new())), + (3, diff_detail(3, "RUNNING", Vec::new())), + ], + ) + .await; + + let output = diff_cli(&origin, &[]).await; + + assert_eq!(output.status.code(), Some(1)); + assert!(output.stdout.is_empty()); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(stderr.contains("run 3 has not finished"), "{stderr}"); + server.abort(); +} + +#[tokio::test] +async fn diff_never_reports_an_incomplete_run_as_resolved() { + let (origin, server) = serve_diff( + vec![2, 3], + vec![ + ( + 2, + diff_detail( + 2, + "COMPLETED", + vec![diff_finding(Some("keep"), "SERIOUS", "still there")], + ), + ), + (3, diff_detail(3, "INCOMPLETE", Vec::new())), + ], + ) + .await; + + let output = diff_cli(&origin, &[]).await; + + assert_eq!(output.status.code(), Some(2)); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!(stdout.contains("Not comparable:"), "{stdout}"); + assert!(stdout.contains("environment:"), "{stdout}"); + assert!(stdout.contains("still there"), "{stdout}"); + assert!(stdout.contains("Resolved (0):"), "{stdout}"); + assert!(!stdout.contains("Resolved (1):"), "{stdout}"); + server.abort(); +} + +#[tokio::test] +async fn diff_reports_a_missing_run_as_http_404() { + let (origin, server) = serve_diff( + vec![2, 3], + vec![(2, diff_detail(2, "COMPLETED", Vec::new()))], + ) + .await; + + let output = diff_cli(&origin, &[]).await; + + assert_eq!(output.status.code(), Some(1)); + assert!(output.stdout.is_empty()); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(stderr.contains("HTTP 404"), "{stderr}"); + server.abort(); +} + +#[tokio::test] +async fn diff_needs_two_runs() { + let (origin, server) = + serve_diff(vec![1], vec![(1, diff_detail(1, "COMPLETED", Vec::new()))]).await; + + let output = diff_cli(&origin, &[]).await; + + assert_eq!(output.status.code(), Some(1)); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!( + stderr.contains("only run 1; a diff needs two runs"), + "{stderr}" + ); + server.abort(); +} + +#[tokio::test] +async fn diff_labels_findings_and_emits_the_documented_json() { + let (origin, server) = serve_diff( + vec![2, 3], + vec![ + ( + 2, + diff_detail( + 2, + "COMPLETED", + vec![ + diff_finding(Some("keep"), "WARNING", "still there"), + diff_finding(Some("fixed"), "SERIOUS", "was fixed"), + diff_finding(None, "WARNING", "previous unknown"), + ], + ), + ), + ( + 3, + diff_detail( + 3, + "COMPLETED", + vec![ + diff_finding(Some("keep"), "SERIOUS", "still there"), + diff_finding(Some("new"), "WARNING", "brand new"), + diff_finding(None, "NOTE", "current unknown"), + ], + ), + ), + ], + ) + .await; + + let output = diff_cli(&origin, &[]).await; + assert_eq!( + output.status.code(), + Some(0), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let stdout = String::from_utf8_lossy(&output.stdout); + for label in [ + "New (1):", + "Resolved (1):", + "Persisting (1):", + "Uncorrelated (2):", + ] { + assert!(stdout.contains(label), "{stdout}"); + } + assert!(stdout.contains("was WARNING"), "{stdout}"); + + let output = diff_cli(&origin, &["--json"]).await; + assert_eq!( + output.status.code(), + Some(0), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let document: Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(document["repository"], "acme/web"); + assert_eq!(document["pull_request"], 7); + assert_eq!(document["from"], 2); + assert_eq!(document["to"], 3); + assert_eq!(document["from_status"], "COMPLETED"); + assert_eq!(document["to_status"], "COMPLETED"); + assert_eq!(document["new"].as_array().unwrap().len(), 1); + assert_eq!(document["resolved"].as_array().unwrap().len(), 1); + assert_eq!(document["persisting"].as_array().unwrap().len(), 1); + assert_eq!(document["uncorrelated"].as_array().unwrap().len(), 2); + assert_eq!(document["not_comparable"], json!([])); + server.abort(); +} + +#[tokio::test] +async fn diff_follows_a_truncated_run_history_to_the_newest_runs() { + let pages = Arc::new(AtomicUsize::new(0)); + let observed = Arc::clone(&pages); + let details: Arc> = Arc::new( + [ + (2, diff_detail(2, "COMPLETED", Vec::new())), + (3, diff_detail(3, "COMPLETED", Vec::new())), + ] + .into_iter() + .collect(), + ); + let app = Router::new() + .route( + &format!("/api/v1/organizations/{ORG}/reviews/pr/{{repository}}/{{number}}"), + get(move |uri: axum::http::Uri| { + let observed = Arc::clone(&observed); + async move { + let second = observed.fetch_add(1, Ordering::SeqCst) == 1; + if second { + assert_eq!(uri.query(), Some("cursor=next")); + Json(json!({ + "items": [diff_summary(3)], + "next_cursor": null, + "truncated": false, + "filters": { "repositories": [{ "id": REPOSITORY, "name": "acme/web" }] }, + })) + } else { + assert_eq!(uri.query(), None); + Json(json!({ + "items": [diff_summary(1), diff_summary(2)], + "next_cursor": "next", + "truncated": true, + "filters": { "repositories": [{ "id": REPOSITORY, "name": "acme/web" }] }, + })) + } + } + }), + ) + .route( + &format!( + "/api/v1/organizations/{ORG}/reviews/pr/{{repository}}/{{number}}/runs/{{run}}" + ), + get( + move |Path((_repository, _number, run)): Path<(String, u64, u64)>| { + let details = Arc::clone(&details); + async move { Json(details.get(&run).unwrap().clone()) } + }, + ), + ); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let origin = format!("http://{}", listener.local_addr().unwrap()); + let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + + let output = diff_cli(&origin, &["--json"]).await; + + assert_eq!( + output.status.code(), + Some(0), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let document: Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(document["from"], 2); + assert_eq!(document["to"], 3); + assert_eq!(pages.load(Ordering::SeqCst), 2); + server.abort(); +}