From 1133ffcff8b04626f867e73998f4f0fa10f91036 Mon Sep 17 00:00:00 2001 From: Harshit Sharma Date: Sun, 29 Nov 2026 19:39:00 +0530 Subject: [PATCH 1/2] Show what a review run cost in review text output The review API returns each run's charge (cost_microcredits), the share for review work (review_cost_microcredits) and what paid for it (cost_funding) to organization members, but the text output dropped all three. Only --json carried them, so a person on the free review month or a capped plan could not see what a review spent without reading raw JSON, and had nothing to size `scan --budget` against. Review text now prints one line below the review link, for example: Cost: 2.75 credits (review 2.5, walkthrough 0.25); paid by: free review month 2.75 - Amounts are exact decimal credits from integer microcredits, never rounded or converted through floats. - A pending or running review reports its cost "so far". - The walkthrough share appears only when it is positive; parts that paid nothing are left out. - A caller the server hides the cost from, or an older server, gets no line. A cost value the CLI cannot read is treated as absent, so it never fails the review read; --json keeps the API's value unchanged. --- README.md | 2 + src/model.rs | 35 +++++++++++ src/outcome.rs | 3 + src/render.rs | 152 +++++++++++++++++++++++++++++++++++++++++++++- tests/contract.rs | 5 +- tests/http.rs | 81 ++++++++++++++++++++++++ 6 files changed, 275 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index eea0165..a0bd784 100644 --- a/README.md +++ b/README.md @@ -38,6 +38,8 @@ Native knowledge, plan, fix and configuration commands send the selected organiz `proofline reviews --repository-id UUID --cursor CURSOR` returns one page with its continuation metadata, and all flags are optional. `proofline routing REVIEW_ID` reads recorded routing. `proofline run --repo owner/name --pr 7 --run 2` reads one retained run, and `proofline history --repo owner/name --pr 7` reads all recorded runs. Both commands send the API the name without its owner, and use the response only when its repository choices list `owner/name`, or the Git remote's owner and name, among the organization's reviewed repositories. A repository with no reviews in the organization exits nonzero. `proofline findings --pr 7` finds the pull request's newest review through the same route and counts only runs of the repository whose full name matches. None of these commands reads the organization's review list. +When the server shows a caller what a run was charged, as it does for organization members, review text output prints a `Cost:` line below the review link, for example `Cost: 2.75 credits (review 2.5, walkthrough 0.25); paid by: free review month 2.75`. Amounts are exact decimal credits; one credit is 1,000,000 microcredits. The split appears when the separately billed pull-request walkthrough cost something, and `paid by` names each part the plan, the free review month or the organization's credits paid. A review that is still running reports its cost `so far`. Other callers and older servers get no line. `--json` keeps the API's `cost_microcredits`, `review_cost_microcredits` and `cost_funding` fields unchanged. + `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. `proofline review --range BASE..HEAD --fail-on serious` exits 3 when a complete review has an unresolved finding at or above the threshold. PR reviews use the server’s effective open-item counts; other reviews count unresolved findings. Incomplete and unavailable results retain their nonzero exits. `--fail-on` cannot be combined with `--no-wait`. diff --git a/src/model.rs b/src/model.rs index e029008..d2a0421 100644 --- a/src/model.rs +++ b/src/model.rs @@ -98,6 +98,41 @@ pub struct ReviewDetail { /// every other review. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub local_reverifications: Vec, + /// The credits this run was charged so far, in microcredits, whoever paid. + /// Null for a caller who is not a member of the organization, and absent + /// from an older server. + #[serde(default, deserialize_with = "display_only")] + pub cost_microcredits: Option, + /// The review work within `cost_microcredits`, excluding the separately + /// billed pull-request walkthrough. + #[serde(default, deserialize_with = "display_only")] + pub review_cost_microcredits: Option, + /// What paid for `cost_microcredits`. Present exactly when it is. + #[serde(default, deserialize_with = "display_only")] + pub cost_funding: Option, +} + +/// A value the CLI only displays reads as absent when it is not the shape the +/// CLI knows, so it can never fail the review read that carries it. The JSON +/// output keeps the API's value either way. +fn display_only<'de, D, T>(deserializer: D) -> Result, D::Error> +where + D: serde::Deserializer<'de>, + T: serde::de::DeserializeOwned, +{ + let value = Option::::deserialize(deserializer)?; + Ok(value.and_then(|value| serde_json::from_value(value).ok())) +} + +/// What paid for a run's credit cost. The three parts add up to the cost. +#[derive(Debug, Deserialize, Serialize)] +pub struct ReviewCostFunding { + /// Paid by the workspace allowance or the author's seat. + pub plan_microcredits: i64, + /// Paid by the organization's free review month. + pub free_review_microcredits: i64, + /// Taken from the organization's shared credit balance. + pub organization_microcredits: i64, } /// One finding a patch review re-verified against the local changes. The diff --git a/src/outcome.rs b/src/outcome.rs index 5bc661b..7c72c10 100644 --- a/src/outcome.rs +++ b/src/outcome.rs @@ -341,6 +341,9 @@ mod tests { repository_full_name: Some("acme/web".to_owned()), run_number: Some(1), local_reverifications: Vec::new(), + cost_microcredits: None, + review_cost_microcredits: None, + cost_funding: None, } } diff --git a/src/render.rs b/src/render.rs index 782b09f..3136479 100644 --- a/src/render.rs +++ b/src/render.rs @@ -6,7 +6,8 @@ use std::cmp::Reverse; use url::Url; use crate::model::{ - Assessment, CodeAssessment, Finding, LocalReverification, ReviewDetail, StoredCheck, + Assessment, CodeAssessment, Finding, LocalReverification, ReviewCostFunding, ReviewDetail, + StoredCheck, }; use crate::outcome::{self, Outcome}; use crate::severity::Severity; @@ -133,6 +134,76 @@ fn commits(review: &ReviewDetail) -> String { } } +/// One credit is a million microcredits, the API's exact charge unit. +const MICROCREDITS_PER_CREDIT: u64 = 1_000_000; + +/// Microcredits as exact decimal credits, never rounded: `1250000` is `1.25` +/// and `3` is `0.000003`. +fn credits(microcredits: i64) -> String { + let sign = if microcredits < 0 { "-" } else { "" }; + let magnitude = microcredits.unsigned_abs(); + let whole = magnitude / MICROCREDITS_PER_CREDIT; + let fraction = magnitude % MICROCREDITS_PER_CREDIT; + if fraction == 0 { + return format!("{sign}{whole}"); + } + let digits = format!("{fraction:06}"); + format!("{sign}{whole}.{}", digits.trim_end_matches('0')) +} + +/// The parts of a run's cost that something paid, in a fixed order. A part +/// that paid nothing is left out. +fn funding(funding: &ReviewCostFunding) -> Vec { + [ + ("plan", funding.plan_microcredits), + ("free review month", funding.free_review_microcredits), + ("organization credits", funding.organization_microcredits), + ] + .into_iter() + .filter(|(_, microcredits)| *microcredits != 0) + .map(|(source, microcredits)| format!("{source} {}", credits(microcredits))) + .collect() +} + +/// What the run was charged, for a caller the server shows it to. The server +/// reports the charge so far, so a review that is still running says so. The +/// review work excludes the separately billed walkthrough, so the rest of the +/// total is the walkthrough's. +fn cost(review: &ReviewDetail, state: Option) -> Option { + let total = review.cost_microcredits?; + let unit = if total.unsigned_abs() == MICROCREDITS_PER_CREDIT { + "credit" + } else { + "credits" + }; + let so_far = if state.is_none() { " so far" } else { "" }; + let split = review + .review_cost_microcredits + .and_then(|work| { + let walkthrough = total.checked_sub(work).filter(|rest| *rest > 0)?; + Some(format!( + " (review {}, walkthrough {})", + credits(work), + credits(walkthrough) + )) + }) + .unwrap_or_default(); + let paid = review + .cost_funding + .as_ref() + .map(funding) + .unwrap_or_default(); + let paid = if paid.is_empty() { + String::new() + } else { + format!("; paid by: {}", paid.join(", ")) + }; + Some(format!( + "Cost: {} {unit}{so_far}{split}{paid}", + credits(total) + )) +} + /// The paths a FILES review selected at its primary revision. fn selected_files(review: &ReviewDetail) -> Option { if review.kind != "FILES" { @@ -213,6 +284,7 @@ pub fn audit(url: &Url) -> String { pub fn review(review: &ReviewDetail, state: Option, url: &Url) -> String { let mut out = vec![headline(review, state), url.to_string()]; + out.extend(cost(review, state)); if let Some(reason) = outcome::review_gap(review) { out.push(format!("Review incomplete: {reason}")); } @@ -271,9 +343,87 @@ mod tests { repository_full_name: Some("acme/web".to_owned()), run_number: Some(2), local_reverifications: Vec::new(), + cost_microcredits: None, + review_cost_microcredits: None, + cost_funding: None, + } + } + + fn charged(total: i64, work: Option, paid: Option<(i64, i64, i64)>) -> ReviewDetail { + let mut detail = sample("COMPLETED", Vec::new()); + detail.cost_microcredits = Some(total); + detail.review_cost_microcredits = work; + detail.cost_funding = paid.map(|(plan, free, organization)| ReviewCostFunding { + plan_microcredits: plan, + free_review_microcredits: free, + organization_microcredits: organization, + }); + detail + } + + #[test] + fn credits_are_exact_decimals_without_rounding() { + for (microcredits, text) in [ + (0, "0"), + (3, "0.000003"), + (999_999, "0.999999"), + (1_000_000, "1"), + (1_250_000, "1.25"), + (12_345_678, "12.345678"), + (-1_500_000, "-1.5"), + (i64::MIN, "-9223372036854.775808"), + ] { + assert_eq!(credits(microcredits), text, "{microcredits}"); + } + } + + #[test] + fn the_cost_names_its_split_and_what_paid_for_it() { + let detail = charged(1_250_000, Some(1_100_000), Some((1_000_000, 0, 250_000))); + let text = review(&detail, outcome::terminal(&detail), &url()); + let lines: Vec<&str> = text.lines().collect(); + assert_eq!( + lines[2], + "Cost: 1.25 credits (review 1.1, walkthrough 0.15); paid by: plan 1, organization credits 0.25" + ); + } + + #[test] + fn a_running_review_reports_its_cost_so_far() { + let mut detail = charged(400_000, Some(400_000), Some((0, 400_000, 0))); + detail.status = "RUNNING".to_owned(); + let text = review(&detail, outcome::terminal(&detail), &url()); + assert!( + text.contains("\nCost: 0.4 credits so far; paid by: free review month 0.4\n"), + "{text}" + ); + } + + #[test] + fn one_credit_is_singular_and_a_free_run_names_no_payer() { + let one = review(&charged(1_000_000, None, None), None, &url()); + assert!(one.contains("\nCost: 1 credit so far\n"), "{one}"); + let free = review(&charged(0, Some(0), Some((0, 0, 0))), None, &url()); + assert!(free.contains("\nCost: 0 credits so far\n"), "{free}"); + } + + #[test] + fn an_inconsistent_review_share_prints_no_split() { + // Review work equal to or above the total leaves no walkthrough to name. + for work in [1_000, 2_000] { + let detail = charged(1_000, Some(work), None); + let text = review(&detail, outcome::terminal(&detail), &url()); + assert!(text.contains("\nCost: 0.001 credits\n"), "{text}"); } } + #[test] + fn a_caller_the_server_hides_the_cost_from_sees_no_cost_line() { + let detail = sample("COMPLETED", Vec::new()); + let text = review(&detail, outcome::terminal(&detail), &url()); + assert!(!text.contains("Cost:"), "{text}"); + } + fn finding(severity: &str, claim: &str) -> Finding { Finding { id: uuid::Uuid::nil(), diff --git a/tests/contract.rs b/tests/contract.rs index cf7ae44..d062082 100644 --- a/tests/contract.rs +++ b/tests/contract.rs @@ -7,8 +7,8 @@ use proofline_cli::model::{ CommitReviewRequest, CommitReviewResponse, CoverageUploadRequest, CoverageUploadResponse, DeployCheckpoint, EvidenceRef, FileReviewRequest, FileReviewResponse, FileScope, FilterChoice, Finding, OpenItems, PatchReviewRequest, PatchReviewResponse, RepositoryName, RepositoryNames, - ReviewDetail, ReviewFilters, ReviewPage, ReviewSubject, ReviewSummary, RunNowMode, - RunNowRequest, RunNowResponse, StopResponse, UploadedReport, + ReviewCostFunding, ReviewDetail, ReviewFilters, ReviewPage, ReviewSubject, ReviewSummary, + RunNowMode, RunNowRequest, RunNowResponse, StopResponse, UploadedReport, }; use serde::Serialize; use serde::de::DeserializeOwned; @@ -155,6 +155,7 @@ fn types_match_the_public_contract() { holds::("RepositoryName"); holds::("ReviewSummary"); holds::("CustomerReviewDetail"); + holds::("ReviewCostFunding"); holds::("OpenItemsView"); holds::("CustomerAssessment"); holds::("CustomerCodeAssessment"); diff --git a/tests/http.rs b/tests/http.rs index 940dc12..b2fcec5 100644 --- a/tests/http.rs +++ b/tests/http.rs @@ -432,6 +432,8 @@ struct Fake { polls: Arc, report_organization: bool, summary: Option, + /// Fields merged into the review, such as its cost. + review_fields: Option, } async fn code() -> Json { @@ -532,6 +534,11 @@ async fn review(State(fake): State, headers: HeaderMap) -> Response { if let Some(summary) = fake.summary { body["change_summary"] = summary; } + if let Some(Value::Object(fields)) = fake.review_fields { + for (name, value) in fields { + body[name] = value; + } + } Json(body).into_response() } @@ -691,6 +698,80 @@ async fn a_review_reads_with_unknown_fields_and_keeps_its_gap() { } } +#[tokio::test] +async fn review_text_names_the_runs_cost_only_when_the_server_shows_it() { + let review = "0190f3a0-0000-7000-8000-0000000000aa"; + let charged = json!({ + "cost_microcredits": 2_750_000, + "review_cost_microcredits": 2_500_000, + "cost_funding": { + "plan_microcredits": 0, + "free_review_microcredits": 2_750_000, + "organization_microcredits": 0, + }, + }); + // A caller who is not a member of the organization reads nulls. + let hidden = json!({ + "cost_microcredits": null, + "review_cost_microcredits": null, + "cost_funding": null, + }); + for (fields, line) in [ + ( + Some(charged), + Some( + "Cost: 2.75 credits (review 2.5, walkthrough 0.25); paid by: free review month 2.75", + ), + ), + (Some(hidden), None), + // An older server omits the fields. + (None, None), + // A cost the CLI cannot read never fails the review it rides on. + ( + Some(json!({ + "cost_microcredits": "2.75", + "review_cost_microcredits": [], + "cost_funding": "free review month", + })), + None, + ), + ( + Some(json!({ + "cost_microcredits": 1_000_000, + "cost_funding": { "plan_microcredits": 1_000_000 }, + })), + Some("Cost: 1 credit"), + ), + ] { + let origin = serve(Fake { + review_fields: fields.clone(), + ..Fake::default() + }) + .await; + let output = cli(&origin.to_string(), &["findings", "--review", review]).await; + // The fake review's environment assessment is incomplete. + assert_eq!(output.status.code(), Some(2), "{output:?}"); + let stdout = String::from_utf8(output.stdout).unwrap(); + let lines: Vec<&str> = stdout.lines().collect(); + match line { + Some(line) => assert_eq!(lines.get(2), Some(&line), "{stdout}"), + None => assert!(!stdout.contains("Cost:"), "{stdout}"), + } + + let json = cli( + &origin.to_string(), + &["findings", "--review", review, "--json"], + ) + .await; + let result: Value = serde_json::from_slice(&json.stdout).unwrap(); + if let Some(Value::Object(fields)) = &fields { + for (name, value) in fields { + assert_eq!(&result["review"][name], value, "{name}"); + } + } + } +} + #[tokio::test] async fn redirects_are_refused_so_the_token_stays_on_its_origin() { let api = Api::new( From 7ba745857e7ce9b5abf2ae822db91c0373dfa8e1 Mon Sep 17 00:00:00 2001 From: Harshit Sharma Date: Mon, 30 Nov 2026 07:51:02 +0530 Subject: [PATCH 2/2] Omit the cost split when the review share is negative The split guard dropped a review share at or above the total, but not one below zero. A negative review_cost_microcredits then printed a negative review cost and a walkthrough cost larger than the total. Show the split only when the review share lies within the total; the total itself still prints. --- src/render.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/render.rs b/src/render.rs index 3136479..251a53a 100644 --- a/src/render.rs +++ b/src/render.rs @@ -179,6 +179,8 @@ fn cost(review: &ReviewDetail, state: Option) -> Option { let so_far = if state.is_none() { " so far" } else { "" }; let split = review .review_cost_microcredits + // A share outside the total names no real split. + .filter(|work| *work >= 0) .and_then(|work| { let walkthrough = total.checked_sub(work).filter(|rest| *rest > 0)?; Some(format!( @@ -409,8 +411,9 @@ mod tests { #[test] fn an_inconsistent_review_share_prints_no_split() { - // Review work equal to or above the total leaves no walkthrough to name. - for work in [1_000, 2_000] { + // Review work below zero, or equal to or above the total, names no + // real walkthrough share, so only the total prints. + for work in [-1, -500, i64::MIN, 1_000, 2_000] { let detail = charged(1_000, Some(work), None); let text = review(&detail, outcome::terminal(&detail), &url()); assert!(text.contains("\nCost: 0.001 credits\n"), "{text}");