Skip to content
Open
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
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@ To register MCP without a prompt, run `proofline agent install CLIENT --yes`. Su

Native knowledge, plan, fix and configuration commands send the selected organization as `organization_id` in each MCP tool call. With `PROOFLINE_TOKEN`, select an authorized UUID using `--org ORGANIZATION_ID` or `PROOFLINE_ORGANIZATION_ID`; the flag takes precedence. A stored device sign-in uses its approved organization and refuses a different selection. For example, `proofline --org ORGANIZATION_ID wiki list --repo owner/name` and `proofline --org ORGANIZATION_ID config get` target that organization with a shared MCP OAuth credential. Selection grants no authority: the server checks each call, and a foreign target returns its refusal with a nonzero exit. MCP OAuth credentials remain limited to MCP and cannot use REST commands. The raw `proofline mcp` bridge preserves the caller's messages and per-call target unchanged.

### Debug output

Pass `--debug`, or set `PROOFLINE_DEBUG=1`, to print each request the CLI makes to Proofline to standard error: its method and path, then its status, duration and size, or the error that ended it, and each retry with its wait. Update downloads are not included. The variable is off when empty or `0`, `false`, `no`, `off`, `n` or `f`, and on for any other value; it reaches Git hooks and the MCP bridge, which take no flags. Headers, request bodies and response bodies are never printed, so the output holds no token or code, but paths and query strings are, so a CI log keeps the organization ID and any search text. Standard output is unchanged, so `--json` stays parseable.

## Reviews, history, and reruns

