Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -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"
Expand Down
15 changes: 15 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
70 changes: 66 additions & 4 deletions src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<u8>,
}
Expand Down Expand Up @@ -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()
Expand All @@ -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
Expand Down Expand Up @@ -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<serde_json::Value, ApiError> {
async fn read(&self, url: Url, accept: &str) -> Result<Reply, ApiError> {
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,
Expand All @@ -355,6 +367,56 @@ impl Api {
.protocol("the retry budget ended without a response"))
}

async fn get(&self, url: Url) -> Result<serde_json::Value, ApiError> {
let reply = self.read(url, "application/json").await?;
self.decode(&reply.body)
}

pub(crate) async fn history(
&self,
repository: &str,
number: u64,
) -> Result<serde_json::Value, ApiError> {
self.get(self.url(&["reviews", "pr", repository, &number.to_string()]))
.await
}

pub(crate) async fn guidance(&self, repository: Uuid) -> Result<serde_json::Value, ApiError> {
self.get(self.url(&["repositories", &repository.to_string(), "review-guidance"]))
.await
}

pub(crate) async fn fix_prompt(&self, finding: Uuid) -> Result<serde_json::Value, ApiError> {
self.get(self.url(&["findings", &finding.to_string(), "fix-prompt"]))
.await
}

pub(crate) async fn rerun(&self, review: Uuid) -> Result<serde_json::Value, ApiError> {
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<Reply, ApiError> {
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<T: DeserializeOwned>(&self, body: &[u8]) -> Result<T, ApiError> {
serde_json::from_slice(body).map_err(|error| self.http.protocol(error.to_string()))
}
Expand Down
34 changes: 34 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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)]
Expand Down Expand Up @@ -358,6 +370,28 @@ pub async fn run(cli: Cli, token: Option<SecretString>) -> anyhow::Result<Verdic
}
Ok(Verdict::Done)
}
Command::Rerun(args) => {
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)?;
Expand Down
167 changes: 167 additions & 0 deletions src/tools.rs
Original file line number Diff line number Diff line change
@@ -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<String>,
/// Grouping for `finding_outcomes` only.
#[arg(long)]
group_by: Option<String>,
}

pub(crate) fn json(value: &serde_json::Value) -> anyhow::Result<Verdict> {
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<Verdict> {
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<Verdict> {
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)
}
6 changes: 5 additions & 1 deletion src/update.rs
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,11 @@ pub fn on_invocation() {
fn suggestion(cache: &Cache, args: &[std::ffi::OsString], interactive: bool) -> Option<String> {
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"
Expand Down
Loading
Loading