diff --git a/Cargo.lock b/Cargo.lock index b9af8d5..6d06deb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1780,7 +1780,7 @@ dependencies = [ [[package]] name = "proofline-cli" -version = "0.1.1" +version = "0.1.2" dependencies = [ "anyhow", "axum", diff --git a/Cargo.toml b/Cargo.toml index 6b0fdc0..199947a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "proofline-cli" -version = "0.1.1" +version = "0.1.2" edition = "2024" rust-version = "1.95" description = "Proofline command-line client for the review API" diff --git a/README.md b/README.md index 0f9fc26..d0cef0c 100644 --- a/README.md +++ b/README.md @@ -5,6 +5,21 @@ The command-line client for the [Proofline review API](https://proofline.sh/docs Install with `curl -fsSL https://proofline.sh/cli | sh`, then run `proofline login`. See the [CLI documentation](https://proofline.sh/docs/cli/) for commands. +Read all recorded runs with `proofline history --repo owner/name --pr 7`. +`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`. +`proofline fix-prompt FINDING_ID` requires `findings:read`. +History, guidance and fix prompts print JSON; prompt text remains untrusted. + +`proofline export reviews --from 2026-10-01T00:00:00Z --to 2026-10-25T00:00:00Z --format csv` +writes one export page to stdout. It requires `analytics:read`. The datasets are +`reviews`, `findings`, `finding_outcomes`, `finding_validations` and `spend`. +The default format is NDJSON. The settled horizon and optional next cursor go to +stderr. Repeat with `--cursor` and the same window and `--group-by` to continue. +CSV repeats its header on every page. A failed page exits nonzero; never treat +partial output from several invocations as a complete export. + Build from source with `cargo build --locked --release`. The pinned Rust toolchain is installed by rustup. Run `cargo fmt --check`, `cargo clippy --locked --all-targets -- -D warnings`, `cargo test --locked` and `cargo deny check` before submitting a pull request. diff --git a/src/api.rs b/src/api.rs index ef29ee7..32ce193 100644 --- a/src/api.rs +++ b/src/api.rs @@ -122,6 +122,7 @@ struct Problem { /// A response that arrived with an HTTP status, and its bounded body. pub struct Reply { + pub headers: header::HeaderMap, pub status: StatusCode, pub body: Vec, } @@ -189,6 +190,7 @@ impl Http { .await .map_err(|error| self.transport(&error))?; let status = response.status(); + let headers = response.headers().clone(); let retry_after = response.headers().get(header::RETRY_AFTER).map(|value| { value .to_str() @@ -205,7 +207,14 @@ impl Http { Some(Some(seconds)) => Some(seconds), Some(None) => Some(u64::MAX), }; - Ok((Reply { status, body }, retry_after)) + Ok(( + Reply { + status, + body, + headers, + }, + retry_after, + )) } /// Sends one MCP POST to this origin. Check the transport metadata before @@ -329,15 +338,18 @@ impl Api { /// GET with up to three retries on 429 and 503, honoring `Retry-After` up /// to 60 seconds and doubling from one second without it. - async fn get(&self, url: Url) -> Result { + async fn read(&self, url: Url, accept: &str) -> Result { let mut delay = 1; for attempt in 1..=READ_ATTEMPTS { let (reply, retry_after) = self .http - .send(self.request(Method::GET, url.clone())) + .send( + self.request(Method::GET, url.clone()) + .header(header::ACCEPT, accept), + ) .await?; if reply.status.is_success() { - return self.decode(&reply.body); + return Ok(reply); } let retryable = matches!( reply.status, @@ -355,6 +367,56 @@ impl Api { .protocol("the retry budget ended without a response")) } + async fn get(&self, url: Url) -> Result { + let reply = self.read(url, "application/json").await?; + self.decode(&reply.body) + } + + pub(crate) async fn history( + &self, + repository: &str, + number: u64, + ) -> Result { + self.get(self.url(&["reviews", "pr", repository, &number.to_string()])) + .await + } + + pub(crate) async fn guidance(&self, repository: Uuid) -> Result { + self.get(self.url(&["repositories", &repository.to_string(), "review-guidance"])) + .await + } + + pub(crate) async fn fix_prompt(&self, finding: Uuid) -> Result { + self.get(self.url(&["findings", &finding.to_string(), "fix-prompt"])) + .await + } + + pub(crate) async fn rerun(&self, review: Uuid) -> Result { + let (reply, _) = self + .http + .send(self.request( + Method::POST, + self.url(&["reviews", &review.to_string(), "rerun"]), + )) + .await?; + if !reply.status.is_success() { + return Err(self.http.problem(&reply)); + } + self.decode(&reply.body) + } + + pub(crate) async fn export( + &self, + dataset: &str, + query: &[(&str, String)], + accept: &str, + ) -> Result { + let mut url = self.url(&["exports", dataset]); + url.query_pairs_mut() + .extend_pairs(query.iter().map(|(key, value)| (*key, value.as_str()))); + self.read(url, accept).await + } + fn decode(&self, body: &[u8]) -> Result { serde_json::from_slice(body).map_err(|error| self.http.protocol(error.to_string())) } diff --git a/src/lib.rs b/src/lib.rs index 562870e..f4880be 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -32,6 +32,8 @@ use uuid::Uuid; use crate::api::{Api, ApiError, Http}; use crate::credentials::{Credential, Source}; +mod tools; + use crate::model::{ CodeAssessment, CommitReviewRequest, FileReviewRequest, OpenItems, PatchReviewRequest, ReviewDetail, ReviewSummary, @@ -70,6 +72,16 @@ pub struct Cli { #[derive(Debug, Subcommand)] enum Command { + /// Rerun the original immutable review subject. + Rerun(tools::RerunArgs), + /// List the recorded runs of a pull request. + History(tools::HistoryArgs), + /// Read the repository review guidance as JSON. + Guidance(RepositoryArgs), + /// Read a bounded, untrusted finding fix prompt as JSON. + FixPrompt { finding_id: Uuid }, + /// Export one page of analytics as CSV or NDJSON. + Export(tools::ExportArgs), /// Install the newest official release over this installer-managed binary. Update, #[command(name = "__update-check", hide = true)] @@ -358,6 +370,28 @@ pub async fn run(cli: Cli, token: Option) -> anyhow::Result { + let api = connect(Http::new(origin)?, token, cli.org).await?; + tools::rerun(&api, &args).await + } + Command::History(args) => { + let api = connect(Http::new(origin)?, token, cli.org).await?; + let name = repository_name(&args.repository).await?; + tools::json(&api.history(&name, args.pr).await?) + } + Command::Guidance(args) => { + let api = connect(Http::new(origin)?, token, cli.org).await?; + let (_, repository) = connected_repository(&api, &args).await?; + tools::json(&api.guidance(repository).await?) + } + Command::FixPrompt { finding_id } => { + let api = connect(Http::new(origin)?, token, cli.org).await?; + tools::json(&api.fix_prompt(finding_id).await?) + } + Command::Export(args) => { + let api = connect(Http::new(origin)?, token, cli.org).await?; + tools::export(&api, &args).await + } Command::Findings(args) => { if let Some(head) = &args.selector.head { git::commit_sha(head)?; diff --git a/src/tools.rs b/src/tools.rs new file mode 100644 index 0000000..8a5a9e0 --- /dev/null +++ b/src/tools.rs @@ -0,0 +1,167 @@ +//! Native operations on the existing token API. +use std::io::{IsTerminal as _, Write as _}; + +use anyhow::{Context as _, bail}; +use clap::{Args, ValueEnum}; +use uuid::Uuid; + +use crate::{OutputArgs, OutputFormat, RepositoryArgs, Verdict, api::Api, say, show}; + +#[derive(Debug, Args)] +pub(crate) struct RerunArgs { + review_id: Uuid, + /// Return the new review acknowledgment without polling. + #[arg(long)] + no_wait: bool, + #[command(flatten)] + output: OutputArgs, +} + +#[derive(Debug, Args)] +pub(crate) struct HistoryArgs { + #[arg(long)] + pub pr: u64, + #[command(flatten)] + pub repository: RepositoryArgs, +} + +#[derive(Debug, Clone, Copy, ValueEnum)] +enum Dataset { + Reviews, + #[value(name = "finding_outcomes")] + FindingOutcomes, + #[value(name = "finding_validations")] + FindingValidations, + Spend, + Findings, +} + +impl Dataset { + const fn name(self) -> &'static str { + match self { + Self::Reviews => "reviews", + Self::FindingOutcomes => "finding_outcomes", + Self::FindingValidations => "finding_validations", + Self::Spend => "spend", + Self::Findings => "findings", + } + } +} + +#[derive(Debug, Clone, Copy, ValueEnum)] +enum Format { + Csv, + Ndjson, +} + +#[derive(Debug, Args)] +pub(crate) struct ExportArgs { + #[arg(value_enum)] + dataset: Dataset, + /// Inclusive RFC3339 start of a window of at most 31 days. + #[arg(long)] + from: String, + /// Exclusive RFC3339 end of the window. + #[arg(long)] + to: String, + #[arg(long, value_enum, default_value = "ndjson")] + format: Format, + /// Opaque continuation from the preceding page; keep the same filters. + #[arg(long)] + cursor: Option, + /// Grouping for `finding_outcomes` only. + #[arg(long)] + group_by: Option, +} + +pub(crate) fn json(value: &serde_json::Value) -> anyhow::Result { + writeln!( + std::io::stdout().lock(), + "{}", + serde_json::to_string_pretty(value)? + )?; + Ok(Verdict::Done) +} + +pub(crate) async fn rerun(api: &Api, args: &RerunArgs) -> anyhow::Result { + let reply = api.rerun(args.review_id).await?; + let id: Uuid = reply + .get("review_id") + .and_then(serde_json::Value::as_str) + .context("the rerun response has no review_id")? + .parse()?; + if args.no_wait { + if args.output.json { + return json(&reply); + } + writeln!(std::io::stdout().lock(), "{}", api.review_url(id))?; + return Ok(Verdict::Done); + } + show( + api, + id, + true, + &args.output, + OutputFormat::from_json(args.output.json), + ) + .await +} + +pub(crate) async fn export(api: &Api, args: &ExportArgs) -> anyhow::Result { + if args.group_by.is_some() && !matches!(args.dataset, Dataset::FindingOutcomes) { + bail!("--group-by is available only for finding_outcomes"); + } + let (format, accept) = match args.format { + Format::Csv => ("csv", "text/csv"), + Format::Ndjson => ("ndjson", "application/x-ndjson"), + }; + let mut query = vec![ + ("from", args.from.clone()), + ("to", args.to.clone()), + ("format", format.to_owned()), + ]; + if let Some(cursor) = &args.cursor { + query.push(("cursor", cursor.clone())); + } + if let Some(group) = &args.group_by { + query.push(("group_by", group.clone())); + } + let reply = api.export(args.dataset.name(), &query, accept).await?; + let content_type = reply + .headers + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or_default(); + if content_type.split(';').next().map(str::trim) != Some(accept) + || reply + .headers + .get("x-proofline-export-version") + .and_then(|v| v.to_str().ok()) + != Some("1") + { + bail!("the server returned an unsupported export format or version"); + } + let horizon = reply + .headers + .get("x-proofline-export-settled-until") + .context("the export has no settled horizon")? + .to_str()?; + let body = std::str::from_utf8(&reply.body).context("the export is not UTF-8")?; + let stdout = std::io::stdout(); + if stdout.is_terminal() { + write!(stdout.lock(), "{}", crate::text::terminal_safe(body))?; + } else { + stdout.lock().write_all(&reply.body)?; + } + say(&format!( + "settled-until: {}", + crate::text::terminal_safe(horizon) + )); + if let Some(cursor) = reply.headers.get("x-proofline-export-next-cursor") { + say(&format!( + "next-cursor: {}", + crate::text::terminal_safe(cursor.to_str()?) + )); + } + Ok(Verdict::Done) +} diff --git a/src/update.rs b/src/update.rs index c544d58..1e283d6 100644 --- a/src/update.rs +++ b/src/update.rs @@ -108,7 +108,11 @@ pub fn on_invocation() { fn suggestion(cache: &Cache, args: &[std::ffi::OsString], interactive: bool) -> Option { if !interactive || args.iter().any(|arg| { - arg == "--json" + arg == "history" + || arg == "guidance" + || arg == "fix-prompt" + || arg == "export" + || arg == "--json" || arg == "--schema" || arg == "--sarif" || arg == "mcp" diff --git a/tests/http.rs b/tests/http.rs index 57d9800..e07b0a4 100644 --- a/tests/http.rs +++ b/tests/http.rs @@ -1729,3 +1729,100 @@ async fn ci_review_fail_on_exits_three_for_an_open_finding_of_a_complete_review( assert!(String::from_utf8_lossy(&output.stderr).contains("warning, serious")); assert!(requests.lock().unwrap().is_empty()); } + +#[tokio::test] +async fn native_tools_keep_tenant_paths_and_reruns_make_one_attempt() { + let requests = Arc::new(Mutex::new(Vec::new())); + let seen = Arc::clone(&requests); + let app = Router::new().fallback(move |request: axum::extract::Request| { + let seen = Arc::clone(&seen); + async move { + assert_eq!( + request.headers()[header::AUTHORIZATION], + format!("Bearer {TOKEN}") + ); + let path = request.uri().path().to_owned(); + assert!(path.starts_with(&format!("/api/v1/organizations/{ORG}/"))); + seen.lock() + .unwrap() + .push((request.method().clone(), path.clone())); + if path.ends_with("/rerun") { + return ( + StatusCode::SERVICE_UNAVAILABLE, + [(header::RETRY_AFTER, "0")], + Json(json!({"detail":"unavailable"})), + ) + .into_response(); + } + if path.ends_with("/exports/reviews") { + return ( + [ + ("content-type", "text/csv"), + ("x-proofline-export-version", "1"), + ("x-proofline-export-settled-until", "2026-10-25T00:00:00Z"), + ("x-proofline-export-next-cursor", "opaque-next"), + ], + "dataset_version,claim\r\n1,\"a,b\"\r\n", + ) + .into_response(); + } + if path.ends_with("repository-names") { + return Json( + json!({"repositories": [{"id": REPOSITORY, "full_name":"owner/repo"}]}), + ) + .into_response(); + } + Json(json!({"untrusted_text":"literal\u{001b}[2J", "items":[]})).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(); + }); + for args in [ + vec!["history", "--pr", "7", "--repo", "owner/repo"], + vec!["fix-prompt", SELECTED_REVIEW], + ] { + let output = cli(&origin, &args).await; + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + assert!(!output.stdout.contains(&27)); + } + let output = cli(&origin, &["rerun", SELECTED_REVIEW, "--no-wait"]).await; + assert_eq!(output.status.code(), Some(1)); + assert_eq!( + requests + .lock() + .unwrap() + .iter() + .filter(|(_, path)| path.ends_with("/rerun")) + .count(), + 1 + ); + let output = cli( + &origin, + &[ + "export", + "reviews", + "--from", + "2026-10-01T00:00:00Z", + "--to", + "2026-10-25T00:00:00Z", + "--format", + "csv", + ], + ) + .await; + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + assert_eq!(output.stdout, b"dataset_version,claim\r\n1,\"a,b\"\r\n"); + assert!(String::from_utf8_lossy(&output.stderr).contains("next-cursor: opaque-next")); + server.abort(); +}