From 7d4d138c5d190014199b447fe1e79ea1c0aa5e5f Mon Sep 17 00:00:00 2001 From: sathishking Date: Sun, 29 Nov 2026 00:07:13 +0530 Subject: [PATCH] feat: add proofline walkthrough and surface live progress and merge gate --- README.md | 2 +- src/lib.rs | 198 +++++++++++++++++++++++++++++++++++--- src/model.rs | 110 +++++++++++++++++++++ src/outcome.rs | 7 ++ src/render.rs | 240 +++++++++++++++++++++++++++++++++++++++++++++- tests/contract.rs | 18 +++- tests/http.rs | 208 ++++++++++++++++++++++++++++++++++++++++ 7 files changed, 763 insertions(+), 20 deletions(-) diff --git a/README.md b/README.md index eea0165..d107e38 100644 --- a/README.md +++ b/README.md @@ -36,7 +36,7 @@ Native knowledge, plan, fix and configuration commands send the selected organiz `proofline review --path src/main.rs` reviews only that file's local changes against the normal merge-base. The path is literal and repository-relative; the command refuses directories, globs, and `..`. Combine it with `--staged` to read the index, or `--include-untracked` to select a new, non-ignored file. The command preserves the real index and applies the usual secret preflight. You cannot combine `--path` with pushed-commit, range, or pull-request review. -`proofline reviews --repository-id UUID --cursor CURSOR` returns one page with its continuation metadata, and all flags are optional. `proofline routing REVIEW_ID` reads recorded routing. `proofline run --repo owner/name --pr 7 --run 2` reads one retained run, and `proofline history --repo owner/name --pr 7` reads all recorded runs. Both commands send the API the name without its owner, and use the response only when its repository choices list `owner/name`, or the Git remote's owner and name, among the organization's reviewed repositories. A repository with no reviews in the organization exits nonzero. `proofline findings --pr 7` finds the pull request's newest review through the same route and counts only runs of the repository whose full name matches. None of these commands reads the organization's review list. +`proofline reviews --repository-id UUID --cursor CURSOR` returns one page with its continuation metadata, and all flags are optional. `proofline routing REVIEW_ID` reads recorded routing. `proofline run --repo owner/name --pr 7 --run 2` reads one retained run, and `proofline history --repo owner/name --pr 7` reads all recorded runs. Both commands send the API the name without its owner, and use the response only when its repository choices list `owner/name`, or the Git remote's owner and name, among the organization's reviewed repositories. A repository with no reviews in the organization exits nonzero. `proofline findings --pr 7` finds the pull request's newest review through the same route and counts only runs of the repository whose full name matches, while `proofline walkthrough --pr 7` renders its reading-order file groups, per-file notes, and skipped-file reasons. None of these commands reads the organization's review list. `proofline rerun REVIEW_ID` requests the original immutable subject and waits, while `--no-wait` returns its link. Reruns require `reviews:rerun`. `proofline guidance --repo owner/name` requires `guidance:read`, and `proofline fix-prompt FINDING_ID` requires `findings:read`. History, guidance, and fix prompts print JSON; prompt text remains untrusted. diff --git a/src/lib.rs b/src/lib.rs index 8c6f1d6..db60d11 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -169,6 +169,8 @@ enum Command { Stop(StopArgs), /// Show the findings of the latest review of a commit or pull request. Findings(FindingsArgs), + /// Show the reading-order file walkthrough of a pull request, commit, or review. + Walkthrough(WalkthroughArgs), /// Forward a coding agent's stdio messages to this console's MCP server. Mcp, /// Commands for a CI job. @@ -399,6 +401,19 @@ struct FindingsArgs { output: OutputArgs, } +#[derive(Debug, Args)] +struct WalkthroughArgs { + #[command(flatten)] + selector: Selector, + /// Wait for the review's walkthrough to be stored. + #[arg(long)] + wait: bool, + #[command(flatten)] + repository: RepositoryArgs, + #[command(flatten)] + output: OutputArgs, +} + #[derive(Debug, Clone, Copy)] enum OutputFormat { Text, @@ -607,6 +622,13 @@ pub async fn run(cli: Cli, token: Option) -> anyhow::Result { + if let Some(head) = &args.selector.head { + git::commit_sha(head)?; + } + let api = connect(Http::new(origin)?, token, cli.org).await?; + walkthrough(&api, &args).await + } Command::Mcp => { let http = Http::new(origin)?; let credential = credentials::load(http.origin(), token, cli.org).await?; @@ -1206,25 +1228,33 @@ async fn finish(api: &Api, review_id: Uuid, args: &ReviewArgs) -> anyhow::Result .await } -async fn findings(api: &Api, args: &FindingsArgs) -> anyhow::Result { - let review_id = match (&args.selector.review, args.selector.pr) { - (Some(id), _) => *id, - (None, Some(number)) => pull_request_review(api, &args.repository, number).await?, +async fn resolve_review_id( + api: &Api, + selector: &Selector, + repository: &RepositoryArgs, +) -> anyhow::Result { + match (&selector.review, selector.pr) { + (Some(id), _) => Ok(*id), + (None, Some(number)) => pull_request_review(api, repository, number).await, (None, None) => { - let sha = match &args.selector.head { + let sha = match &selector.head { Some(raw) => git::commit_sha(raw)?, None => git::head().await?, }; - let (name, repository_id) = reviewed_repository(api, &args.repository).await?; + let (name, repository_id) = reviewed_repository(api, repository).await?; // An audit is a revision scan of this commit too, but its // findings are in its report, so it never answers for the head. latest(api, repository_id, &sha, |item| { item.audit_mode.is_none() && item.head_commit_sha.as_deref() == Some(sha.as_str()) }) - .await? - .with_context(|| format!("no review of {name} has head commit {sha}; push it and open a pull request, or name one with --pr"))? + .await? + .with_context(|| format!("no review of {name} has head commit {sha}; push it and open a pull request, or name one with --pr")) } - }; + } +} + +async fn findings(api: &Api, args: &FindingsArgs) -> anyhow::Result { + let review_id = resolve_review_id(api, &args.selector, &args.repository).await?; let format = if args.sarif { OutputFormat::Sarif } else { @@ -1233,6 +1263,54 @@ async fn findings(api: &Api, args: &FindingsArgs) -> anyhow::Result { show(api, review_id, args.wait, &args.output, format, None).await } +async fn walkthrough(api: &Api, args: &WalkthroughArgs) -> anyhow::Result { + let review_id = resolve_review_id(api, &args.selector, &args.repository).await?; + let deadline = if args.wait { + Some(poll_deadline(args.output.timeout)?) + } else { + None + }; + let Some((raw, detail, state)) = + read_review_until(api, review_id, deadline, false, |detail, terminal| { + terminal.is_some() || detail.walkthrough.is_some() + }) + .await? + else { + say_not_established(api, review_id, args.output.timeout); + return Ok(Verdict::Unavailable); + }; + let Some(walkthrough) = &detail.walkthrough else { + let url = api.review_url(review_id); + match state { + None => say(&format!( + "No walkthrough is stored for this review yet (status: {}); pass --wait or check {url}.", + text::one_line(&detail.status) + )), + Some(_) => say(&format!( + "No walkthrough was recorded for this review ({}); see {url}.", + text::one_line(&detail.status) + )), + } + return Ok(Verdict::NotComplete); + }; + let url = api.review_url(review_id); + if args.output.json { + let document = serde_json::json!({ + "review_id": detail.id, + "review_url": url.as_str(), + "diff_stats": raw.get("diff_stats").unwrap_or(&serde_json::Value::Null), + "walkthrough": raw.get("walkthrough").unwrap_or(&serde_json::Value::Null), + }); + return tools::json(&document); + } + write!( + std::io::stdout().lock(), + "{}", + render::walkthrough(&detail, walkthrough, &url) + )?; + Ok(Verdict::Done) +} + #[derive(Debug, thiserror::Error)] #[error("--timeout {minutes} minutes is too large to wait; choose a shorter timeout")] struct PollTimeoutTooLarge { @@ -1264,6 +1342,16 @@ async fn read_review( review_id: Uuid, deadline: Option, sarif: bool, +) -> anyhow::Result> { + read_review_until(api, review_id, deadline, sarif, |_, state| state.is_some()).await +} + +async fn read_review_until( + api: &Api, + review_id: Uuid, + deadline: Option, + sarif: bool, + ready: impl Fn(&ReviewDetail, Option) -> bool, ) -> anyhow::Result> { let deadline = match deadline { Some(deadline) if tokio::time::Instant::now() < deadline => deadline, @@ -1278,13 +1366,10 @@ async fn read_review( }; let read = read?; let now = tokio::time::Instant::now(); - if read.2.is_some() || now >= deadline { + if ready(&read.1, read.2) || now >= deadline { return Ok(Some(read)); } - say(&format!( - "Review is {}; checking again in {delay} seconds.", - text::one_line(&read.1.status) - )); + say(&poll_status(&read.1, delay)); tokio::time::sleep_until(deadline.min(now + Duration::from_secs(delay))).await; if tokio::time::Instant::now() >= deadline { return Ok(Some(read)); @@ -1293,6 +1378,48 @@ async fn read_review( } } +/// Formats a live polling progress line, surfacing `provider_wait` and +/// `run_progress` when the server reports them. +fn poll_status(detail: &ReviewDetail, delay: u64) -> String { + let status = text::one_line(&detail.status); + let context = match (&detail.provider_wait, &detail.run_progress) { + (Some(wait), _) => { + let reason = match wait.reason.as_str() { + "GITHUB_RATE_LIMIT" => "GitHub rate limit".to_owned(), + other => text::one_line(other), + }; + format!( + " (waiting on {reason} until {})", + text::one_line(&wait.until) + ) + } + (None, Some(progress)) => { + let step = match progress.state.as_str() { + "RETRY_SCHEDULED" => progress.due_at.as_deref().map_or_else( + || "retry scheduled".to_owned(), + |due| format!("retry scheduled for {}", text::one_line(due)), + ), + "QUEUED" => progress.due_at.as_deref().map_or_else( + || "queued".to_owned(), + |due| format!("queued since {}", text::one_line(due)), + ), + "WAITING" => progress.due_at.as_deref().map_or_else( + || "waiting".to_owned(), + |due| format!("waiting until {}", text::one_line(due)), + ), + other => text::one_line(&other.to_ascii_lowercase()), + }; + if progress.attempts > 1 { + format!(" ({step}, attempt {})", progress.attempts) + } else { + format!(" ({step})") + } + } + (None, None) => String::new(), + }; + format!("Review is {status}{context}; checking again in {delay} seconds.") +} + async fn read_review_once(api: &Api, review_id: Uuid, sarif: bool) -> anyhow::Result { let (raw, detail) = api.review(review_id).await?; outcome::same_review(&detail, review_id)?; @@ -2373,4 +2500,47 @@ mod tests { Verdict::NotComplete ); } + + #[test] + fn poll_status_surfaces_provider_wait_and_run_progress() { + let mut detail: ReviewDetail = serde_json::from_value(json!({ + "id": REQUESTED, + "kind": "PULL_REQUEST", + "status": "PENDING", + "assessment_count": 1, + "assessments": [], + "code_assessment": null, + "base_commit_sha": null, + "head_commit_sha": HEAD, + "open_items": null, + "pull_request_number": 12, + "repository_full_name": "acme/app", + "run_number": 1, + })) + .unwrap(); + assert_eq!( + poll_status(&detail, 10), + "Review is PENDING; checking again in 10 seconds." + ); + + detail.run_progress = Some(model::RunProgress { + state: "RETRY_SCHEDULED".to_owned(), + attempts: 2, + due_at: Some("2026-11-28T12:05:00Z".to_owned()), + last_progress_at: None, + }); + assert_eq!( + poll_status(&detail, 20), + "Review is PENDING (retry scheduled for 2026-11-28T12:05:00Z, attempt 2); checking again in 20 seconds." + ); + + detail.provider_wait = Some(model::ProviderWait { + reason: "GITHUB_RATE_LIMIT".to_owned(), + until: "2026-11-28T12:15:00Z".to_owned(), + }); + assert_eq!( + poll_status(&detail, 60), + "Review is PENDING (waiting on GitHub rate limit until 2026-11-28T12:15:00Z); checking again in 60 seconds." + ); + } } diff --git a/src/model.rs b/src/model.rs index e029008..c642d58 100644 --- a/src/model.rs +++ b/src/model.rs @@ -98,6 +98,116 @@ pub struct ReviewDetail { /// every other review. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub local_reverifications: Vec, + /// Where an unfinished review's runs currently stand. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub run_progress: Option, + /// Provider wait holding this review, such as a GitHub rate limit. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub provider_wait: Option, + /// Line totals across changed files in the pinned comparison. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub diff_stats: Option, + /// Deterministic pull-request merge gate captured for this head. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub merge_gate: Option, + /// Automatic Deep Review escalation outcome for this comparison. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub deep_review_escalation: Option, + /// Public incompleteness causes recorded by incomplete assessments. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub incomplete_causes: Option>, + /// Reading-order walkthrough of the reviewed head's changed files. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub walkthrough: Option, +} + +/// Where an unfinished review's runs stand. +#[derive(Debug, Deserialize, Serialize)] +pub struct RunProgress { + pub state: String, + pub attempts: i32, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub due_at: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub last_progress_at: Option, +} + +/// A provider wait currently holding a review. +#[derive(Debug, Deserialize, Serialize)] +pub struct ProviderWait { + pub reason: String, + pub until: String, +} + +/// Line totals across changed files in a review's pinned comparison. +#[derive(Debug, Deserialize, Serialize)] +pub struct ReviewDiffStats { + pub additions: i64, + pub deletions: i64, +} + +/// Deterministic pull-request merge gate state for a reviewed head. +#[derive(Debug, Deserialize, Serialize)] +pub struct PullRequestMergeGate { + pub id: Uuid, + pub pull_request_number: i64, + pub head_sha: String, + pub status: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub decision: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub reason_code: Option, + pub policy_version: String, + pub blocking_severity: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub finding_count: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub assessment_count: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub bypassed_at: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub merged_by_login: Option, +} + +/// Automatic Deep Review escalation status for a comparison. +#[derive(Debug, Deserialize, Serialize)] +pub struct DeepReviewEscalation { + pub status: String, + pub reason: String, +} + +/// Reading-order walkthrough of a review's pinned head. +#[derive(Debug, Deserialize, Serialize)] +pub struct Walkthrough { + pub head_sha: String, + pub groups: Vec, +} + +/// One logical group of changed files in a walkthrough. +#[derive(Debug, Deserialize, Serialize)] +pub struct WalkthroughGroup { + pub title: String, + pub kind: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub description: Option, + pub files: Vec, +} + +/// One changed file entry in a walkthrough group. +#[derive(Debug, Deserialize, Serialize)] +pub struct WalkthroughFile { + pub path: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub previous_path: Option, + pub change: String, + pub additions: i64, + pub deletions: i64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub depth: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub skip_class: Option, + pub line: String, + pub generated: bool, } /// One finding a patch review re-verified against the local changes. The diff --git a/src/outcome.rs b/src/outcome.rs index 5bc661b..ae39600 100644 --- a/src/outcome.rs +++ b/src/outcome.rs @@ -341,6 +341,13 @@ mod tests { repository_full_name: Some("acme/web".to_owned()), run_number: Some(1), local_reverifications: Vec::new(), + run_progress: None, + provider_wait: None, + diff_stats: None, + merge_gate: None, + deep_review_escalation: None, + incomplete_causes: None, + walkthrough: None, } } diff --git a/src/render.rs b/src/render.rs index 782b09f..6a80de8 100644 --- a/src/render.rs +++ b/src/render.rs @@ -6,7 +6,8 @@ use std::cmp::Reverse; use url::Url; use crate::model::{ - Assessment, CodeAssessment, Finding, LocalReverification, ReviewDetail, StoredCheck, + Assessment, CodeAssessment, DeepReviewEscalation, Finding, LocalReverification, + PullRequestMergeGate, ReviewDetail, ReviewDiffStats, StoredCheck, Walkthrough, WalkthroughFile, }; use crate::outcome::{self, Outcome}; use crate::severity::Severity; @@ -213,6 +214,27 @@ pub fn audit(url: &Url) -> String { pub fn review(review: &ReviewDetail, state: Option, url: &Url) -> String { let mut out = vec![headline(review, state), url.to_string()]; + if let Some(stats) = &review.diff_stats { + out.push(diff_stats_line(stats)); + } + if let Some(gate) = &review.merge_gate { + out.push(merge_gate_line(gate)); + } + if let Some(escalation) = &review.deep_review_escalation + && escalation.status != "NOT_SELECTED" + { + out.push(escalation_line(escalation)); + } + if let Some(causes) = &review.incomplete_causes + && !causes.is_empty() + { + let joined = causes + .iter() + .map(|cause| one_line(cause)) + .collect::>() + .join(", "); + out.push(format!("Incomplete causes: {joined}")); + } if let Some(reason) = outcome::review_gap(review) { out.push(format!("Review incomplete: {reason}")); } @@ -235,6 +257,107 @@ pub fn review(review: &ReviewDetail, state: Option, url: &Url) -> Strin out.join("\n") } +fn diff_stats_line(stats: &ReviewDiffStats) -> String { + format!("Diff: +{} -{}", stats.additions, stats.deletions) +} + +fn merge_gate_line(gate: &PullRequestMergeGate) -> String { + let reason = gate + .reason_code + .as_deref() + .map_or_else(String::new, |code| format!(", reason {}", one_line(code))); + let bypass = match (&gate.bypassed_at, &gate.merged_by_login) { + (Some(_), Some(login)) => format!(", bypassed by {}", one_line(login)), + (Some(_), None) => ", bypassed".to_owned(), + _ => String::new(), + }; + format!( + "Merge gate: {} (policy {}, blocks on {}{reason}{bypass})", + one_line(&gate.status), + one_line(&gate.policy_version), + one_line(&gate.blocking_severity), + ) +} + +fn escalation_line(escalation: &DeepReviewEscalation) -> String { + format!( + "Deep review: {} ({})", + one_line(&escalation.status), + one_line(&escalation.reason) + ) +} + +/// Renders a review's reading-order file walkthrough as terminal-safe text. +pub fn walkthrough(review: &ReviewDetail, walkthrough: &Walkthrough, url: &Url) -> String { + let subject = match (&review.repository_full_name, review.pull_request_number) { + (Some(repository), Some(number)) => format!("{} #{number}", one_line(repository)), + (Some(repository), None) => one_line(repository), + _ => one_line(&review.kind), + }; + let head_short = one_line( + walkthrough + .head_sha + .get(..12) + .unwrap_or(&walkthrough.head_sha), + ); + let mut out = vec![format!("{subject} at {head_short}"), url.to_string()]; + if let Some(stats) = &review.diff_stats { + out.push(diff_stats_line(stats)); + } + let total_files: usize = walkthrough + .groups + .iter() + .map(|group| group.files.len()) + .sum(); + let skipped_files: usize = walkthrough + .groups + .iter() + .flat_map(|group| &group.files) + .filter(|file| file.skip_class.is_some()) + .count(); + let evaluated_files = total_files.saturating_sub(skipped_files); + out.push(format!( + "Walkthrough ({} groups, {total_files} files: {evaluated_files} evaluated, {skipped_files} skipped):", + walkthrough.groups.len() + )); + + for group in &walkthrough.groups { + out.push(String::new()); + out.push(format!( + "[{}] {}", + one_line(&group.kind), + one_line(&group.title) + )); + if let Some(description) = &group.description { + out.push(format!(" {}", one_line(description))); + } + for file in &group.files { + walkthrough_file(&mut out, file); + } + } + out.push(String::new()); + out.join("\n") +} + +fn walkthrough_file(out: &mut Vec, file: &WalkthroughFile) { + let path = file.previous_path.as_deref().map_or_else( + || one_line(&file.path), + |previous| format!("{} -> {}", one_line(previous), one_line(&file.path)), + ); + let qualifier = match (&file.skip_class, &file.depth) { + (Some(skip), _) => format!(" [skipped: {}]", one_line(skip)), + (None, Some(depth)) => format!(" [{}]", one_line(depth)), + (None, None) => String::new(), + }; + out.push(format!( + " {:<8} {path} (+{}/-{}){qualifier}", + one_line(&file.change), + file.additions, + file.deletions, + )); + out.push(format!(" {}", one_line(&file.line))); +} + #[cfg(test)] mod tests { use super::*; @@ -271,6 +394,13 @@ mod tests { repository_full_name: Some("acme/web".to_owned()), run_number: Some(2), local_reverifications: Vec::new(), + run_progress: None, + provider_wait: None, + diff_stats: None, + merge_gate: None, + deep_review_escalation: None, + incomplete_causes: None, + walkthrough: None, } } @@ -344,4 +474,112 @@ mod tests { assert!(!text.contains('\u{1b}')); assert!(text.contains("x\u{FFFD}[2J y")); } + + #[test] + fn review_surfaces_diff_stats_merge_gate_escalation_and_incomplete_causes() { + let mut detail = sample("INCOMPLETE", Vec::new()); + detail.diff_stats = Some(ReviewDiffStats { + additions: 42, + deletions: 7, + }); + detail.merge_gate = Some(PullRequestMergeGate { + id: uuid::Uuid::nil(), + pull_request_number: 42, + head_sha: "0123456789abcdef0123456789abcdef01234567".to_owned(), + status: "BYPASSED".to_owned(), + decision: Some("BLOCK".to_owned()), + reason_code: Some("SERIOUS_FINDING".to_owned()), + policy_version: "v2".to_owned(), + blocking_severity: "SERIOUS".to_owned(), + finding_count: Some(1), + assessment_count: Some(1), + bypassed_at: Some("2026-11-28T10:00:00Z".to_owned()), + merged_by_login: Some("alice".to_owned()), + }); + detail.deep_review_escalation = Some(DeepReviewEscalation { + status: "ADMITTED".to_owned(), + reason: "Auth boundary modified".to_owned(), + }); + detail.incomplete_causes = Some(vec!["OUT_OF_CREDITS".to_owned()]); + let text = review(&detail, outcome::terminal(&detail), &url()); + assert!(text.contains("Diff: +42 -7"), "{text}"); + assert!( + text.contains( + "Merge gate: BYPASSED (policy v2, blocks on SERIOUS, reason SERIOUS_FINDING, bypassed by alice)" + ), + "{text}" + ); + assert!( + text.contains("Deep review: ADMITTED (Auth boundary modified)"), + "{text}" + ); + assert!(text.contains("Incomplete causes: OUT_OF_CREDITS"), "{text}"); + } + + #[test] + fn walkthrough_renders_groups_renames_skips_and_sanitizes_untrusted_text() { + use crate::model::WalkthroughGroup; + + let mut detail = sample("COMPLETED", Vec::new()); + detail.diff_stats = Some(ReviewDiffStats { + additions: 15, + deletions: 3, + }); + let guide = Walkthrough { + head_sha: "0123456789abcdef0123456789abcdef01234567".to_owned(), + groups: vec![ + WalkthroughGroup { + title: "Auth\u{1b}[31m flow".to_owned(), + kind: "FEATURE".to_owned(), + description: Some("Tighten token checks".to_owned()), + files: vec![WalkthroughFile { + path: "src/auth.rs".to_owned(), + previous_path: Some("src/old_auth.rs".to_owned()), + change: "RENAMED".to_owned(), + additions: 12, + deletions: 3, + depth: Some("DEEP".to_owned()), + skip_class: None, + line: "Enforces\u{202E}scope checks.".to_owned(), + generated: true, + }], + }, + WalkthroughGroup { + title: "Lockfile".to_owned(), + kind: "DEPENDENCIES".to_owned(), + description: None, + files: vec![WalkthroughFile { + path: "Cargo.lock".to_owned(), + previous_path: None, + change: "MODIFIED".to_owned(), + additions: 3, + deletions: 0, + depth: None, + skip_class: Some("LOCKFILE".to_owned()), + line: "Dependency lockfile update.".to_owned(), + generated: false, + }], + }, + ], + }; + let text = walkthrough(&detail, &guide, &url()); + assert!(!text.contains('\u{1b}')); + assert!(!text.contains('\u{202E}')); + assert!(text.contains("acme/web #42 at 0123456789ab"), "{text}"); + assert!(text.contains("Diff: +15 -3"), "{text}"); + assert!( + text.contains("Walkthrough (2 groups, 2 files: 1 evaluated, 1 skipped):"), + "{text}" + ); + assert!(text.contains("[FEATURE] Auth\u{FFFD}[31m flow"), "{text}"); + assert!( + text.contains("RENAMED src/old_auth.rs -> src/auth.rs (+12/-3) [DEEP]"), + "{text}" + ); + assert!(text.contains("Enforces\u{FFFD}scope checks."), "{text}"); + assert!( + text.contains("MODIFIED Cargo.lock (+3/-0) [skipped: LOCKFILE]"), + "{text}" + ); + } } diff --git a/tests/contract.rs b/tests/contract.rs index cf7ae44..47a1463 100644 --- a/tests/contract.rs +++ b/tests/contract.rs @@ -5,10 +5,12 @@ use std::process::Command; use proofline_cli::model::{ Assessment, Check, Checks, CodeAssessment, CommitDeploy, CommitDeployVerifications, CommitReviewRequest, CommitReviewResponse, CoverageUploadRequest, CoverageUploadResponse, - DeployCheckpoint, EvidenceRef, FileReviewRequest, FileReviewResponse, FileScope, FilterChoice, - Finding, OpenItems, PatchReviewRequest, PatchReviewResponse, RepositoryName, RepositoryNames, - ReviewDetail, ReviewFilters, ReviewPage, ReviewSubject, ReviewSummary, RunNowMode, - RunNowRequest, RunNowResponse, StopResponse, UploadedReport, + DeepReviewEscalation, DeployCheckpoint, EvidenceRef, FileReviewRequest, FileReviewResponse, + FileScope, FilterChoice, Finding, OpenItems, PatchReviewRequest, PatchReviewResponse, + ProviderWait, PullRequestMergeGate, RepositoryName, RepositoryNames, ReviewDetail, + ReviewDiffStats, ReviewFilters, ReviewPage, ReviewSubject, ReviewSummary, RunNowMode, + RunNowRequest, RunNowResponse, RunProgress, StopResponse, UploadedReport, Walkthrough, + WalkthroughFile, WalkthroughGroup, }; use serde::Serialize; use serde::de::DeserializeOwned; @@ -155,6 +157,14 @@ fn types_match_the_public_contract() { holds::("RepositoryName"); holds::("ReviewSummary"); holds::("CustomerReviewDetail"); + holds::("RunProgress"); + holds::("ProviderWait"); + holds::("ReviewDiffStats"); + holds::("PullRequestMergeGate"); + holds::("DeepReviewEscalation"); + holds::("WalkthroughView"); + holds::("WalkthroughGroupView"); + holds::("WalkthroughFileView"); holds::("OpenItemsView"); holds::("CustomerAssessment"); holds::("CustomerCodeAssessment"); diff --git a/tests/http.rs b/tests/http.rs index 940dc12..4f1a602 100644 --- a/tests/http.rs +++ b/tests/http.rs @@ -3647,3 +3647,211 @@ async fn config_proposal_targets_must_match_the_selected_organization() { assert_eq!(server.requests()[0]["arguments"]["organization_id"], ORG); assert_eq!(server.frames.load(Ordering::SeqCst), 3); } + +#[tokio::test] +async fn walkthrough_reads_and_waits_while_polling_reports_progress_and_provider_waits() { + let review_id = SELECTED_REVIEW; + let head = "0123456789abcdef0123456789abcdef01234567"; + let reads = Arc::new(AtomicUsize::new(0)); + let reads_route = Arc::clone(&reads); + + let app = Router::new() + .route( + &format!("/api/v1/organizations/{ORG}/reviews/pr/web/42"), + get(move || async move { + Json(json!({ + "items": [{ + "id": review_id, + "kind": "PULL_REQUEST", + "status": "RUNNING", + "created_at": "2026-11-28T10:00:00Z", + "head_commit_sha": head, + "pull_request_number": 42, + "repository_id": REPOSITORY, + "run_number": 1, + }], + "next_cursor": null, + "truncated": false, + "filters": { + "repositories": [{ "id": REPOSITORY, "name": "acme/web" }] + } + })) + }), + ) + .route( + &format!("/api/v1/organizations/{ORG}/reviews/{review_id}"), + get(move || { + let reads_route = Arc::clone(&reads_route); + async move { + let read = reads_route.fetch_add(1, Ordering::SeqCst); + if read == 0 { + return Json(json!({ + "id": review_id, + "kind": "PULL_REQUEST", + "status": "PENDING", + "assessment_count": 1, + "assessments": [], + "provider_wait": { + "reason": "GITHUB_RATE_LIMIT", + "until": "2026-11-28T10:05:00Z" + }, + "run_progress": { + "state": "WAITING", + "attempts": 1, + "due_at": "2026-11-28T10:05:00Z" + }, + "head_commit_sha": head, + "pull_request_number": 42, + "repository_full_name": "acme/web", + "run_number": 1, + })) + .into_response(); + } + Json(json!({ + "id": review_id, + "kind": "PULL_REQUEST", + "status": "COMPLETED", + "assessment_count": 1, + "assessments": [{ + "id": "0190f3a0-0000-7000-8000-000000000044", + "environment_display_name": "production", + "status": "COMPLETED", + "findings": [], + "checks": { "receipt_recorded": true, "status": "READY", "families": [] }, + }], + "diff_stats": { "additions": 10, "deletions": 2 }, + "merge_gate": { + "id": "0190f3a0-0000-7000-8000-000000000055", + "pull_request_number": 42, + "head_sha": head, + "status": "ALLOWED", + "decision": "ALLOW", + "policy_version": "v1", + "blocking_severity": "SERIOUS" + }, + "deep_review_escalation": { + "status": "ADMITTED", + "reason": "Sensitive IAM path changed" + }, + "walkthrough": { + "head_sha": head, + "groups": [{ + "title": "IAM permissions", + "kind": "INFRASTRUCTURE", + "description": "Scope S3 policy", + "files": [{ + "path": "infra/iam.tf", + "change": "MODIFIED", + "additions": 10, + "deletions": 2, + "depth": "DEEP", + "line": "Restricts bucket write actions.", + "generated": true + }] + }] + }, + "head_commit_sha": head, + "pull_request_number": 42, + "repository_full_name": "acme/web", + "run_number": 1, + })) + .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() }); + + // 1. Without --wait on the first read (no walkthrough stored yet), exits 2 clearly. + let pending = cli( + &origin, + &["walkthrough", "--repo", "acme/web", "--pr", "42"], + ) + .await; + assert_eq!(pending.status.code(), Some(2)); + let pending_stderr = String::from_utf8_lossy(&pending.stderr); + assert!( + pending_stderr.contains("No walkthrough is stored for this review yet"), + "{pending_stderr}" + ); + + // 2. Reading again once stored renders the walkthrough, diff_stats, and groups. + let output = cli(&origin, &["walkthrough", "--review", review_id]).await; + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let stdout = String::from_utf8(output.stdout).unwrap(); + assert!(stdout.contains("acme/web #42 at 0123456789ab"), "{stdout}"); + assert!(stdout.contains("Diff: +10 -2"), "{stdout}"); + assert!( + stdout.contains("Walkthrough (1 groups, 1 files: 1 evaluated, 0 skipped):"), + "{stdout}" + ); + assert!( + stdout.contains("[INFRASTRUCTURE] IAM permissions"), + "{stdout}" + ); + assert!( + stdout.contains("MODIFIED infra/iam.tf (+10/-2) [DEEP]"), + "{stdout}" + ); + + // 3. `--json` preserves the raw walkthrough and diff_stats payload. + let json_out = cli(&origin, &["walkthrough", "--review", review_id, "--json"]).await; + assert!(json_out.status.success()); + let parsed: Value = serde_json::from_slice(&json_out.stdout).unwrap(); + assert_eq!(parsed["review_id"], review_id); + assert_eq!(parsed["diff_stats"]["additions"], 10); + assert_eq!( + parsed["walkthrough"]["groups"][0]["title"], + "IAM permissions" + ); + + // 4. `findings --review` surfaces diff_stats, merge_gate, and deep_review_escalation. + let findings_out = cli(&origin, &["findings", "--review", review_id]).await; + assert!(findings_out.status.success()); + let findings_stdout = String::from_utf8(findings_out.stdout).unwrap(); + assert!( + findings_stdout.contains("Diff: +10 -2"), + "{findings_stdout}" + ); + assert!( + findings_stdout.contains("Merge gate: ALLOWED (policy v1, blocks on SERIOUS)"), + "{findings_stdout}" + ); + assert!( + findings_stdout.contains("Deep review: ADMITTED (Sensitive IAM path changed)"), + "{findings_stdout}" + ); + + // 5. Reset read count to 0 and verify `--wait` reports `provider_wait` while polling. + reads.store(0, Ordering::SeqCst); + let waited = cli( + &origin, + &[ + "findings", + "--review", + review_id, + "--wait", + "--timeout", + "1", + ], + ) + .await; + assert!( + waited.status.success(), + "{}", + String::from_utf8_lossy(&waited.stderr) + ); + let waited_stderr = String::from_utf8_lossy(&waited.stderr); + assert!( + waited_stderr.contains("waiting on GitHub rate limit until 2026-11-28T10:05:00Z"), + "{waited_stderr}" + ); + + server.abort(); +}