diff --git a/openapi.public.json b/openapi.public.json index 7ab1d71..be32a15 100644 --- a/openapi.public.json +++ b/openapi.public.json @@ -263,6 +263,22 @@ ], "type": "string" }, + "ApprovalGap": { + "properties": { + "assessment_id": { + "format": "uuid", + "type": "string" + }, + "code": { + "type": "string" + } + }, + "required": [ + "assessment_id", + "code" + ], + "type": "object" + }, "AssessmentProjection": { "properties": { "assessment_id": { @@ -457,6 +473,36 @@ } ] }, + "CaptureState": { + "description": "How the capture ended.", + "oneOf": [ + { + "const": "PENDING", + "description": "Still waiting for an authorized execution or a decidable look.", + "type": "string" + }, + { + "const": "RECORDED", + "description": "World recorded every deferred question.", + "type": "string" + }, + { + "const": "UNBOUND", + "description": "At least one deferred question is not bound to the execution.", + "type": "string" + }, + { + "const": "NOT_EXECUTED", + "description": "The gate never authorized the execution.", + "type": "string" + }, + { + "const": "INCOMPLETE", + "description": "The capture failed before it wrote its receipt. The gate is\n unchanged; nothing is inferred about the deferred questions.", + "type": "string" + } + ] + }, "ChangeAttributionView": { "description": "Which conditions behind a check's result the change brought, and which\n World found at the review's base revision. It sits beside the result and\n never changes it: a condition already at the base is still a condition.", "properties": { @@ -1702,7 +1748,7 @@ "type": "string" }, "kind": { - "description": "`PULL_REQUEST`, `DEPLOYMENT`, `PATCH`, a review of local changes\n sent as a patch, or `COMMIT`, a review of pushed commits.", + "description": "`PULL_REQUEST`, `DEPLOYMENT`, `PATCH`, a review of local changes\n sent as a patch, `COMMIT`, a review of pushed commits, or `FILES`,\n complete selected files at one pushed commit.", "type": "string" }, "merge_gate": { @@ -2091,7 +2137,8 @@ "PULL_REQUEST", "DEPLOYMENT", "PATCH", - "COMMIT" + "COMMIT", + "FILES" ], "type": "string" }, @@ -2172,6 +2219,67 @@ ], "type": "object" }, + "FileReviewRequest": { + "additionalProperties": false, + "description": "Whole files selected at one exact pushed commit.", + "properties": { + "commit_sha": { + "description": "The exact pushed commit whose whole files are reviewed.", + "type": "string" + }, + "paths": { + "description": "Between one and twenty exact repository-relative file paths.", + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "commit_sha", + "paths" + ], + "type": "object" + }, + "FileReviewResponse": { + "description": "What a named-file review request produced.", + "properties": { + "existing": { + "description": "True when this exact selection already had a review and that one is\n returned. Sending the same selection twice by the same person reviews it once.", + "type": "boolean" + }, + "review_id": { + "description": "The review of this selection, readable through the review and findings\n routes.", + "format": "uuid", + "type": "string" + } + }, + "required": [ + "review_id", + "existing" + ], + "type": "object" + }, + "FileScope": { + "additionalProperties": false, + "description": "The retained selection, not a digest of file contents. Its identity uses\n a version prefix and length-framed UTF-8 paths in their sorted order.", + "properties": { + "paths": { + "items": { + "type": "string" + }, + "type": "array" + }, + "paths_digest": { + "type": "string" + } + }, + "required": [ + "paths", + "paths_digest" + ], + "type": "object" + }, "FilterChoice": { "properties": { "id": { @@ -3010,6 +3118,13 @@ }, "GateState": { "properties": { + "occurrence_captures": { + "description": "The occurrence questions the gate's approval deferred, as each\n observed execution of its deployment answered them. Outcome-only\n records: none of them changes the gate or grades a prediction.", + "items": { + "$ref": "#/components/schemas/OccurrenceCapture" + }, + "type": "array" + }, "override_record": { "anyOf": [ { @@ -3027,7 +3142,8 @@ } }, "required": [ - "status" + "status", + "occurrence_captures" ], "type": "object" }, @@ -3061,6 +3177,91 @@ ], "type": "object" }, + "OccurrenceCapture": { + "description": "The capture of one observed execution of a gate's deployment.", + "properties": { + "approval_gaps": { + "description": "Assessments whose approval could defer nothing, with the reason.", + "items": { + "$ref": "#/components/schemas/ApprovalGap" + }, + "type": "array" + }, + "detail": { + "type": [ + "string", + "null" + ] + }, + "occurrence_key": { + "type": [ + "string", + "null" + ] + }, + "questions": { + "items": { + "$ref": "#/components/schemas/OccurrenceQuestion" + }, + "type": "array" + }, + "state": { + "$ref": "#/components/schemas/CaptureState" + } + }, + "required": [ + "state", + "approval_gaps", + "questions" + ], + "type": "object" + }, + "OccurrenceQuestion": { + "description": "One deferred question as the gate presents it.", + "properties": { + "assessment_id": { + "format": "uuid", + "type": "string" + }, + "code": { + "description": "World's binding or refusal code, or the control plane's own gap.", + "type": [ + "string", + "null" + ] + }, + "family_key": { + "type": "string" + }, + "family_version": { + "format": "int32", + "type": "integer" + }, + "observed_result": { + "description": "World's observed result once it recorded the question.", + "type": [ + "string", + "null" + ] + }, + "outcome_id": { + "type": [ + "string", + "null" + ] + }, + "state": { + "$ref": "#/components/schemas/QuestionState" + } + }, + "required": [ + "assessment_id", + "family_key", + "family_version", + "state" + ], + "type": "object" + }, "OpenFindingCounts": { "properties": { "serious": { @@ -3590,6 +3791,31 @@ ], "type": "object" }, + "QuestionState": { + "description": "Where one deferred question stands.", + "oneOf": [ + { + "const": "PENDING", + "description": "World has stored no record yet: the execution is not yet decidable\n inside the question's window.", + "type": "string" + }, + { + "const": "RECORDED", + "description": "World recorded what the execution was observed to do.", + "type": "string" + }, + { + "const": "UNBOUND", + "description": "The question is not bound to the execution: World's binding code, its\n refusal of the replay, or the control plane's own gap says why.", + "type": "string" + }, + { + "const": "NOT_EXECUTED", + "description": "The gate never authorized the execution, so nothing ran to observe.", + "type": "string" + } + ] + }, "RefusedEnvironment": { "description": "An environment a refusal names. `external_key` is how its pages are\n addressed.", "properties": { @@ -4151,7 +4377,7 @@ "type": "string" }, "kind": { - "description": "`PULL_REQUEST`, `DEPLOYMENT`, `PATCH`, a review of local changes\n sent as a patch, or `COMMIT`, a review of pushed commits.", + "description": "`PULL_REQUEST`, `DEPLOYMENT`, `PATCH`, a review of local changes\n sent as a patch, `COMMIT`, a review of pushed commits, or `FILES`,\n complete selected files at one pushed commit.", "type": "string" }, "public_key": { @@ -4377,7 +4603,7 @@ "$ref": "#/components/schemas/ExportReviewKind" } ], - "description": "Whether the review analyzes a pull request, a deployment, a local patch or pushed\n commits." + "description": "Whether the review analyzes a pull request, a deployment, a local patch, pushed\n commits or selected whole files." }, "organization_id": { "description": "The organization that owns the review.", @@ -5014,6 +5240,33 @@ ], "type": "object" }, + "StopResponse": { + "description": "What stopping a review recorded.", + "properties": { + "review_id": { + "format": "uuid", + "type": "string" + }, + "status": { + "description": "Always `STOPPED`: the review's status once the stop is committed.", + "type": "string" + }, + "stopped_at": { + "format": "date-time", + "type": "string" + }, + "stopped_by": { + "$ref": "#/components/schemas/ActorView" + } + }, + "required": [ + "review_id", + "status", + "stopped_by", + "stopped_at" + ], + "type": "object" + }, "SubjectAuthorization": { "description": "One assessment's authorization of one subject, by identity.\n\n The display name is not the answer on its own: an environment's external key\n is unique within its organization and a display name is mutable metadata,\n so two environments of one review can carry the same one.\n Collapsing to it would leave a reader unable to tell which assessment\n authorized the subject and which one gapped, which is the confusion this\n field exists to remove.", "properties": { @@ -5067,6 +5320,17 @@ "null" ] }, + "file_scope": { + "anyOf": [ + { + "$ref": "#/components/schemas/FileScope" + }, + { + "type": "null" + } + ], + "description": "Whole-file selection at the pinned revision; absent for comparisons." + }, "id": { "description": "The subject's stable identifier. It holds across a poll refresh even\n when a concurrently populated subject shifts this response's\n `(kind, id)` order: a client keying its own local UI state (an open\n disclosure, a focused control) by array index would otherwise lose\n that state to a reorder that changed nothing it owns.", "format": "uuid", @@ -5813,6 +6077,84 @@ "x-proofline-token-scope": "reviews:request" } }, + "/api/v1/organizations/{org_id}/repositories/{repo_id}/file-reviews": { + "post": { + "description": "Reviews up to twenty exact file paths at one pushed commit. Requires live GitHub read access and verifies every path at that commit. The retained selection is immutable; a repeat by the same person returns its review. Results remain in Proofline and are never posted to GitHub.", + "operationId": "request_file_review", + "parameters": [ + { + "in": "path", + "name": "org_id", + "required": true, + "schema": { + "format": "uuid", + "type": "string" + }, + "style": "simple" + }, + { + "in": "path", + "name": "repo_id", + "required": true, + "schema": { + "format": "uuid", + "type": "string" + }, + "style": "simple" + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/FileReviewRequest" + } + } + }, + "description": "Whole files selected at one exact pushed commit.", + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/FileReviewResponse" + } + } + }, + "description": "What a named-file review request produced." + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RunNowRefused" + } + } + }, + "description": "A run-now request that created nothing, as the 400 it is answered with.\n\n The refusal is a configuration fact, not a failure, and it is still sent\n as an RFC 9457 problem: `title`, `status` and `detail` are what a client\n that knows only problems shows, and `repository_name` and `refusal` are\n the extension members a client that knows refusals links from. During a\n rollout a page loaded from the previous bundle keeps working against\n this server, because a refusal was a 400 with a `detail` before too." + }, + "default": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "An RFC 9457 problem; the HTTP status remains authoritative." + } + }, + "security": [ + { + "bearerAuth": [] + } + ], + "summary": "Review selected whole files", + "x-proofline-token-scope": "reviews:request" + } + }, "/api/v1/organizations/{org_id}/repositories/{repo_id}/patch-reviews": { "post": { "description": "Reviews a unified diff against a commit GitHub has in the repository, and returns that patch's review when one exists. The review reads only that commit and the patch, and is never posted to a pull request. Requires live GitHub read access; the same patch on the same base always returns the same review.", @@ -6824,6 +7166,63 @@ "summary": "Get review routing", "x-proofline-token-scope": "reviews:read" } + }, + "/api/v1/organizations/{org_id}/reviews/{review_id}/stop": { + "post": { + "description": "Stops the holder's own pending or running withheld patch, commit or named-file review. Requires a personal or CLI device token with live GitHub read access to the review's repository. Organization, CI job and MCP OAuth tokens cannot stop reviews. The stopped review retains its findings and exact code identity; requesting the same input returns that stopped review.", + "operationId": "stop_review", + "parameters": [ + { + "in": "path", + "name": "org_id", + "required": true, + "schema": { + "format": "uuid", + "type": "string" + }, + "style": "simple" + }, + { + "in": "path", + "name": "review_id", + "required": true, + "schema": { + "format": "uuid", + "type": "string" + }, + "style": "simple" + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/StopResponse" + } + } + }, + "description": "What stopping a review recorded." + }, + "default": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "An RFC 9457 problem; the HTTP status remains authoritative." + } + }, + "security": [ + { + "bearerAuth": [] + } + ], + "summary": "Stop your local review", + "x-proofline-token-scope": "reviews:request" + } } } } diff --git a/src/api.rs b/src/api.rs index 6cee97f..ef29ee7 100644 --- a/src/api.rs +++ b/src/api.rs @@ -11,8 +11,9 @@ use url::Url; use uuid::Uuid; use crate::model::{ - CommitReviewRequest, CommitReviewResponse, PatchReviewRequest, PatchReviewResponse, - RepositoryNames, ReviewDetail, ReviewPage, RunNowMode, RunNowRequest, RunNowResponse, + CommitReviewRequest, CommitReviewResponse, FileReviewRequest, FileReviewResponse, + PatchReviewRequest, PatchReviewResponse, RepositoryNames, ReviewDetail, ReviewPage, RunNowMode, + RunNowRequest, RunNowResponse, StopResponse, }; use crate::origin::Origin; use crate::text::terminal_safe; @@ -472,6 +473,24 @@ impl Api { Err(self.http.problem(&reply)) } + /// Requests whole-file review of a selection at one pushed commit. + pub async fn request_file_review( + &self, + repository_id: Uuid, + request: &FileReviewRequest, + ) -> Result { + let repository = repository_id.to_string(); + let url = self.url(&["repositories", &repository, "file-reviews"]); + let (reply, _) = self + .http + .send(self.request(Method::POST, url).json(request)) + .await?; + if reply.status.is_success() { + return self.decode(&reply.body); + } + Err(self.http.problem(&reply)) + } + /// Requests a review of the change from one pushed commit to another. One /// attempt; the server returns the existing review of the same commits. pub async fn request_commit_review( @@ -491,6 +510,31 @@ impl Api { Err(self.http.problem(&reply)) } + /// Stops the holder's own local review in one bounded attempt. A refusal + /// starts no replacement review, and the client never repeats the POST. + pub async fn stop_review( + &self, + review_id: Uuid, + ) -> Result<(serde_json::Value, StopResponse), ApiError> { + let id = review_id.to_string(); + let (reply, _) = self + .http + .send(self.request(Method::POST, self.url(&["reviews", &id, "stop"]))) + .await?; + if !reply.status.is_success() { + return Err(self.http.problem(&reply)); + } + let raw: serde_json::Value = self.decode(&reply.body)?; + let stopped: StopResponse = serde_json::from_value(raw.clone()) + .map_err(|error| self.http.protocol(error.to_string()))?; + if stopped.review_id != review_id || stopped.status != "STOPPED" { + return Err(self + .http + .protocol("the stop response does not confirm this review is STOPPED")); + } + Ok((raw, stopped)) + } + /// The console page for a review, which resolves the organization and /// review IDs to the current display names after sign-in. pub fn review_url(&self, review_id: Uuid) -> Url { diff --git a/src/git.rs b/src/git.rs index ced056e..6df5fb8 100644 --- a/src/git.rs +++ b/src/git.rs @@ -39,6 +39,10 @@ pub enum GitError { NoParent(String), #[error("{0:?} is not a range; write it as BASE..HEAD")] NotRange(String), + #[error("name between 1 and 20 exact repository-relative file paths")] + FileCount, + #[error("{0:?} is not a regular tracked file at commit {1}; no review was requested")] + NotTrackedFile(String, String), } /// Two exact commits of a pushed change: the head, and the base it is @@ -66,6 +70,57 @@ async fn resolve(dir: &Path, revision: &str) -> Result { commit_sha(String::from_utf8_lossy(&output).trim()) } +/// Resolve a whole-file selection once, using only the named commit's tree. +/// Working-tree and index contents never contribute to this request. +pub async fn named_files( + dir: &Path, + revision: &str, + paths: &[String], +) -> Result<(String, Vec), GitError> { + if paths.is_empty() || paths.len() > 20 { + return Err(GitError::FileCount); + } + let commit = resolve(dir, revision).await?; + let mut selected = paths.to_vec(); + selected.sort(); + selected.dedup(); + for path in &selected { + if path.chars().count() > 1_000 + || path.contains('\0') + || path.split('/').any(|part| matches!(part, "" | "." | "..")) + { + return Err(GitError::NotTrackedFile(path.clone(), commit.clone())); + } + let entries = git_in( + dir, + None, + &[ + "--literal-pathspecs", + "ls-tree", + "-z", + "--full-tree", + &commit, + "--", + path, + ], + ) + .await?; + let found = entries.split(|byte| *byte == 0).any(|entry| { + let Some(separator) = entry.iter().position(|byte| *byte == b'\t') else { + return false; + }; + let (metadata, remainder) = entry.split_at(separator); + let found = &remainder[1..]; + found == path.as_bytes() + && (metadata.starts_with(b"100644 blob ") || metadata.starts_with(b"100755 blob ")) + }); + if !found { + return Err(GitError::NotTrackedFile(path.clone(), commit.clone())); + } + } + Ok((commit, selected)) +} + /// The change one commit makes: the commit against its first parent. pub async fn pushed_commit(dir: &Path, revision: &str) -> Result { let head_commit_sha = resolve(dir, revision).await?; diff --git a/src/lib.rs b/src/lib.rs index 1c1c5ba..ce648d2 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -33,7 +33,8 @@ use uuid::Uuid; use crate::api::{Api, ApiError, Http}; use crate::credentials::{Credential, Source}; use crate::model::{ - CodeAssessment, CommitReviewRequest, OpenItems, PatchReviewRequest, ReviewDetail, ReviewSummary, + CodeAssessment, CommitReviewRequest, FileReviewRequest, OpenItems, PatchReviewRequest, + ReviewDetail, ReviewSummary, }; use crate::origin::{DEFAULT_ORIGIN, Origin}; use crate::outcome::Outcome; @@ -42,7 +43,7 @@ use crate::severity::Severity; const FIRST_POLL_SECONDS: u64 = 5; const LONGEST_POLL_SECONDS: u64 = 60; const SEARCH_PAGES: usize = 10; -/// What `findings` and `review` need. The approval page shows each one +/// What `findings`, `review` and `stop` need. The approval page shows each one /// and can narrow them. const DEFAULT_SCOPES: [&str; 3] = ["reviews:read", "findings:read", "reviews:request"]; @@ -50,7 +51,7 @@ const DEFAULT_SCOPES: [&str; 3] = ["reviews:read", "findings:read", "reviews:req #[command( name = "proofline", version, - about = "Read and request Proofline reviews from a terminal" + about = "Read, request and stop Proofline reviews from a terminal" )] pub struct Cli { /// Proofline console origin. @@ -84,6 +85,8 @@ enum Command { /// Review the checkout's local changes, pushed commits, or an open pull /// request's current head. Review(ReviewArgs), + /// Stop your own pending or running local patch, pushed-commit or named-file review. + Stop(StopArgs), /// Show the findings of the latest review of a commit or pull request. Findings(FindingsArgs), /// Forward a coding agent's stdio messages to this console's MCP server. @@ -165,6 +168,15 @@ struct OutputArgs { timeout: u64, } +#[derive(Debug, Args)] +struct StopArgs { + /// The review ID returned by `review --no-wait`. + review_id: Uuid, + /// Print the server's stop acknowledgment as JSON. + #[arg(long)] + json: bool, +} + #[derive(Debug, Args)] struct LocalSelectionArgs { /// Review the original index against the base, excluding unstaged changes. @@ -188,12 +200,17 @@ struct ReviewArgs { local_selection: LocalSelectionArgs, /// Review the change this pushed commit makes against its first parent. /// The name is resolved once in the checkout; GitHub must have both commits. + /// With --files, review complete selected files at that commit instead. #[arg( long, value_name = "REVISION", conflicts_with_all = ["pr", "range", "staged", "include_untracked", "allow_path"] )] commit: Option, + /// Review the complete contents of up to twenty tracked files at --commit. + #[arg(long, value_name = "PATH", num_args = 1..=20, requires = "commit", + conflicts_with_all = ["pr", "range", "staged", "include_untracked", "allow_path"])] + files: Vec, /// Review the change from BASE to HEAD, both pushed, BASE an ancestor of /// HEAD. The names are resolved once in the checkout. #[arg( @@ -320,6 +337,17 @@ pub async fn run(cli: Cli, token: Option) -> anyhow::Result { + let api = connect(Http::new(origin)?, token, cli.org).await?; + let (raw, stopped) = api.stop_review(args.review_id).await?; + let mut stdout = std::io::stdout().lock(); + if args.json { + writeln!(stdout, "{}", serde_json::to_string(&raw)?)?; + } else { + writeln!(stdout, "Stopped review {}.", stopped.review_id)?; + } + Ok(Verdict::Done) + } Command::Findings(args) => { if let Some(head) = &args.selector.head { git::commit_sha(head)?; @@ -568,6 +596,9 @@ async fn latest( async fn review(api: &Api, args: &ReviewArgs) -> anyhow::Result { let Some(number) = args.pr else { + if !args.files.is_empty() { + return review_files(api, args).await; + } if args.commit.is_some() || args.range.is_some() { return review_pushed(api, args).await; } @@ -651,6 +682,29 @@ async fn review_local(api: &Api, args: &ReviewArgs) -> anyhow::Result { finish(api, requested.review_id, args).await } +async fn review_files(api: &Api, args: &ReviewArgs) -> anyhow::Result { + let revision = args + .commit + .as_deref() + .context("--files requires --commit")?; + let (commit_sha, paths) = + git::named_files(std::path::Path::new("."), revision, &args.files).await?; + let (name, repository_id) = connected_repository(api, &args.repository).await?; + let request = FileReviewRequest { commit_sha, paths }; + let requested = api.request_file_review(repository_id, &request).await?; + say(&format!( + "{} whole-file review of {} selected files in {name} at {}.", + if requested.existing { + "Found the existing" + } else { + "Requested a" + }, + request.paths.len(), + request.commit_sha + )); + finish(api, requested.review_id, args).await +} + /// Reviews pushed commits: one commit against its parent, or a range. The /// names are resolved to exact commits once, here; nothing leaves the /// machine but the two SHAs, because GitHub already has the code. diff --git a/src/model.rs b/src/model.rs index f1fc074..dc0dcf3 100644 --- a/src/model.rs +++ b/src/model.rs @@ -62,6 +62,22 @@ pub struct ReviewDetail { pub pull_request_number: Option, pub repository_full_name: Option, pub run_number: Option, + #[serde(default)] + pub subjects: Vec, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct ReviewSubject { + pub kind: String, + pub role: String, + pub file_scope: Option, +} + +/// Selection identity at one commit, not a digest of file contents. +#[derive(Debug, Deserialize, Serialize)] +pub struct FileScope { + pub paths: Vec, + pub paths_digest: String, } /// A malformed or newer CODE record cannot establish completeness. Keep it @@ -194,6 +210,12 @@ pub struct RunNowResponse { pub automatic_reviews_paused: bool, } +#[derive(Debug, Deserialize, Serialize)] +pub struct StopResponse { + pub review_id: Uuid, + pub status: String, +} + /// Whether the server may reuse a settled review of the live pull-request head. #[derive(Debug, Clone, Copy, Default, Deserialize, Serialize, PartialEq, Eq)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] @@ -241,6 +263,20 @@ pub struct PatchReviewResponse { pub patch_digest: String, } +/// Complete selected files at one exact pushed commit. +#[derive(Debug, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct FileReviewRequest { + pub commit_sha: String, + pub paths: Vec, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct FileReviewResponse { + pub review_id: Uuid, + pub existing: bool, +} + /// Pushed commits to review: two exact commits GitHub has, the base an /// ancestor of the head. #[derive(Debug, Deserialize, Serialize)] diff --git a/src/outcome.rs b/src/outcome.rs index 1d03126..bc906ff 100644 --- a/src/outcome.rs +++ b/src/outcome.rs @@ -197,6 +197,7 @@ mod tests { assessment_count: count, assessments, code_assessment: None, + subjects: Vec::new(), base_commit_sha: None, head_commit_sha: None, open_items: None, diff --git a/src/render.rs b/src/render.rs index c893f74..c7a7d18 100644 --- a/src/render.rs +++ b/src/render.rs @@ -131,6 +131,23 @@ pub fn review(review: &ReviewDetail, state: Option, url: &Url) -> Strin ); out.push(format!("{subject}{run}{head}: {status}")); out.push(url.to_string()); + if review.kind == "FILES" + && let Some(scope) = review + .subjects + .iter() + .find(|subject| subject.role == "PRIMARY" && subject.kind == "GIT_REVISION") + .and_then(|subject| subject.file_scope.as_ref()) + { + out.push(format!( + "Selected files: {}", + scope + .paths + .iter() + .map(|path| one_line(path)) + .collect::>() + .join(", ") + )); + } if let Some(code) = outcome::code_assessment(review) { out.push(String::new()); code_assessment(&mut out, code); @@ -160,6 +177,7 @@ mod tests { status: "COMPLETED".to_owned(), assessment_count: 1, code_assessment: None, + subjects: Vec::new(), assessments: vec![Assessment { id: uuid::Uuid::nil(), environment_display_name: "production".to_owned(), diff --git a/tests/contract.rs b/tests/contract.rs index 7deca8b..9088aed 100644 --- a/tests/contract.rs +++ b/tests/contract.rs @@ -5,9 +5,10 @@ use std::process::Command; use proofline_cli::model::{ Assessment, Check, Checks, CodeAssessment, CommitReviewRequest, CommitReviewResponse, - EvidenceRef, FilterChoice, Finding, OpenItems, PatchReviewRequest, PatchReviewResponse, - RepositoryName, RepositoryNames, ReviewDetail, ReviewFilters, ReviewPage, ReviewSummary, - RunNowMode, RunNowRequest, RunNowResponse, + EvidenceRef, FileReviewRequest, FileReviewResponse, FileScope, FilterChoice, Finding, + OpenItems, PatchReviewRequest, PatchReviewResponse, RepositoryName, RepositoryNames, + ReviewDetail, ReviewFilters, ReviewPage, ReviewSubject, ReviewSummary, RunNowMode, + RunNowRequest, RunNowResponse, StopResponse, }; use serde::Serialize; use serde::de::DeserializeOwned; @@ -165,6 +166,11 @@ fn types_match_the_public_contract() { holds::("PatchReviewResponse"); holds::("CommitReviewRequest"); holds::("CommitReviewResponse"); + holds::("StopResponse"); + holds::("FileReviewRequest"); + holds::("FileReviewResponse"); + holds::("FileScope"); + holds::("SubjectView"); // Schema display has no console, credentials or checkout to read. It uses // the bundled public contract, even when the configured origin is invalid. @@ -224,6 +230,10 @@ fn operations_the_cli_calls_exist() { ("get", "/api/v1/organizations/{org_id}/reviews"), ("get", "/api/v1/organizations/{org_id}/reviews/{review_id}"), ("get", "/api/v1/organizations/{org_id}/repository-names"), + ( + "post", + "/api/v1/organizations/{org_id}/reviews/{review_id}/stop", + ), ( "post", "/api/v1/organizations/{org_id}/repositories/{repo_id}/pull-requests/{number}/review", @@ -236,6 +246,10 @@ fn operations_the_cli_calls_exist() { "post", "/api/v1/organizations/{org_id}/repositories/{repo_id}/commit-reviews", ), + ( + "post", + "/api/v1/organizations/{org_id}/repositories/{repo_id}/file-reviews", + ), ] { assert!( document["paths"][path][method].is_object(), diff --git a/tests/http.rs b/tests/http.rs index 2049322..68b8421 100644 --- a/tests/http.rs +++ b/tests/http.rs @@ -486,6 +486,97 @@ async fn a_refused_review_request_names_the_reason_without_terminal_control() { assert_eq!(detail, "No environment links acme/web.\u{FFFD}[2J"); } +#[tokio::test] +async fn stopping_uses_one_post_and_confirms_the_selected_stopped_review() { + let review_id = Uuid::parse_str(SELECTED_REVIEW).unwrap(); + let acknowledgment = json!({ + "review_id": SELECTED_REVIEW, + "status": "STOPPED", + "stopped_by": {"github_user_id": 123, "login": "reviewer"}, + "stopped_at": "2026-01-01T00:00:00Z", + "a_compatible_addition": true, + }); + let mut wrong_review = acknowledgment.clone(); + wrong_review["review_id"] = json!(Uuid::nil()); + let mut running = acknowledgment.clone(); + running["status"] = json!("RUNNING"); + for (status, body, json_output, success) in [ + (StatusCode::OK, acknowledgment.clone(), false, true), + (StatusCode::OK, acknowledgment.clone(), true, true), + (StatusCode::OK, wrong_review, true, false), + (StatusCode::OK, running, true, false), + ( + StatusCode::FORBIDDEN, + json!({"detail": "live read access is required\u{1b}[2J"}), + true, + false, + ), + ( + StatusCode::SERVICE_UNAVAILABLE, + json!({"detail": "GitHub could not confirm read access"}), + false, + false, + ), + (StatusCode::FOUND, json!({}), false, false), + ] { + let requests = Arc::new(AtomicUsize::new(0)); + let observed = Arc::clone(&requests); + let response_body = body; + let app = Router::new().route( + &format!("/api/v1/organizations/{ORG}/reviews/{{id}}/stop"), + post( + move |Path(id): Path, headers: HeaderMap, body: Bytes| { + let observed = Arc::clone(&observed); + let response_body = response_body.clone(); + async move { + assert_eq!(id, review_id); + assert_eq!(headers[header::AUTHORIZATION], format!("Bearer {TOKEN}")); + assert!(body.is_empty()); + observed.fetch_add(1, Ordering::SeqCst); + (status, Json(response_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 mut args = vec!["stop", SELECTED_REVIEW]; + if json_output { + args.push("--json"); + } + let output = cli(&origin, &args).await; + assert_eq!(output.status.success(), success, "{status}: {output:?}"); + assert_eq!(requests.load(Ordering::SeqCst), 1, "{status}: {output:?}"); + assert!( + !output + .stdout + .windows(TOKEN.len()) + .any(|bytes| bytes == TOKEN.as_bytes()) + ); + assert!( + !output + .stderr + .windows(TOKEN.len()) + .any(|bytes| bytes == TOKEN.as_bytes()) + ); + assert!(!output.stderr.contains(&0x1b)); + if success && json_output { + let returned: Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(returned, acknowledgment); + } else if success { + let text = String::from_utf8(output.stdout).unwrap(); + assert!(text.contains(SELECTED_REVIEW)); + } else { + assert!( + output.stdout.is_empty(), + "a refused stop cannot acknowledge success" + ); + } + server.abort(); + } +} + #[tokio::test] async fn an_incomplete_review_is_not_success_in_either_output() { let origin = serve(Fake::default()).await.to_string(); diff --git a/tests/local_patch.rs b/tests/local_patch.rs index 2087e81..538e023 100644 --- a/tests/local_patch.rs +++ b/tests/local_patch.rs @@ -25,6 +25,7 @@ struct Fixture { requests: Arc, uploads: Arc>>, commit_requests: Arc>>, + file_requests: Arc>>, authorized: bool, } @@ -77,6 +78,17 @@ async fn commit_review( Json(json!({ "review_id": REVIEW, "existing": false })) } +async fn file_review( + State(fixture): State, + headers: HeaderMap, + Json(body): Json, +) -> Json { + assert!(fixture.authorized); + assert_eq!(headers[header::AUTHORIZATION], format!("Bearer {TOKEN}")); + fixture.file_requests.lock().unwrap().push(body); + Json(json!({ "review_id": REVIEW, "existing": false })) +} + struct Server { origin: String, fixture: Fixture, @@ -90,6 +102,7 @@ impl Server { requests: Arc::default(), uploads: Arc::default(), commit_requests: Arc::default(), + file_requests: Arc::default(), authorized, }; let app = Router::new() @@ -105,6 +118,10 @@ impl Server { &format!("/api/v1/organizations/{ORG}/repositories/{REPOSITORY}/commit-reviews"), post(commit_review), ) + .route( + &format!("/api/v1/organizations/{ORG}/repositories/{REPOSITORY}/file-reviews"), + post(file_review), + ) .fallback(|| async { StatusCode::NOT_FOUND }) .with_state(fixture.clone()) .layer(middleware::from_fn_with_state(fixture.clone(), observe)); @@ -616,6 +633,59 @@ async fn pushed_commits_send_two_exact_shas_and_no_patch() { server.close().await; } +/// Even the root commit is a valid whole-file subject; the index and working +/// tree cannot change its selected paths or contribute source bytes. +#[tokio::test] +async fn named_files_send_one_pinned_commit_and_ignore_local_changes() { + let checkout = Checkout::new(&[("kept.txt", "committed\n"), ("other.txt", "other\n")]).await; + checkout + .write("kept.txt", "unpushed text must not leave this checkout\n") + .await; + checkout.write("untracked.txt", "local only\n").await; + let before = checkout.index().await; + let server = Server::start(true).await; + for flags in [ + vec!["--files", "kept.txt"], + vec!["--commit", "HEAD", "--files", "untracked.txt"], + vec!["--commit", "HEAD", "--files", "kept.txt", "--staged"], + vec!["--range", "HEAD~1..HEAD", "--files", "kept.txt"], + vec!["--commit", "HEAD", "--files", "../kept.txt"], + ] { + let output = checkout.review(&server, &[], &flags).await; + assert!(!output.status.success(), "{flags:?}"); + server.assert_no_requests(); + } + let output = checkout + .review( + &server, + &[], + &[ + "--commit", + "HEAD", + "--files", + "other.txt", + "kept.txt", + "kept.txt", + ], + ) + .await; + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + assert_eq!( + *server.fixture.file_requests.lock().unwrap(), + vec![json!({ + "commit_sha": checkout.base, "paths": ["kept.txt", "other.txt"], + })] + ); + assert!(server.fixture.uploads.lock().unwrap().is_empty()); + assert!(server.fixture.commit_requests.lock().unwrap().is_empty()); + assert_eq!(checkout.index().await, before); + server.close().await; +} + #[tokio::test] async fn a_local_override_still_requires_repository_authorization() { let checkout = Checkout::new(&[]).await;