diff --git a/README.md b/README.md index 18c4903..ad05e36 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/src/api.rs b/src/api.rs index d2d69e7..951d00d 100644 --- a/src/api.rs +++ b/src/api.rs @@ -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, @@ -223,8 +224,34 @@ impl Http { &self, request: reqwest::RequestBuilder, ) -> Result<(Reply, Option), 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), ApiError> { + let response = client + .execute(request) .await .map_err(|error| self.transport(&error))?; let status = response.status(); @@ -263,10 +290,32 @@ impl Http { body: Vec, protocol: Option<&str>, notification: bool, + ) -> Result, 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, + protocol: Option<&str>, + notification: bool, ) -> Result, 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") @@ -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); } diff --git a/src/debug.rs b/src/debug.rs new file mode 100644 index 0000000..d1fd984 --- /dev/null +++ b/src/debug.rs @@ -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()) + ); +} diff --git a/src/lib.rs b/src/lib.rs index bcffa71..354a31c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -8,6 +8,7 @@ pub mod api; mod config; mod coverage; pub mod credentials; +mod debug; mod deploy; pub mod device; pub mod git; @@ -80,6 +81,12 @@ pub struct Cli { #[arg(long, global = true, env = "PROOFLINE_CA_CERT", value_name = "FILE")] ca_cert: Option, + /// 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, } @@ -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) -> anyhow::Result { + if cli.debug { + debug::enable(); + } if let Some(path) = &cli.ca_cert { tls::trust(path)?; } diff --git a/tests/debug.rs b/tests/debug.rs new file mode 100644 index 0000000..bf270b2 --- /dev/null +++ b/tests/debug.rs @@ -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}" + ); + } +}