Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand Down
35 changes: 35 additions & 0 deletions src/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,41 @@ pub struct ReviewDetail {
/// every other review.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub local_reverifications: Vec<LocalReverification>,
/// 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<i64>,
/// The review work within `cost_microcredits`, excluding the separately
/// billed pull-request walkthrough.
#[serde(default, deserialize_with = "display_only")]
pub review_cost_microcredits: Option<i64>,
/// What paid for `cost_microcredits`. Present exactly when it is.
#[serde(default, deserialize_with = "display_only")]
pub cost_funding: Option<ReviewCostFunding>,
}

/// 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<Option<T>, D::Error>
where
D: serde::Deserializer<'de>,
T: serde::de::DeserializeOwned,
{
let value = Option::<serde_json::Value>::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
Expand Down
3 changes: 3 additions & 0 deletions src/outcome.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
}
}

Expand Down
155 changes: 154 additions & 1 deletion src/render.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -133,6 +134,78 @@ 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<String> {
[
("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<Outcome>) -> Option<String> {
Comment thread
prooflinedev[bot] marked this conversation as resolved.
Resolved
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
// 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!(
" (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<String> {
if review.kind != "FILES" {
Expand Down Expand Up @@ -213,6 +286,7 @@ pub fn audit(url: &Url) -> String {

pub fn review(review: &ReviewDetail, state: Option<Outcome>, 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}"));
}
Expand Down Expand Up @@ -271,9 +345,88 @@ 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<i64>, 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 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}");
}
}

#[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(),
Expand Down
5 changes: 3 additions & 2 deletions tests/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -155,6 +155,7 @@ fn types_match_the_public_contract() {
holds::<RepositoryName>("RepositoryName");
holds::<ReviewSummary>("ReviewSummary");
holds::<ReviewDetail>("CustomerReviewDetail");
holds::<ReviewCostFunding>("ReviewCostFunding");
holds::<OpenItems>("OpenItemsView");
holds::<Assessment>("CustomerAssessment");
holds::<CodeAssessment>("CustomerCodeAssessment");
Expand Down
81 changes: 81 additions & 0 deletions tests/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -432,6 +432,8 @@ struct Fake {
polls: Arc<AtomicUsize>,
report_organization: bool,
summary: Option<Value>,
/// Fields merged into the review, such as its cost.
review_fields: Option<Value>,
}

async fn code() -> Json<Value> {
Expand Down Expand Up @@ -532,6 +534,11 @@ async fn review(State(fake): State<Fake>, 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()
}

Expand Down Expand Up @@ -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(
Expand Down