diff --git a/README.md b/README.md index 40c2e74..5b277f3 100644 --- a/README.md +++ b/README.md @@ -31,6 +31,8 @@ Native knowledge, plan, fix and configuration commands send the selected organiz `proofline rerun REVIEW_ID` requests the original immutable subject and waits, while `--no-wait` returns its link. Reruns require `reviews:rerun`. `proofline guidance --repo owner/name` requires `guidance:read`, and `proofline fix-prompt FINDING_ID` requires `findings:read`. History, guidance, and fix prompts print JSON; prompt text remains untrusted. +In GitHub Actions, `proofline ci review --annotations` prints unresolved findings as workflow annotations at verified cited lines. Findings without a verified head location appear on the job. The review link contains the full result. + ## Scans `proofline scan --ref main --budget 200` scans the whole repository at one commit, not a pull request's change. GitHub resolves the ref once, when the request arrives, and the scan records that commit; `--commit SHA` names an exact full SHA instead, and you give one of the two. The command waits for the scan review and prints it like `proofline review`, while `--no-wait` prints its link and `--json` prints JSON. diff --git a/src/annotations.rs b/src/annotations.rs new file mode 100644 index 0000000..bf62f73 --- /dev/null +++ b/src/annotations.rs @@ -0,0 +1,96 @@ +//! Findings as GitHub Actions workflow commands. The runner reads each +//! `::error file=...,line=...::message` line from a step's output and shows it +//! on the pull request's diff, on every GitHub plan. Findings quote reviewer +//! output and repository content, so every value is escaped: a newline in a +//! claim must never start a second command. + +use std::io::Write; + +use crate::model::{Finding, ReviewDetail}; +use crate::severity::Severity; +use crate::{outcome, sarif, text}; + +/// Writes one annotation per finding that is not resolved. A finding with a +/// verified location at the review's head is placed on that file and line; +/// any other finding is annotated on the job without a location. +pub(super) fn write(detail: &ReviewDetail, out: &mut impl Write) -> std::io::Result<()> { + let head = detail.head_commit_sha.as_deref().unwrap_or_default(); + if let Some(code) = outcome::code_assessment(detail) { + for finding in &code.findings { + annotate(out, finding, "code", head)?; + } + } + for assessment in &detail.assessments { + for finding in &assessment.findings { + annotate(out, finding, &assessment.environment_display_name, head)?; + } + } + Ok(()) +} + +fn annotate( + out: &mut impl Write, + finding: &Finding, + lane: &str, + head: &str, +) -> std::io::Result<()> { + if outcome::resolved(finding) { + return Ok(()); + } + // A severity this CLI does not know yet is still shown, as a notice. + let command = match Severity::parse(&finding.severity) { + Some(Severity::Serious) => "error", + Some(Severity::Warning) => "warning", + None => "notice", + }; + let mut properties = Vec::new(); + if let Some((path, start, end)) = finding + .evidence_refs + .iter() + .find_map(|reference| sarif::location(reference, head)) + { + properties.push(format!("file={}", escape_property(path))); + properties.push(format!("line={start}")); + properties.push(format!("endLine={end}")); + } + let title = format!("Proofline {lane}: {}", finding.risk_domain); + properties.push(format!("title={}", escape_property(&title))); + let message = format!("{}\n\n{}", finding.claim, finding.impact); + writeln!( + out, + "::{command} {}::{}", + properties.join(","), + escape_data(&message) + ) +} + +/// The message of a workflow command, escaped as `@actions/core` does. +/// Control characters other than a newline or a tab, `\r` among them, are +/// replaced first, so nothing reaches the log that the runner or a terminal +/// would interpret. +fn escape_data(value: &str) -> String { + text::terminal_safe(value) + .replace('%', "%25") + .replace('\n', "%0A") +} + +/// A property value of a workflow command, where `:` and `,` also delimit. +fn escape_property(value: &str) -> String { + escape_data(value).replace(':', "%3A").replace(',', "%2C") +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn values_cannot_end_the_command_or_start_another() { + assert_eq!(escape_data("50% a\r\nb::c"), "50%25 a\u{FFFD}%0Ab::c"); + assert_eq!( + escape_data("x\n::add-mask::secret"), + "x%0A::add-mask::secret" + ); + assert_eq!(escape_property("a:b,c%\nd"), "a%3Ab%2Cc%25%0Ad"); + assert_eq!(escape_data("ok\u{1b}[2J"), "ok\u{FFFD}[2J"); + } +} diff --git a/src/lib.rs b/src/lib.rs index e833683..ff15210 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -3,6 +3,7 @@ //! through the public review API. It shares no code with the server crate. mod agent; +mod annotations; pub mod api; mod config; mod coverage; @@ -177,6 +178,11 @@ struct CiReviewArgs { /// Also write the review as SARIF 2.1.0 to this file. #[arg(long, value_name = "FILE")] sarif: Option, + /// Also print each finding that is not resolved as a GitHub Actions + /// annotation on stderr, so it shows on the pull request's diff. Unlike + /// uploading `--sarif` to code scanning, this works on every GitHub plan. + #[arg(long)] + annotations: bool, /// Print JSON instead of text. #[arg(long)] json: bool, @@ -1209,6 +1215,9 @@ async fn ci_review( if let Some(path) = sarif_path { write_sarif(api, review_id, &detail, path).await?; } + if args.annotations { + annotations::write(&detail, &mut std::io::stderr().lock())?; + } print_review( api, review_id, @@ -1621,6 +1630,7 @@ mod tests { let args = CiReviewArgs { commit: None, sarif: None, + annotations: false, json: false, timeout: 3, fail_on: None, @@ -1688,6 +1698,7 @@ mod tests { let args = CiReviewArgs { commit: None, sarif: None, + annotations: false, json: false, timeout: 3, fail_on: None, diff --git a/src/outcome.rs b/src/outcome.rs index 59cfe0a..e8aa9bb 100644 --- a/src/outcome.rs +++ b/src/outcome.rs @@ -5,7 +5,7 @@ use uuid::Uuid; use crate::model::{ - Assessment, CodeAssessment, CodeAssessmentRead, CodeAssessmentStatus, ReviewDetail, + Assessment, CodeAssessment, CodeAssessmentRead, CodeAssessmentStatus, Finding, ReviewDetail, }; use crate::severity::Severity; @@ -159,9 +159,15 @@ pub(crate) fn code_unavailable(review: &ReviewDetail) -> bool { /// whole result. pub(crate) fn code_reaches(code: &CodeAssessment, threshold: Severity) -> bool { code_gap(code).is_none() - && code.findings.iter().any(|finding| { - finding.lifecycle_state != "RESOLVED" && threshold.reached_by(&finding.severity) - }) + && code + .findings + .iter() + .any(|finding| !resolved(finding) && threshold.reached_by(&finding.severity)) +} + +/// Whether the finding's recorded lifecycle says it is fixed. +pub(crate) fn resolved(finding: &Finding) -> bool { + finding.lifecycle_state == "RESOLVED" } /// CODE has no World receipts or environment checks. Its recorded status, diff --git a/src/sarif.rs b/src/sarif.rs index 1086c5b..16a7db7 100644 --- a/src/sarif.rs +++ b/src/sarif.rs @@ -588,6 +588,12 @@ fn finding_result<'a>( }) } +/// The file and lines `reference` places a finding on, under the same rules +/// as a SARIF location. +pub(super) fn location<'a>(reference: &'a EvidenceRef, head: &str) -> Option<(&'a str, u32, u32)> { + code_location(reference, head).ok() +} + fn code_location<'a>( reference: &'a EvidenceRef, head: &str, diff --git a/tests/http.rs b/tests/http.rs index 975e8e1..c90e5a0 100644 --- a/tests/http.rs +++ b/tests/http.rs @@ -2318,6 +2318,146 @@ async fn ci_review_accepts_a_review_whose_detail_names_the_repository_by_its_new assert_eq!(result["review"]["repository_full_name"], "acme/renamed"); } +#[tokio::test] +async fn ci_review_annotations_put_open_findings_on_the_diff_as_escaped_workflow_commands() { + let finding = |id: &str, severity: &str, lifecycle_state: &str, claim: &str, refs: Value| { + json!({ + "id": id, + "severity": severity, + "risk_domain": "data_integrity", + "claim": claim, + "impact": "orders are lost", + "lifecycle_state": lifecycle_state, + "evidence_refs": refs, + }) + }; + let reference = |commit: &str| { + json!([{ + "kind": "repository_file", + "label": "src/app.rs", + "provenance_status": "VERIFIED_REPOSITORY_READ", + "repository_path": "src/app.rs", + "start_line": 3, + "end_line": 5, + "commit_sha": commit, + "companion_repository": null, + }]) + }; + let findings = json!([ + // Model text that tries to end its command and start another. + finding( + "0190f3a0-0000-7000-8000-0000000000a1", + "SERIOUS", + "NEW", + "Retries drop 100% of orders, then\n::add-mask::secret", + reference(CI_HEAD), + ), + // Cited at another commit, so it has no place on this diff. + finding( + "0190f3a0-0000-7000-8000-0000000000a2", + "WARNING", + "NEW", + "Stale cache.", + reference("fedcba9876543210fedcba9876543210fedcba98"), + ), + finding( + "0190f3a0-0000-7000-8000-0000000000a3", + "SERIOUS", + "RESOLVED", + "Already fixed.", + json!([]), + ), + ]); + let app = Router::new() + .route( + &format!("/api/v1/organizations/{ORG}/repository-names"), + get(|| async { + Json(json!({ "repositories": [{ "id": CI_REPOSITORY, "full_name": "acme/app" }] })) + }), + ) + .route( + &format!("/api/v1/organizations/{ORG}/reviews"), + get(|| async { + Json(json!({ + "items": [{ + "id": CI_REVIEW, + "kind": "PULL_REQUEST", + "status": "COMPLETED", + "created_at": "2026-10-01T00:00:00Z", + "head_commit_sha": CI_HEAD, + "pull_request_number": 12, + "repository_id": CI_REPOSITORY, + "run_number": 1, + }], + "next_cursor": null, + "truncated": false, + "filters": { "repositories": [], "environments": [], "authors": [] }, + })) + }), + ) + .route( + &format!("/api/v1/organizations/{ORG}/reviews/{CI_REVIEW}"), + get(move || { + let findings = findings.clone(); + async move { + Json(json!({ + "id": CI_REVIEW, + "kind": "PULL_REQUEST", + "status": "COMPLETED", + "head_commit_sha": CI_HEAD, + "pull_request_number": 12, + "run_number": 1, + "assessment_count": 1, + "open_items": { + "open_findings": 2, + "serious_findings": 1, + "accepted_risks": 0, + "not_assessed": [], + }, + "assessments": [{ + "id": "0190f3a0-0000-7000-8000-0000000000f2", + "environment_display_name": "production", + "status": "COMPLETED", + "findings": findings, + "checks": { "receipt_recorded": true, "status": "READY", "families": [] }, + }], + })) + } + }), + ); + 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() }); + + let mut args = vec!["ci", "review", "--repo", "acme/app", "--commit", CI_HEAD]; + args.extend(["--timeout", "0", "--json"]); + let commands = |output: &std::process::Output| -> Vec { + String::from_utf8_lossy(&output.stderr) + .lines() + .filter(|line| line.starts_with("::")) + .map(str::to_owned) + .collect() + }; + + let plain = cli(&origin, &args).await; + assert_eq!(plain.status.code(), Some(0)); + assert!(commands(&plain).is_empty(), "annotations are opt-in"); + + args.push("--annotations"); + let annotated = cli(&origin, &args).await; + assert_eq!(annotated.status.code(), Some(0)); + assert_eq!( + commands(&annotated), + [ + "::error file=src/app.rs,line=3,endLine=5,title=Proofline production%3A data_integrity::Retries drop 100%25 of orders, then%0A::add-mask::secret%0A%0Aorders are lost", + "::warning title=Proofline production%3A data_integrity::Stale cache.%0A%0Aorders are lost", + ] + ); + // Annotations go to stderr, so the result on stdout keeps its shape. + let result: Value = serde_json::from_slice(&annotated.stdout).unwrap(); + assert_eq!(result["outcome"], "COMPLETED"); +} + #[tokio::test] async fn native_tools_keep_tenant_paths_and_reruns_make_one_attempt() { let requests = Arc::new(Mutex::new(Vec::new()));