From 75c3a3f15823c0c16a595a569a33c7e92fe68421 Mon Sep 17 00:00:00 2001 From: akacolf Date: Wed, 18 Nov 2026 16:10:01 +0300 Subject: [PATCH 1/2] feat: add proofline finding command --- build.rs | 1 + src/api.rs | 18 +++- src/lib.rs | 24 +++++ src/model.rs | 97 +++++++++++++++++++ src/render.rs | 230 +++++++++++++++++++++++++++++++++++++++++++++- tests/contract.rs | 16 +++- tests/http.rs | 115 +++++++++++++++++++++++ 7 files changed, 492 insertions(+), 9 deletions(-) diff --git a/build.rs b/build.rs index fdb1a6f..be9241f 100644 --- a/build.rs +++ b/build.rs @@ -12,6 +12,7 @@ const OPERATIONS: &[(&str, &str, &[&str])] = &[ ("get", "export_reviews", &["dataset"]), ("get", "get_agent_session", &["session_id"]), ("get", "get_agent_session_prompt", &["finding_id"]), + ("get", "get_finding", &["finding_id"]), ("get", "get_finding_fix_prompt", &["finding_id"]), ( "get", diff --git a/src/api.rs b/src/api.rs index 3a78004..e4b2a00 100644 --- a/src/api.rs +++ b/src/api.rs @@ -12,9 +12,9 @@ use uuid::Uuid; use crate::model::{ CommitReviewRequest, CommitReviewResponse, CoverageUploadRequest, CoverageUploadResponse, - FileReviewRequest, FileReviewResponse, PatchReviewRequest, PatchReviewResponse, - RepositoryNames, ReviewDetail, ReviewPage, RunNowMode, RunNowRequest, RunNowResponse, - ScanRequest, ScanResponse, StopResponse, + CustomerFinding, FileReviewRequest, FileReviewResponse, PatchReviewRequest, + PatchReviewResponse, RepositoryNames, ReviewDetail, ReviewPage, RunNowMode, RunNowRequest, + RunNowResponse, ScanRequest, ScanResponse, StopResponse, }; use crate::origin::Origin; use crate::text::terminal_safe; @@ -502,6 +502,18 @@ impl Api { Ok((raw, typed)) } + /// Fetches one finding as the raw document and its typed reading. + pub async fn finding( + &self, + finding_id: Uuid, + ) -> Result<(serde_json::Value, CustomerFinding), ApiError> { + let id = finding_id.to_string(); + let raw = self.get(self.url_get_finding(&id)).await?; + let typed = serde_json::from_value(raw.clone()) + .map_err(|error| self.http.protocol(error.to_string()))?; + Ok((raw, typed)) + } + /// One page of the review collection, newest first. pub async fn reviews( &self, diff --git a/src/lib.rs b/src/lib.rs index 6273dcc..4f90dc6 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -160,6 +160,8 @@ enum Command { Stop(StopArgs), /// Show the findings of the latest review of a commit or pull request. Findings(FindingsArgs), + /// Read one finding with its evidence references, validation state, and causal graph. + Finding(FindingArgs), /// Forward a coding agent's stdio messages to this console's MCP server. Mcp, /// Commands for a CI job. @@ -216,6 +218,15 @@ struct CiReviewArgs { repository: RepositoryArgs, } +#[derive(Debug, Args)] +struct FindingArgs { + /// Finding UUID. + finding_id: Uuid, + /// Print JSON instead of text. + #[arg(long)] + json: bool, +} + #[derive(Debug, Args)] struct LoginArgs { /// Review API scope to ask for; repeat for several. The approval page can @@ -554,6 +565,19 @@ pub async fn run(cli: Cli, token: Option) -> anyhow::Result { + let api = connect(Http::new(origin)?, token, cli.org).await?; + let (raw, typed) = api.finding(args.finding_id).await?; + if args.json { + return tools::json(&raw); + } + write!( + std::io::stdout().lock(), + "{}", + render::finding_detail(&typed) + )?; + Ok(Verdict::Done) + } Command::Mcp => { let http = Http::new(origin)?; let credential = credentials::load(http.origin(), token, cli.org).await?; diff --git a/src/model.rs b/src/model.rs index 283fb67..385ff20 100644 --- a/src/model.rs +++ b/src/model.rs @@ -248,6 +248,103 @@ pub struct EvidenceRef { pub companion_repository: Option, } +/// Full finding detail returned by `GET /findings/{finding_id}`. +#[derive(Debug, Deserialize, Serialize)] +pub struct CustomerFinding { + pub id: Uuid, + pub finding_fingerprint: Option, + pub severity: String, + pub risk_domain: String, + pub claim: String, + pub impact: String, + pub symbols: Vec, + pub lifecycle_state: String, + pub remediation: Option, + pub evidence_class: Option, + pub evidence_refs: Vec, + pub causal_graph: Option, + pub supporting_evidence: Option, + pub latest_validation: Option, + pub validation: Option, + pub github_comment_url: Option, + pub rule_refs: Vec, + pub comment_reactions: Vec, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub local_findings: Vec, + pub placement: Option, + pub comment_evaluation: Option, + pub thread_observation: Option, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct CustomerEvidenceRef { + pub kind: String, + pub label: String, + pub provenance_status: String, + pub repository_path: Option, + pub start_line: Option, + pub end_line: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub file_sha256: Option, + pub commit_sha: Option, + pub companion_repository: Option, + pub url: Option, + pub workflow_run_id: Option, + pub workflow_attempt: Option, + pub legacy_text: Option, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct CustomerFindingValidation { + pub validation: String, + pub source: String, + pub recorded_at: String, + pub actor_github_user_id: Option, + pub actor_login: Option, + pub actor_name: Option, + pub covering_author_kind: Option, + pub covering_author_login: Option, + pub covering_comment_created_at: Option, + pub github_comment_url: Option, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct FindingCausalGraphView { + pub nodes: Vec, + pub edges: Vec, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct FindingCausalNodeView { + pub id: String, + pub label: String, + pub role: String, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct FindingCausalEdgeView { + pub from: String, + pub to: String, + pub label: Option, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct FindingRuleRefView { + pub key: String, + pub revisions: Vec, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct FindingSupport { + pub explanation: Option, + pub evidence_refs: Vec, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct UntrustedText { + pub untrusted_text: String, +} + #[derive(Debug, Deserialize, Serialize)] pub struct RunNowResponse { pub review_id: Uuid, diff --git a/src/render.rs b/src/render.rs index 93bf758..0456c0d 100644 --- a/src/render.rs +++ b/src/render.rs @@ -5,7 +5,10 @@ use std::cmp::Reverse; use url::Url; -use crate::model::{Assessment, CodeAssessment, Finding, LocalReverification, ReviewDetail}; +use crate::model::{ + Assessment, CodeAssessment, CustomerEvidenceRef, CustomerFinding, Finding, LocalReverification, + ReviewDetail, +}; use crate::outcome::{self, Outcome}; use crate::severity::Severity; use crate::text::{one_line, terminal_safe}; @@ -196,6 +199,132 @@ pub fn review(review: &ReviewDetail, state: Option, url: &Url) -> Strin out.join("\n") } +fn format_evidence_ref(evidence: &CustomerEvidenceRef) -> String { + let place = evidence + .repository_path + .as_deref() + .map(one_line) + .map(|path| match (evidence.start_line, evidence.end_line) { + (Some(start), Some(end)) if end > start => format!("{path}:{start}-{end}"), + (Some(start), _) => format!("{path}:{start}"), + (None, _) => path, + }); + let mut parts = vec![format!( + "[{}] {} ({})", + one_line(&evidence.kind), + one_line(&evidence.label), + one_line(&evidence.provenance_status) + )]; + if let Some(place) = place { + parts.push(format!("at {place}")); + } + if let Some(url) = &evidence.url { + parts.push(one_line(url)); + } + parts.join(" ") +} + +/// Renders one `CustomerFinding` for terminal output, keeping all model- or +/// repository-derived strings terminal-safe. +pub fn finding_detail(finding: &CustomerFinding) -> String { + let mut out = vec![ + format!( + "{:<8} {} [{}]", + one_line(&finding.severity), + one_line(&finding.risk_domain), + one_line(&finding.lifecycle_state), + ), + format!("id: {}", finding.id), + ]; + if let Some(class) = &finding.evidence_class { + out.push(format!("evidence_class: {}", one_line(class))); + } + if let Some(validation) = &finding.latest_validation { + let actor = validation + .actor_name + .as_deref() + .or(validation.actor_login.as_deref()) + .map_or_else(|| "automatic".to_owned(), one_line); + out.push(format!( + "validation: {} ({}, {}, {})", + one_line(&validation.validation), + one_line(&validation.source), + actor, + one_line(&validation.recorded_at), + )); + } else if let Some(validation) = &finding.validation { + out.push(format!("validation: {}", one_line(validation))); + } + out.push(format!("claim: {}", one_line(&finding.claim))); + out.push(format!("impact: {}", one_line(&finding.impact))); + if let Some(remediation) = &finding.remediation { + out.push(format!("fix: {}", one_line(remediation))); + } + if let Some(url) = &finding.github_comment_url { + out.push(format!("github_comment: {}", one_line(url))); + } + if !finding.evidence_refs.is_empty() { + out.push("evidence:".to_owned()); + for evidence in &finding.evidence_refs { + out.push(format!(" {}", format_evidence_ref(evidence))); + } + } + if let Some(support) = &finding.supporting_evidence { + if let Some(explanation) = &support.explanation { + out.push(format!( + "support: {}", + one_line(&explanation.untrusted_text) + )); + } + for evidence in &support.evidence_refs { + out.push(format!(" support_ref: {}", format_evidence_ref(evidence))); + } + } + if let Some(graph) = &finding.causal_graph { + out.push(format!( + "causal_graph: {} nodes, {} edges", + graph.nodes.len(), + graph.edges.len() + )); + for node in &graph.nodes { + let role = if node.role.is_empty() { + String::new() + } else { + format!(" [{}]", one_line(&node.role)) + }; + out.push(format!( + " node {}{}: {}", + one_line(&node.id), + role, + one_line(&node.label) + )); + } + for edge in &graph.edges { + let relation = edge + .label + .as_deref() + .map(|label| format!(" ({})", one_line(label))) + .unwrap_or_default(); + out.push(format!( + " edge {} -> {}{}", + one_line(&edge.from), + one_line(&edge.to), + relation + )); + } + } + if !finding.rule_refs.is_empty() { + let keys: Vec = finding + .rule_refs + .iter() + .map(|rule| one_line(&rule.key)) + .collect(); + out.push(format!("rules: {}", keys.join(", "))); + } + out.push(String::new()); + out.join("\n") +} + #[cfg(test)] mod tests { use super::*; @@ -305,4 +434,103 @@ mod tests { assert!(!text.contains('\u{1b}')); assert!(text.contains("x\u{FFFD}[2J y")); } + + #[test] + fn finding_detail_renders_evidence_validation_and_causal_graph() { + use crate::model::{ + CustomerEvidenceRef, CustomerFinding, CustomerFindingValidation, FindingCausalEdgeView, + FindingCausalGraphView, FindingCausalNodeView, FindingRuleRefView, FindingSupport, + UntrustedText, + }; + + let item = CustomerFinding { + id: uuid::Uuid::nil(), + finding_fingerprint: None, + severity: "SERIOUS".to_owned(), + risk_domain: "data_integrity".to_owned(), + claim: "x\u{1b}[2J\norder lost".to_owned(), + impact: "orders are dropped".to_owned(), + symbols: vec!["save_order".to_owned()], + lifecycle_state: "NEW".to_owned(), + remediation: Some("wrap in transaction".to_owned()), + evidence_class: Some("WORLD_EVIDENCED".to_owned()), + evidence_refs: vec![CustomerEvidenceRef { + kind: "CODE".to_owned(), + label: "handler".to_owned(), + provenance_status: "VERIFIED".to_owned(), + repository_path: Some("src/orders.rs".to_owned()), + start_line: Some(10), + end_line: Some(14), + file_sha256: None, + commit_sha: None, + companion_repository: None, + url: None, + workflow_run_id: None, + workflow_attempt: None, + legacy_text: None, + }], + causal_graph: Some(FindingCausalGraphView { + nodes: vec![ + FindingCausalNodeView { + id: "n1".to_owned(), + label: "save_order".to_owned(), + role: "change".to_owned(), + }, + FindingCausalNodeView { + id: "n2".to_owned(), + label: "orders_db".to_owned(), + role: "failure".to_owned(), + }, + ], + edges: vec![FindingCausalEdgeView { + from: "n1".to_owned(), + to: "n2".to_owned(), + label: Some("writes without tx".to_owned()), + }], + }), + supporting_evidence: Some(FindingSupport { + explanation: Some(UntrustedText { + untrusted_text: "verified against schema".to_owned(), + }), + evidence_refs: Vec::new(), + }), + latest_validation: Some(CustomerFindingValidation { + validation: "CONFIRMED".to_owned(), + source: "GITHUB_COMMENT".to_owned(), + recorded_at: "2026-11-18T00:00:00Z".to_owned(), + actor_github_user_id: Some(42), + actor_login: Some("octocat".to_owned()), + actor_name: Some("Octo Cat".to_owned()), + covering_author_kind: None, + covering_author_login: None, + covering_comment_created_at: None, + github_comment_url: None, + }), + validation: Some("CONFIRMED".to_owned()), + github_comment_url: Some( + "https://github.com/owner/repo/pull/1#discussion_r1".to_owned(), + ), + rule_refs: vec![FindingRuleRefView { + key: "tx-safety".to_owned(), + revisions: Vec::new(), + }], + comment_reactions: Vec::new(), + local_findings: Vec::new(), + placement: None, + comment_evaluation: None, + thread_observation: None, + }; + let text = finding_detail(&item); + assert!(!text.contains('\u{1b}'), "{text}"); + assert!(text.contains("SERIOUS data_integrity [NEW]"), "{text}"); + assert!(text.contains("evidence_class: WORLD_EVIDENCED"), "{text}"); + assert!( + text.contains("validation: CONFIRMED (GITHUB_COMMENT, Octo Cat, 2026-11-18T00:00:00Z)"), + "{text}" + ); + assert!(text.contains("at src/orders.rs:10-14"), "{text}"); + assert!(text.contains("causal_graph: 2 nodes, 1 edges"), "{text}"); + assert!(text.contains("edge n1 -> n2 (writes without tx)"), "{text}"); + assert!(text.contains("rules: tx-safety"), "{text}"); + } } diff --git a/tests/contract.rs b/tests/contract.rs index e8aaf77..893cb25 100644 --- a/tests/contract.rs +++ b/tests/contract.rs @@ -4,11 +4,11 @@ use std::process::Command; use proofline_cli::model::{ Assessment, Check, Checks, CodeAssessment, CommitReviewRequest, CommitReviewResponse, - CoverageUploadRequest, CoverageUploadResponse, EvidenceRef, FileReviewRequest, - FileReviewResponse, FileScope, FilterChoice, Finding, OpenItems, PatchReviewRequest, - PatchReviewResponse, RepositoryName, RepositoryNames, ReviewDetail, ReviewFilters, ReviewPage, - ReviewSubject, ReviewSummary, RunNowMode, RunNowRequest, RunNowResponse, StopResponse, - UploadedReport, + CoverageUploadRequest, CoverageUploadResponse, CustomerEvidenceRef, CustomerFinding, + EvidenceRef, FileReviewRequest, FileReviewResponse, FileScope, FilterChoice, Finding, + OpenItems, PatchReviewRequest, PatchReviewResponse, RepositoryName, RepositoryNames, + ReviewDetail, ReviewFilters, ReviewPage, ReviewSubject, ReviewSummary, RunNowMode, + RunNowRequest, RunNowResponse, StopResponse, UploadedReport, }; use serde::Serialize; use serde::de::DeserializeOwned; @@ -161,7 +161,9 @@ fn types_match_the_public_contract() { holds::("CustomerChecks"); holds::("CustomerCheck"); holds::("CustomerFinding"); + holds::("CustomerFinding"); holds::("CustomerEvidenceRef"); + holds::("CustomerEvidenceRef"); holds::("RunNowRequest"); holds::("RunNowResponse"); holds::("PatchReviewRequest"); @@ -231,6 +233,10 @@ fn operations_the_cli_calls_exist() { for (method, path) in [ ("get", "/api/v1/organizations/{org_id}/reviews"), ("get", "/api/v1/organizations/{org_id}/reviews/{review_id}"), + ( + "get", + "/api/v1/organizations/{org_id}/findings/{finding_id}", + ), ("get", "/api/v1/organizations/{org_id}/repository-names"), ( "post", diff --git a/tests/http.rs b/tests/http.rs index eb6157d..85c9d84 100644 --- a/tests/http.rs +++ b/tests/http.rs @@ -3506,3 +3506,118 @@ async fn config_proposal_targets_must_match_the_selected_organization() { assert_eq!(server.requests()[0]["arguments"]["organization_id"], ORG); assert_eq!(server.frames.load(Ordering::SeqCst), 3); } + +#[tokio::test] +async fn finding_command_renders_text_and_json_safely() { + let finding_id = "00000000-0000-0000-0000-000000000099"; + let expected_path = format!("/api/v1/organizations/{ORG}/findings/{finding_id}"); + let payload = json!({ + "id": finding_id, + "finding_fingerprint": null, + "severity": "SERIOUS", + "risk_domain": "data_integrity", + "claim": "dropped write\u{001b}[2J", + "impact": "orders can be lost", + "symbols": ["save_order"], + "lifecycle_state": "NEW", + "remediation": "wrap in a transaction", + "evidence_class": "WORLD_EVIDENCED", + "evidence_refs": [{ + "kind": "CODE", + "label": "handler", + "provenance_status": "VERIFIED", + "repository_path": "src/orders.rs", + "start_line": 10, + "end_line": 14, + "file_sha256": null, + "commit_sha": null, + "companion_repository": null, + "url": null, + "workflow_run_id": null, + "workflow_attempt": null, + "legacy_text": null + }], + "causal_graph": { + "nodes": [{"id": "n1", "label": "save_order", "role": "change"}], + "edges": [{"from": "n1", "to": "n2", "label": "writes"}] + }, + "supporting_evidence": { + "explanation": {"untrusted_text": "confirmed by trace"}, + "evidence_refs": [] + }, + "latest_validation": { + "validation": "CONFIRMED", + "source": "GITHUB_COMMENT", + "recorded_at": "2026-11-18T00:00:00Z", + "actor_github_user_id": 42, + "actor_login": "octocat", + "actor_name": "Octo Cat", + "covering_author_kind": null, + "covering_author_login": null, + "covering_comment_created_at": null, + "github_comment_url": null + }, + "validation": "CONFIRMED", + "github_comment_url": "https://github.com/owner/repo/pull/1#discussion_r1", + "rule_refs": [{"key": "tx-safety", "revisions": []}], + "comment_reactions": [], + "local_findings": [], + "placement": null, + "comment_evaluation": null, + "thread_observation": null, + "future_server_field": {"kept_in_json": true} + }); + let body = payload.clone(); + let app = Router::new().route( + &expected_path, + get(move |headers: HeaderMap| { + let body = body.clone(); + async move { + assert_eq!( + headers + .get("authorization") + .and_then(|value| value.to_str().ok()), + Some(format!("Bearer {TOKEN}").as_str()) + ); + Json(body) + } + }), + ); + 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(); + }); + + let text_out = cli(&origin, &["finding", finding_id]).await; + assert!( + text_out.status.success(), + "{}", + String::from_utf8_lossy(&text_out.stderr) + ); + assert!(!text_out.stdout.contains(&27)); + let stdout = String::from_utf8_lossy(&text_out.stdout); + assert!( + stdout.contains("SERIOUS data_integrity [NEW]"), + "{stdout}" + ); + assert!( + stdout.contains("evidence_class: WORLD_EVIDENCED"), + "{stdout}" + ); + assert!(stdout.contains("at src/orders.rs:10-14"), "{stdout}"); + assert!( + stdout.contains("causal_graph: 1 nodes, 1 edges"), + "{stdout}" + ); + + let json_out = cli(&origin, &["finding", finding_id, "--json"]).await; + assert!( + json_out.status.success(), + "{}", + String::from_utf8_lossy(&json_out.stderr) + ); + let parsed: Value = serde_json::from_slice(&json_out.stdout).unwrap(); + assert_eq!(parsed["id"], finding_id); + assert_eq!(parsed["future_server_field"]["kept_in_json"], true); +} From 98cac86da9b988f887abefbe1d5406f43a718ddf Mon Sep 17 00:00:00 2001 From: akacolf Date: Wed, 18 Nov 2026 16:34:32 +0300 Subject: [PATCH 2/2] test: assert full raw JSON payload preservation for finding --json --- tests/http.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/tests/http.rs b/tests/http.rs index 85c9d84..2cb3787 100644 --- a/tests/http.rs +++ b/tests/http.rs @@ -3618,6 +3618,5 @@ async fn finding_command_renders_text_and_json_safely() { String::from_utf8_lossy(&json_out.stderr) ); let parsed: Value = serde_json::from_slice(&json_out.stdout).unwrap(); - assert_eq!(parsed["id"], finding_id); - assert_eq!(parsed["future_server_field"]["kept_in_json"], true); + assert_eq!(parsed, payload); }