`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.
Expand Down
63 changes: 58 additions & 5 deletions src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,16 @@
//! timeouts, no redirects, and bounded retries for reads.

use std::sync::Arc;
use std::time::Duration;
use std::time::{Duration, Instant};

use reqwest::{Method, StatusCode, header};
use secrecy::{ExposeSecret as _, SecretString};
use serde::Deserialize;
use serde::de::DeserializeOwned;
use url::Url;
use url::{Position, Url};
use uuid::Uuid;

use crate::debug;
use crate::github_actions::Renewal;
use crate::model::{
CommitDeployVerifications, CommitReviewRequest, CommitReviewResponse, CoverageUploadRequest,
Expand Down Expand Up @@ -223,8 +224,34 @@ impl Http {
&self,
request: reqwest::RequestBuilder,
) -> Result<(Reply, Option<u64>), ApiError> {
let response = request
.send()
let (client, request) = request.build_split();
let request = request.map_err(|error| self.transport(&error))?;
debug::log(format_args!(
"→ {} {}",
request.method(),
&request.url()[Position::BeforePath..]
));
let started = Instant::now();
let result = self.exchange(&client, request).await;
let elapsed = started.elapsed().as_millis();
match &result {
Ok((reply, _)) => debug::log(format_args!(
"← {} in {elapsed} ms ({} bytes)",
reply.status.as_u16(),
reply.body.len()
)),
Err(error) => debug::log(format_args!("← failed after {elapsed} ms: {error}")),
}
result
}

async fn exchange(
&self,
client: &reqwest::Client,
request: reqwest::Request,
) -> Result<(Reply, Option<u64>), ApiError> {
let response = client
.execute(request)
.await
.map_err(|error| self.transport(&error))?;
let status = response.status();
Expand Down Expand Up @@ -263,10 +290,32 @@ impl Http {
body: Vec<u8>,
protocol: Option<&str>,
notification: bool,
) -> Result<Vec<u8>, McpHttpError> {
let url = self.origin.join(["mcp"]);
debug::log(format_args!("→ POST {}", &url[Position::BeforePath..]));
let started = Instant::now();
let result = self
.mcp_exchange(url, token, body, protocol, notification)
.await;
let elapsed = started.elapsed().as_millis();
match &result {
Ok(body) => debug::log(format_args!("← ok in {elapsed} ms ({} bytes)", body.len())),
Err(error) => debug::log(format_args!("← failed after {elapsed} ms: {error}")),
}
result
}

async fn mcp_exchange(
&self,
url: Url,
token: &SecretString,
body: Vec<u8>,
protocol: Option<&str>,
notification: bool,
) -> Result<Vec<u8>, McpHttpError> {
let mut request = self
.client
.post(self.origin.join(["mcp"]))
.post(url)
.bearer_auth(token.expose_secret())
.header(header::CONTENT_TYPE, "application/json")
.header(header::ACCEPT, "application/json, text/event-stream")
Expand Down Expand Up @@ -436,6 +485,10 @@ impl Api {
if !retryable || attempt == READ_ATTEMPTS || wait > MAX_RETRY_AFTER {
return Err(self.http.problem(&reply));
}
debug::log(format_args!(
"retry {attempt} of {} in {wait} s",
READ_ATTEMPTS - 1
));
tokio::time::sleep(Duration::from_secs(wait)).await;
delay = (delay * 2).min(MAX_RETRY_AFTER);
}
Expand Down
22 changes: 22 additions & 0 deletions src/debug.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
use std::fmt::Arguments;
use std::io::Write as _;
use std::sync::atomic::{AtomicBool, Ordering};

use crate::text::one_line;

static ENABLED: AtomicBool = AtomicBool::new(false);

pub(crate) fn enable() {
ENABLED.store(true, Ordering::Relaxed);
}

pub(crate) fn log(line: Arguments<'_>) {
if !ENABLED.load(Ordering::Relaxed) {
return;
}
let _ = writeln!(
std::io::stderr().lock(),
"proofline debug: {}",
one_line(&line.to_string())
);
}
10 changes: 10 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ pub mod api;
mod config;
mod coverage;
pub mod credentials;
mod debug;
mod deploy;
pub mod device;
pub mod git;
Expand Down Expand Up @@ -80,6 +81,12 @@ pub struct Cli {
#[arg(long, global = true, env = "PROOFLINE_CA_CERT", value_name = "FILE")]
ca_cert: Option<PathBuf>,

/// Print each request to Proofline, its result and any retry to standard
/// error. Headers and bodies are never printed.
#[arg(long, global = true, env = "PROOFLINE_DEBUG",
value_parser = clap::builder::FalseyValueParser::new())]
debug: bool,

#[command(subcommand)]
command: Command,
}
Expand Down Expand Up @@ -419,6 +426,9 @@ pub enum Verdict {

/// Runs one command. `token` is `PROOFLINE_TOKEN`, read by the caller.
pub async fn run(cli: Cli, token: Option<SecretString>) -> anyhow::Result<Verdict> {
if cli.debug {
debug::enable();
}
if let Some(path) = &cli.ca_cert {
tls::trust(path)?;
}
Expand Down
59 changes: 59 additions & 0 deletions tests/debug.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
use std::net::TcpListener;
use std::process::Command;

const TOKEN: &str = "pld_secretsecretsecret";

fn stderr(flag: bool, env: Option<&str>) -> String {
let port = TcpListener::bind("127.0.0.1:0")
.unwrap()
.local_addr()
.unwrap()
.port();
let mut command = Command::new(env!("CARGO_BIN_EXE_proofline"));
command
.args(["--base-url", &format!("http://127.0.0.1:{port}"), "reviews"])
.env("PROOFLINE_NO_UPDATE_CHECK", "1")
.env("PROOFLINE_TOKEN", TOKEN)
.env(
"PROOFLINE_ORGANIZATION_ID",
"0190f3a0-0000-7000-8000-000000000001",
)
.env_remove("PROOFLINE_DEBUG");
if flag {
command.arg("--debug");
}
if let Some(value) = env {
command.env("PROOFLINE_DEBUG", value);
}
let output = command.output().unwrap();
assert!(!output.status.success());
String::from_utf8(output.stderr).unwrap()
}

#[test]
fn the_flag_or_a_truthy_variable_prints_each_request_without_the_token() {
for (flag, env) in [(true, None), (false, Some("1")), (false, Some("yes"))] {
let stderr = stderr(flag, env);
assert!(
stderr.contains("proofline debug: → GET /api/v1/organizations/"),
"{flag} {env:?}: {stderr}"
);
assert!(
stderr.contains("proofline debug: ← failed after"),
"{flag} {env:?}: {stderr}"
);
assert!(!stderr.contains(TOKEN), "{flag} {env:?}: {stderr}");
}
}

#[test]
fn no_flag_and_a_falsey_variable_print_nothing() {
for env in [None, Some(""), Some("0"), Some("false"), Some("off")] {
let stderr = stderr(false, env);
assert!(!stderr.contains("proofline debug"), "{env:?}: {stderr}");
assert!(
stderr.starts_with("proofline: could not reach"),
"{env:?}: {stderr}"
);
}
}