From bccd26eb917dcf24fd41a5c21af1ced1f2573ea5 Mon Sep 17 00:00:00 2001 From: Hugo Planque Date: Sun, 8 Nov 2026 16:08:54 +0100 Subject: [PATCH 1/2] Show CI review findings on the pull request diff `ci review --annotations` prints each finding that is not resolved as a GitHub Actions workflow command on stderr, placed on the cited file and lines when an evidence ref is verified at the review's head. Annotations work on every GitHub plan, while uploading SARIF to code scanning needs GitHub Advanced Security on private repositories. Values are escaped like @actions/core does, so a claim cannot end its command or start another one. --- README.md | 7 +++ src/annotations.rs | 96 +++++++++++++++++++++++++++++++ src/lib.rs | 10 ++++ src/outcome.rs | 14 +++-- src/sarif.rs | 6 ++ tests/http.rs | 140 +++++++++++++++++++++++++++++++++++++++++++++ 6 files changed, 269 insertions(+), 4 deletions(-) create mode 100644 src/annotations.rs diff --git a/README.md b/README.md index 25b8097..a58fa6b 100644 --- a/README.md +++ b/README.md @@ -35,6 +35,13 @@ stderr. Repeat with `--cursor` and the same window and `--group-by` to continue. CSV repeats its header on every page. A failed page exits nonzero; never treat partial output from several invocations as a complete export. +In GitHub Actions, `proofline ci review --annotations` also prints each finding +that is not resolved as a workflow annotation, so it shows on the pull request's +diff at the cited lines. It works on every GitHub plan, while uploading the +`--sarif` file to code scanning needs GitHub Advanced Security on private +repositories. GitHub shows at most 10 error and 10 warning annotations per step; +the review link has the rest. + Build from source with `cargo build --locked --release`. The pinned Rust toolchain is installed by rustup. Run `cargo fmt --check`, `cargo clippy --locked --all-targets -- -D warnings`, `cargo test --locked` and `cargo deny check` before submitting a pull request. 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 6096711..babd11b 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 coverage; pub mod credentials; @@ -169,6 +170,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, @@ -1176,6 +1182,9 @@ async fn ci_review( .await .with_context(|| format!("could not write SARIF to {}", path.display()))?; } + if args.annotations { + annotations::write(&detail, &mut std::io::stderr().lock())?; + } print_review( api, review_id, @@ -1451,6 +1460,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 c5f87ec..c3511a9 100644 --- a/src/outcome.rs +++ b/src/outcome.rs @@ -3,7 +3,7 @@ //! complete, and an assessment with a gap is never reported as clean. use crate::model::{ - Assessment, CodeAssessment, CodeAssessmentRead, CodeAssessmentStatus, ReviewDetail, + Assessment, CodeAssessment, CodeAssessmentRead, CodeAssessmentStatus, Finding, ReviewDetail, }; use crate::severity::Severity; @@ -101,9 +101,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 and diff --git a/src/sarif.rs b/src/sarif.rs index b3c39ee..7fea680 100644 --- a/src/sarif.rs +++ b/src/sarif.rs @@ -579,6 +579,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 b65ed37..b172e53 100644 --- a/tests/http.rs +++ b/tests/http.rs @@ -1879,6 +1879,146 @@ async fn ci_review_fail_on_exits_three_for_an_open_finding_of_a_complete_review( assert!(requests.lock().unwrap().is_empty()); } +#[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())); From 49793f9856d64b08b1297d876ab7fe24e09df066 Mon Sep 17 00:00:00 2001 From: Mohsen Azimi Date: Tue, 17 Nov 2026 14:18:45 +0100 Subject: [PATCH 2/2] Keep annotations disabled in review identity regression fixture --- src/lib.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/lib.rs b/src/lib.rs index 29e63d0..ff15210 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1698,6 +1698,7 @@ mod tests { let args = CiReviewArgs { commit: None, sarif: None, + annotations: false, json: false, timeout: 3, fail_on: None,