From 1ff110f14becc5371fdd4399c971716a64b5fae2 Mon Sep 17 00:00:00 2001 From: Sean Floyd Date: Thu, 5 Nov 2026 22:13:27 -0500 Subject: [PATCH 1/2] Link the console when a setting refuses a review A refused review request printed only the server's detail. A new organization whose repository had no linked environment read "link one from the repository's setup" with no way there; `proofline setup` opens the generic organization picker. The review-request operations answer such a refusal with RunNowRefused, whose `refusal` member exists for clients to link from. Problem dropped it. Keep its reason, and after the detail print the owner's console. - The detail already names the setting, so the CLI adds only where to change it: one link for every reason, including ones a newer server adds, with no per-reason text to drift from the server's. - Only a 400 carrying a readable reason gets the link. - The link is the `orgs/github/{owner}` route `setup` already builds, lowercased as setup's `console_url` addresses organizations. - The hook report is one line, so it joins the two with "; ". Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0131zPk6VGEqnVzoiizYQeh5 --- src/api.rs | 8 +++++ src/hooks.rs | 18 ++++++++--- src/lib.rs | 37 ++++++++++++++++++--- tests/http.rs | 90 ++++++++++++++++++++++++++++++++++++++++++++++++++- 4 files changed, 144 insertions(+), 9 deletions(-) diff --git a/src/api.rs b/src/api.rs index f908670..aceded4 100644 --- a/src/api.rs +++ b/src/api.rs @@ -32,6 +32,8 @@ pub enum ApiError { origin: String, status: u16, detail: String, + /// The `refusal.reason` of a review request that created nothing. + refusal: Option, }, #[error("could not reach {origin}: {reason}")] Transport { origin: String, reason: String }, @@ -119,6 +121,7 @@ impl ApiError { struct Problem { title: Option, detail: Option, + refusal: Option, } /// A response that arrived with an HTTP status, and its bounded body. @@ -269,6 +272,10 @@ impl Http { pub fn problem(&self, reply: &Reply) -> ApiError { let parsed = serde_json::from_slice::(&reply.body).ok(); + let refusal = parsed + .as_ref() + .and_then(|problem| problem.refusal.as_ref()?.get("reason")?.as_str()) + .map(str::to_owned); let detail = parsed .and_then(|problem| problem.detail.or(problem.title)) .map_or_else( @@ -285,6 +292,7 @@ impl Http { origin: self.origin.to_string(), status: reply.status.as_u16(), detail, + refusal, } } diff --git a/src/hooks.rs b/src/hooks.rs index 3c79631..8f8f4e8 100644 --- a/src/hooks.rs +++ b/src/hooks.rs @@ -22,7 +22,9 @@ use crate::outcome::{self, Outcome}; use crate::render::location; use crate::severity::Severity; use crate::text::one_line; -use crate::{RepositoryArgs, Verdict, connect, connected_repository, preflight, read_review, say}; +use crate::{ + RepositoryArgs, Verdict, connect, connected_repository, preflight, read_review, refused, say, +}; /// Identifies a script this CLI wrote. Uninstall removes a hook only when its /// whole text is the script this version writes, so an edited hook stays. @@ -485,14 +487,17 @@ async fn request( deadline: tokio::time::Instant, ) -> Report { let requested = async { - let (_, repository_id) = connected_repository(api, repository).await?; + let (name, repository_id) = connected_repository(api, repository).await?; let request = PatchReviewRequest { base_commit_sha: changes.base_commit_sha, patch: changes.patch, trigger_source: Some(hook.trigger_source()), verify_finding_ids: Vec::new(), }; - let requested = api.request_patch_review(repository_id, &request).await?; + let requested = api + .request_patch_review(repository_id, &request) + .await + .map_err(|error| refused(error, api.origin(), &name))?; let (_, detail, state) = read_review(api, requested.review_id, Some(deadline), false).await?; anyhow::Ok((requested.review_id, detail, state)) @@ -550,7 +555,12 @@ fn conclude( gap = true; say(&format!( "Proofline could not review {label}: {}", - one_line(reason) + reason + .lines() + .filter(|line| !line.trim().is_empty()) + .map(one_line) + .collect::>() + .join("; ") )); } Report::Read { diff --git a/src/lib.rs b/src/lib.rs index 6096711..979b741 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -707,6 +707,26 @@ async fn connected_repository(api: &Api, args: &RepositoryArgs) -> anyhow::Resul Ok((name, id)) } +/// Links the console after a review request that a setting refused; the +/// server's detail names the setting. +pub(crate) fn refused(error: ApiError, origin: &Origin, repository: &str) -> anyhow::Error { + if !matches!( + error, + ApiError::Problem { + status: 400, + refusal: Some(_), + .. + } + ) { + return error.into(); + } + let owner = repository + .split_once('/') + .map_or(repository, |(owner, _)| owner); + let console = origin.join(["orgs", "github", &owner.to_lowercase()]); + anyhow::anyhow!("{error}\nChange it at {console}") +} + /// A repository with reviews the token can read, for finding one of them. A /// repository that has since left the installation keeps its reviews, so this /// reads the review collection's repositories, not the connected ones. @@ -773,7 +793,7 @@ async fn review(api: &Api, args: &ReviewArgs) -> anyhow::Result { "this sign-in cannot request reviews; run `proofline login` and keep the reviews:request permission", )); } - Err(error) => return Err(error.into()), + Err(error) => return Err(refused(error, api.origin(), &name)), }; say(&format!( "{} review run {} of {name} #{}{}.", @@ -832,7 +852,10 @@ async fn review_local(api: &Api, args: &ReviewArgs) -> anyhow::Result { trigger_source: None, verify_finding_ids: args.verify.clone(), }; - let requested = api.request_patch_review(repository_id, &request).await?; + let requested = api + .request_patch_review(repository_id, &request) + .await + .map_err(|error| refused(error, api.origin(), &name))?; say(&format!( "{} review of {files} changed {} in {name} on {}.", if requested.existing { @@ -861,7 +884,10 @@ async fn review_files(api: &Api, args: &ReviewArgs) -> anyhow::Result { git::named_files(std::path::Path::new("."), revision, &args.files).await?; let (name, repository_id) = connected_repository(api, &args.repository).await?; let request = FileReviewRequest { commit_sha, paths }; - let requested = api.request_file_review(repository_id, &request).await?; + let requested = api + .request_file_review(repository_id, &request) + .await + .map_err(|error| refused(error, api.origin(), &name))?; say(&format!( "{} whole-file review of {} selected files in {name} at {}.", if requested.existing { @@ -890,7 +916,10 @@ async fn review_pushed(api: &Api, args: &ReviewArgs) -> anyhow::Result base_commit_sha: change.base_commit_sha, head_commit_sha: change.head_commit_sha, }; - let requested = api.request_commit_review(repository_id, &request).await?; + let requested = api + .request_commit_review(repository_id, &request) + .await + .map_err(|error| refused(error, api.origin(), &name))?; say(&format!( "{} review of {name} {}..{}.", if requested.existing { diff --git a/tests/http.rs b/tests/http.rs index b65ed37..c82cc15 100644 --- a/tests/http.rs +++ b/tests/http.rs @@ -664,11 +664,99 @@ async fn a_refused_review_request_names_the_reason_without_terminal_control() { org(), ); let error = api.request_review(Uuid::nil(), 7).await.unwrap_err(); - let ApiError::Problem { status, detail, .. } = &error else { + let ApiError::Problem { + status, + detail, + refusal, + .. + } = &error + else { panic!("expected a problem, got {error:?}"); }; assert_eq!(*status, 400); assert_eq!(detail, "No environment links acme/web.\u{FFFD}[2J"); + assert_eq!(refusal.as_deref(), Some("NO_LINKED_ENVIRONMENT")); +} + +/// A console that answers every pull-request review of `acme/web` with `status` and `body`. +async fn refusing(status: StatusCode, body: Value) -> String { + let app = Router::new() + .route( + &format!("/api/v1/organizations/{ORG}/repository-names"), + get(|| async { + Json(json!({ "repositories": [ + { "id": FIRST_REPOSITORY, "full_name": "acme/web" }, + ] })) + }), + ) + .route( + &format!( + "/api/v1/organizations/{ORG}/repositories/{FIRST_REPOSITORY}/pull-requests/7/review" + ), + post(move || async move { (status, Json(body)) }), + ); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + format!("http://{address}") +} + +async fn review_stderr(origin: &str, repository: &str) -> String { + let output = cli( + origin, + &["review", "--pr", "7", "--no-wait", "--repo", repository], + ) + .await; + assert!(!output.status.success()); + String::from_utf8(output.stderr).unwrap() +} + +#[tokio::test] +async fn a_refused_review_links_the_owners_console_after_the_servers_detail() { + let origin = refusing( + StatusCode::BAD_REQUEST, + json!({ + "title": "invalid request", + "status": 400, + "detail": "environment production is not ready", + "repository_name": "web", + "refusal": { "reason": "A_REASON_FROM_A_NEWER_SERVER" }, + }), + ) + .await; + assert_eq!( + review_stderr(&origin, "Acme/Web").await, + format!( + "proofline: {origin} returned HTTP 400: environment production is not ready\n\ + Change it at {origin}/orgs/github/acme\n" + ) + ); +} + +#[tokio::test] +async fn only_a_400_with_a_refusal_reason_links_the_console() { + for (status, refusal) in [ + (StatusCode::BAD_REQUEST, json!(null)), + (StatusCode::BAD_REQUEST, json!({ "reason": 5 })), + ( + StatusCode::CONFLICT, + json!({ "reason": "NO_LINKED_ENVIRONMENT" }), + ), + ] { + let origin = refusing( + status, + json!({ "title": "invalid request", "status": status.as_u16(), "detail": "refused", "refusal": refusal }), + ) + .await; + assert_eq!( + review_stderr(&origin, "acme/web").await, + format!( + "proofline: {origin} returned HTTP {}: refused\n", + status.as_u16() + ), + "{status} {refusal}" + ); + } } #[tokio::test] From 0cc2aa88e6905ae282e771b37b7e6ab11784c2a6 Mon Sep 17 00:00:00 2001 From: Sean Floyd Date: Fri, 6 Nov 2026 00:55:14 -0500 Subject: [PATCH 2/2] Show whether this checkout can be reviewed `proofline status` showed the organization and token but not whether a review would run. A new organization learned that only from a refused request. After the token check, status reads whether the checkout's repository is connected and what setup says, then prints `reviewable` and the next step. `--json` prints the same for agents. - Setup comes from the MCP `get_setup_status` tool, the only source; it needs `setup:write`, and without it status says it cannot tell. - Reviewable means `configuration_complete` and a ready configured environment that links the repository: the console starts reviews on the first, and the refusals NO_LINKED_ENVIRONMENT and ENVIRONMENT_NOT_READY name the second. `activation_complete` is not it; the console sets it after the first review. Open blockers are the reason, shown as the server wrote them. - The environment fields `repository_ids` and `ready` are read as the console reads them; no contract names them, so a missing one is cannot tell, not no. - `reviewable` is null when no answer was read: the server did not answer in time, or its answer was unreadable. `false` is a confirmed answer. - The sign-in hint repeats the token's scopes, because `login --scope` replaces them. - The exit code still reflects only the token, so scripts that use status as a token check keep working. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0131zPk6VGEqnVzoiizYQeh5 --- README.md | 7 + src/lib.rs | 344 +++++++++++++++++++++++++++++++++++++++++------- tests/status.rs | 215 ++++++++++++++++++++++++++++++ 3 files changed, 522 insertions(+), 44 deletions(-) create mode 100644 tests/status.rs diff --git a/README.md b/README.md index 25b8097..619887e 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,13 @@ the index, or `--include-untracked` to select a new, non-ignored file. The command preserves the real index and applies the usual secret preflight. It cannot be combined with pushed-commit, range or pull-request review. +`proofline status` also says whether `proofline review` can run in this +checkout: the repository is connected, setup is finished, and a ready +environment links the repository. Open setup blockers are the reason when it +cannot. Setup needs `setup:write`; without it, status says it cannot tell. +`--json` prints the same report for agents. The exit code still reflects only +the token. + 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`. diff --git a/src/lib.rs b/src/lib.rs index 979b741..5cdc1c1 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -125,8 +125,9 @@ enum Command { Login(LoginArgs), /// Remove the stored token from the OS keychain. Logout, - /// Show which organization and token the CLI uses. - Status, + /// Show which organization and token the CLI uses, and whether this + /// checkout can be reviewed. + Status(StatusArgs), /// Review the checkout's local changes, pushed commits, or an open pull /// request's current head. Review(ReviewArgs), @@ -206,6 +207,15 @@ struct RepositoryArgs { remote: String, } +#[derive(Debug, Args)] +struct StatusArgs { + /// Print JSON instead of text. + #[arg(long)] + json: bool, + #[command(flatten)] + repository: RepositoryArgs, +} + #[derive(Debug, Args)] struct OutputArgs { /// Print JSON instead of text. @@ -458,7 +468,7 @@ pub async fn run(cli: Cli, token: Option) -> anyhow::Result logout(&origin, token.is_some()) .await .map(|()| Verdict::Done), - Command::Status => status(Http::new(origin)?, token, cli.org) + Command::Status(args) => status(Http::new(origin)?, token, cli.org, &args) .await .map(|()| Verdict::Done), Command::Review(args) => { @@ -619,51 +629,280 @@ async fn logout(origin: &Origin, environment: bool) -> anyhow::Result<()> { Ok(()) } -async fn status(http: Http, token: Option, org: Option) -> anyhow::Result<()> { +/// What `status` found. `reviewable` is `None` when the CLI cannot tell. +#[derive(Debug, Default, serde::Serialize)] +struct Status { + console: String, + organization_id: Option, + token: Option<&'static str>, + scopes: Option>, + expires_at: Option, + server: Option, + repository: Option, + /// Why setup could not be read. + setup: Option, + /// The server's `configuration_complete`: setup was finished. + setup_finished: Option, + /// The server's configured environments that link this repository. + environments: Vec, + blockers: Vec, + reviewable: Option, + next: Option, +} + +impl Status { + fn refuse(&mut self, next: String) { + self.reviewable = Some(false); + self.next = Some(next); + } + + fn unknown(&mut self, next: String) { + self.reviewable = None; + self.next = Some(next); + } + + fn print(&self, json: bool) -> anyhow::Result<()> { + let mut stdout = std::io::stdout().lock(); + if json { + writeln!(stdout, "{}", serde_json::to_string_pretty(self)?)?; + } else { + writeln!(stdout, "{}", self.lines().join("\n"))?; + } + Ok(()) + } + + fn lines(&self) -> Vec { + let mut lines = vec![format!("console: {}", self.console)]; + if let Some(organization_id) = self.organization_id { + lines.push(format!("organization: {organization_id}")); + } + if let Some(token) = self.token { + lines.push(format!("token: {token}")); + } + if let Some(scopes) = &self.scopes { + lines.push(format!("scopes: {}", text::one_line(&scopes.join(" ")))); + } + if let Some(expires_at) = self.expires_at { + let left = expires_at.saturating_sub(device::now()); + lines.push(if left == 0 { + "expires: expired; run `proofline login`".to_owned() + } else { + format!("expires: in {} hours", left.div_ceil(3600)) + }); + } + if let Some(server) = &self.server { + lines.push(format!("server: {}", text::one_line(server))); + } + if let Some(repository) = &self.repository { + lines.push(format!("repository: {repository} is connected")); + } + if let Some(setup) = &self.setup { + lines.push(format!("setup: cannot tell: {}", text::one_line(setup))); + } + match self.setup_finished { + Some(true) => lines.push("setup: finished".to_owned()), + Some(false) => lines.push("setup: not finished".to_owned()), + None => {} + } + for environment in &self.environments { + lines.push(format!( + "environment: {} {}", + text::one_line(environment["display_name"].as_str().unwrap_or("unnamed")), + if environment["ready"] == true { + "is ready" + } else { + "is not ready" + } + )); + } + if self.setup_finished.is_some() && self.environments.is_empty() { + lines.push("environment: none links this repository".to_owned()); + } + for blocker in &self.blockers { + let detail = blocker["detail"].as_str().unwrap_or("blocked"); + lines.push(format!("setup: {}", text::one_line(detail))); + } + lines.push(format!( + "reviewable: {}", + match self.reviewable { + Some(true) => "yes", + Some(false) => "no", + None => "cannot tell", + } + )); + if let Some(next) = &self.next { + lines.push(format!("next: {}", text::one_line(next))); + } + lines + } +} + +async fn status( + http: Http, + token: Option, + org: Option, + args: &StatusArgs, +) -> anyhow::Result<()> { + let mut status = Status { + console: http.origin().to_string(), + ..Status::default() + }; + let credential = match credentials::load(http.origin(), token, org).await { + Ok(credential) => credential, + Err(error) => { + status.refuse(error.to_string()); + status.print(args.json)?; + return Err(error.into()); + } + }; let Credential { token, organization_id, scope, expires_at, source, - } = credentials::load(http.origin(), token, org).await?; - let origin = http.origin().clone(); - let mut lines = vec![ - format!("console: {origin}"), - format!("organization: {organization_id}"), - format!( - "token: {}", - match source { - Source::Environment => "PROOFLINE_TOKEN", - Source::Keychain => "OS keychain", - } - ), - ]; - if let Some(scope) = scope { - lines.push(format!("scopes: {}", text::one_line(&scope))); - } - if let Some(expires_at) = expires_at { - let left = expires_at.saturating_sub(device::now()); - lines.push(if left == 0 { - "expires: expired; run `proofline login`".to_owned() - } else { - format!("expires: in {} hours", left.div_ceil(3600)) - }); - } - let api = Api::new(http, token, organization_id); + } = credential; + status.organization_id = Some(organization_id); + status.token = Some(match source { + Source::Environment => "PROOFLINE_TOKEN", + Source::Keychain => "OS keychain", + }); + status.scopes = scope + .as_deref() + .map(|scope| scope.split_whitespace().map(str::to_owned).collect()); + status.expires_at = expires_at; + let api = Api::new(http.clone(), token.clone(), organization_id); let result = api.reviews(None, None, None).await; - lines.push(match &result { - Ok(_) => "server: accepted the token".to_owned(), + match &result { + Ok(_) => { + status.server = Some("accepted the token".to_owned()); + readiness(&mut status, &api, &http, &token, &args.repository).await; + } Err(error) if error.status() == Some(401) => { - "server: the token is expired, revoked or malformed; run `proofline login`".to_owned() + status.server = Some( + "the token is expired, revoked or malformed; run `proofline login`".to_owned(), + ); + status.refuse("run `proofline login`".to_owned()); } - Err(error) => format!("server: {error}"), - }); - writeln!(std::io::stdout().lock(), "{}", lines.join("\n"))?; + Err(error) => { + status.server = Some(error.to_string()); + if unread(error) { + status.unknown(error.to_string()); + } else { + status.refuse(error.to_string()); + } + } + } + status.print(args.json)?; result?; Ok(()) } +/// Whether the CLI has no answer to read: the server did not answer in time, +/// or its answer could not be read. +const fn unread(error: &ApiError) -> bool { + matches!( + error, + ApiError::Protocol { .. } + | ApiError::Problem { + status: 408 | 429, + .. + } + ) || unanswered(error) +} + +/// Whether `proofline review` can run here: the repository is connected, setup +/// is finished, and a ready environment links the repository. Setup is +/// readable only through the MCP setup tool. +async fn readiness( + status: &mut Status, + api: &Api, + http: &Http, + token: &SecretString, + repository: &RepositoryArgs, +) { + let (name, id) = match connected_repository(api, repository).await { + Ok(found) => found, + // No answer was read, so the repository may still be connected. + Err(error) if error.downcast_ref::().is_some_and(unread) => { + return status.unknown(format!("{error:#}")); + } + Err(error) => return status.refuse(format!("{error:#}")), + }; + let console = console(api.origin(), &name).to_string(); + status.repository = Some(name); + if let Some(scopes) = status + .scopes + .as_ref() + .filter(|scopes| !scopes.iter().any(|scope| scope == "setup:write")) + { + status.setup = Some("the token lacks the setup:write scope".to_owned()); + status.next = Some(login_adding(scopes, "setup:write")); + return; + } + let arguments = serde_json::json!({ "organization_id": api.organization_id() }); + let data = match mcp::call(http, token, "get_setup_status", arguments).await { + Ok(result) if result["isError"] != true => result["structuredContent"]["data"].clone(), + Ok(result) => { + let reason = result["content"][0]["text"].as_str().unwrap_or("refused"); + status.setup = Some(reason.to_owned()); + return status.unknown(format!("check setup at {console}")); + } + Err(error) => { + status.setup = Some(error.to_string()); + return status.unknown(format!("check setup at {console}")); + } + }; + // An environment's fields are read as the console reads them. + let id = id.to_string(); + let environments = data["configured_environment_states"] + .as_array() + .and_then(|all| { + all.iter() + .map(|environment| { + let ids = environment["repository_ids"].as_array()?; + environment["ready"].as_bool()?; + Some( + ids.iter() + .any(|linked| linked == id.as_str()) + .then_some(environment), + ) + }) + .collect::>>() + }); + let (Some(finished), Some(environments)) = + (data["configuration_complete"].as_bool(), environments) + else { + status.setup = Some("the server's setup status is incomplete".to_owned()); + return status.unknown(format!("check setup at {console}")); + }; + status.setup_finished = Some(finished); + status.environments = environments.into_iter().flatten().cloned().collect(); + status.blockers = data["blockers"].as_array().cloned().unwrap_or_default(); + let reviewable = finished + && status + .environments + .iter() + .any(|environment| environment["ready"] == true); + status.reviewable = Some(reviewable); + if !reviewable { + let console = data["console_url"].as_str().unwrap_or(&console); + status.next = Some(format!("finish setup at {console}")); + } +} + +/// The sign-in that adds `scope`. `login --scope` replaces the scopes, so it +/// repeats the ones the token has. +fn login_adding(scopes: &[String], scope: &str) -> String { + let flags: Vec = scopes + .iter() + .map(String::as_str) + .chain([scope]) + .map(|scope| format!("--scope {scope}")) + .collect(); + format!("run `proofline login {}`", flags.join(" ")) +} + async fn repository_name(args: &RepositoryArgs) -> anyhow::Result { match &args.repo { Some(name) => Ok(name.clone()), @@ -720,11 +959,17 @@ pub(crate) fn refused(error: ApiError, origin: &Origin, repository: &str) -> any ) { return error.into(); } + let console = console(origin, repository); + anyhow::anyhow!("{error}\nChange it at {console}") +} + +/// The console of the organization that owns `owner/name`, addressed in +/// lowercase as `setup` addresses it. +fn console(origin: &Origin, repository: &str) -> url::Url { let owner = repository .split_once('/') .map_or(repository, |(owner, _)| owner); - let console = origin.join(["orgs", "github", &owner.to_lowercase()]); - anyhow::anyhow!("{error}\nChange it at {console}") + origin.join(["orgs", "github", &owner.to_lowercase()]) } /// A repository with reviews the token can read, for finding one of them. A @@ -1095,13 +1340,15 @@ fn ci_commit(flag: Option<&str>) -> anyhow::Result { /// Whether a failure is Proofline's rather than the caller's: the console /// could not be reached or failed on its side. fn unavailable(error: &anyhow::Error) -> bool { - error - .downcast_ref::() - .is_some_and(|error| match error { - ApiError::Transport { .. } => true, - ApiError::Problem { status, .. } => *status >= 500, - ApiError::Protocol { .. } => false, - }) + error.downcast_ref::().is_some_and(unanswered) +} + +const fn unanswered(error: &ApiError) -> bool { + match error { + ApiError::Transport { .. } => true, + ApiError::Problem { status, .. } => *status >= 500, + ApiError::Protocol { .. } => false, + } } /// `ci review` once its inputs are read. In GitHub Actions without @@ -1573,4 +1820,13 @@ mod tests { Verdict::NotComplete ); } + + #[test] + fn a_scope_hint_keeps_the_scopes_the_token_has() { + let held = ["reviews:read".to_owned(), "reviews:request".to_owned()]; + assert_eq!( + login_adding(&held, "setup:write"), + "run `proofline login --scope reviews:read --scope reviews:request --scope setup:write`" + ); + } } diff --git a/tests/status.rs b/tests/status.rs new file mode 100644 index 0000000..cd2eb9f --- /dev/null +++ b/tests/status.rs @@ -0,0 +1,215 @@ +//! `proofline status --json` against a loopback stand-in for the console. + +use axum::http::StatusCode; +use axum::response::IntoResponse; +use axum::routing::{get, post}; +use axum::{Json, Router}; +use serde_json::{Value, json}; + +const ORG: &str = "0190f3a0-0000-7000-8000-000000000001"; +const TOKEN: &str = "pld_secretsecretsecret"; +const WEB: &str = "0190f3a0-0000-7000-8000-000000000022"; +const API: &str = "0190f3a0-0000-7000-8000-000000000023"; + +/// A console with acme/web connected that answers the token check with +/// `reviews`, the repository list with `names` and the setup tool with `setup`. +async fn console(reviews: StatusCode, names: (StatusCode, Value), setup: Value) -> String { + let app = Router::new() + .route( + &format!("/api/v1/organizations/{ORG}/reviews"), + get(move || async move { + let body = json!({ + "items": [], "next_cursor": null, "truncated": false, + "filters": { "repositories": [] }, + }); + (reviews, Json(body)) + }), + ) + .route( + &format!("/api/v1/organizations/{ORG}/repository-names"), + get(move || async move { (names.0, Json(names.1)) }), + ) + .route( + "/mcp", + post(move |Json(body): Json| { + let setup = setup.clone(); + async move { + match body["method"].as_str() { + Some("initialize") => Json(json!({ + "jsonrpc": "2.0", "id": 1, + "result": { "protocolVersion": "2025-11-25" }, + })) + .into_response(), + Some("notifications/initialized") => StatusCode::ACCEPTED.into_response(), + _ => { + assert_eq!(body["params"]["name"], "get_setup_status"); + assert_eq!(body["params"]["arguments"]["organization_id"], ORG); + Json(json!({ "jsonrpc": "2.0", "id": 2, "result": setup })) + .into_response() + } + } + } + }), + ); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let origin = format!("http://{}", listener.local_addr().unwrap()); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + origin +} + +/// A `get_setup_status` result carrying `data`, shaped as the live tool's. +fn setup(data: Value) -> Value { + json!({ + "isError": false, + "content": [{ "type": "text", "text": data.to_string() }], + "structuredContent": { "ok": true, "data": data }, + }) +} + +fn environment(repository: &str, ready: bool) -> Value { + json!({ "display_name": "production", "repository_ids": [repository], "ready": ready }) +} + +async fn status(origin: &str, args: &[&str]) -> (Option, Value) { + let directory = tempfile::tempdir().unwrap(); + let output = tokio::time::timeout( + std::time::Duration::from_secs(15), + tokio::process::Command::new(env!("CARGO_BIN_EXE_proofline")) + .args(["--base-url", origin, "status", "--json"]) + .args(args) + .env("PROOFLINE_TOKEN", TOKEN) + .env("PATH", "") + .current_dir(directory.path()) + .kill_on_drop(true) + .output(), + ) + .await + .unwrap() + .unwrap(); + let report = serde_json::from_slice(&output.stdout).unwrap(); + (output.status.code(), report) +} + +/// A review runs only after setup is finished, through a ready environment +/// that links this repository. Open blockers alone never decide it. +#[tokio::test] +async fn reviewable_needs_finished_setup_and_a_ready_linked_environment() { + let blocker = + json!({ "code": "DRAFT_UNCONFIRMED", "detail": "Confirm the production environment." }); + let server = "https://console.example/orgs/github/acme"; + for (finished, environment, blockers, console, reviewable) in [ + // Unfinished setup with nothing open is still not reviewable. + ( + false, + environment(WEB, true), + json!([]), + Some(server), + false, + ), + (false, environment(WEB, true), json!([blocker]), None, false), + (true, environment(API, true), json!([]), None, false), + (true, environment(WEB, false), json!([]), None, false), + (true, environment(WEB, true), json!([]), None, true), + ] { + let mut data = json!({ + "configuration_complete": finished, + "configured_environment_states": [environment], + "blockers": blockers, + }); + if let Some(console) = console { + data["console_url"] = json!(console); + } + let origin = console_for(setup(data)).await; + let (code, report) = status(&origin, &["--org", ORG, "--repo", "Acme/Web"]).await; + assert_eq!(code, Some(0), "{report}"); + assert_eq!(report["reviewable"], reviewable, "{report}"); + assert_eq!(report["blockers"], blockers, "{report}"); + let next = console.map_or_else(|| format!("{origin}/orgs/github/acme"), str::to_owned); + let next = (!reviewable).then(|| format!("finish setup at {next}")); + assert_eq!(report["next"], json!(next), "{report}"); + } +} + +/// A setup status the CLI cannot read never becomes a verdict either way. +#[tokio::test] +async fn an_unreadable_setup_cannot_tell() { + let refused = json!({ + "isError": true, + "content": [{ "type": "text", "text": "setup:write is required" }], + }); + let incomplete = setup(json!({ "blockers": [] })); + // The environment fields come from the console's own reads, not a contract. + let renamed = setup(json!({ + "configuration_complete": true, + "configured_environment_states": [{ "repositories": [WEB], "is_ready": true }], + })); + for result in [refused, incomplete, renamed] { + let origin = console_for(result).await; + let (code, report) = status(&origin, &["--org", ORG, "--repo", "acme/web"]).await; + assert_eq!(code, Some(0), "{report}"); + assert_eq!(report["reviewable"], Value::Null, "{report}"); + assert_eq!( + report["next"], + format!("check setup at {origin}/orgs/github/acme") + ); + } +} + +/// `false` is kept for a confirmed answer; a server that did not answer says +/// nothing about the repository. +#[tokio::test] +async fn only_a_confirmed_answer_is_unreviewable() { + let (ok, forbidden, unavailable) = ( + StatusCode::OK, + StatusCode::FORBIDDEN, + StatusCode::SERVICE_UNAVAILABLE, + ); + for (reviews, names, repository, reviewable) in [ + (unavailable, (ok, connected()), "acme/web", Value::Null), + ( + StatusCode::REQUEST_TIMEOUT, + (ok, connected()), + "acme/web", + Value::Null, + ), + (forbidden, (ok, connected()), "acme/web", json!(false)), + (ok, (unavailable, connected()), "acme/web", Value::Null), + (ok, (forbidden, connected()), "acme/web", json!(false)), + // A list that is not the contract's: no answer was read. + ( + ok, + (ok, json!({ "repositories": 5 })), + "acme/web", + Value::Null, + ), + (ok, (ok, connected()), "acme/other", json!(false)), + ] { + let origin = console(reviews, names, setup(json!({}))).await; + let (_, report) = status(&origin, &["--org", ORG, "--repo", repository]).await; + assert_eq!(report["reviewable"], reviewable, "{report}"); + assert!(report["next"].is_string(), "{report}"); + } +} + +/// An agent reads the same fields when the CLI is not signed in. +#[tokio::test] +async fn without_a_sign_in_the_report_keeps_its_fields() { + let origin = console_for(setup(json!({}))).await; + let (code, report) = status(&origin, &["--repo", "acme/web"]).await; + assert_eq!(code, Some(1), "{report}"); + assert_eq!(report["console"], origin); + assert_eq!(report["organization_id"], Value::Null); + assert_eq!(report["reviewable"], false); + assert!( + report["next"].as_str().unwrap().contains("--org"), + "{report}" + ); +} + +async fn console_for(setup: Value) -> String { + console(StatusCode::OK, (StatusCode::OK, connected()), setup).await +} + +fn connected() -> Value { + json!({ "repositories": [{ "id": WEB, "full_name": "acme/web" }] }) +}