diff --git a/README.md b/README.md index c56770c..ac27bda 100644 --- a/README.md +++ b/README.md @@ -29,7 +29,7 @@ Native knowledge, plan, fix and configuration commands send the selected organiz `proofline review --path src/main.rs` reviews only that file's local changes against the normal merge-base. The path is literal and repository-relative; the command refuses directories, globs, and `..`. Combine it with `--staged` to read the index, or `--include-untracked` to select a new, non-ignored file. The command preserves the real index and applies the usual secret preflight. You cannot combine `--path` with pushed-commit, range, or pull-request review. -`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 check `owner/name`, or the Git remote's owner and name, against the organization's reviewed repositories, then send the API the name without its owner. A repository with no reviews in the organization exits nonzero. +`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` follows the endpoint's opaque cursors to read the full history in server order. History traversal is bounded to 100 pages and fails rather than returning a partial result when the server omits, repeats or malforms a continuation cursor. Both commands check `owner/name`, or the Git remote's owner and name, against the organization's reviewed repositories, then send the API the name without its owner. A repository with no reviews in the organization exits nonzero. `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. diff --git a/src/api.rs b/src/api.rs index 3a78004..f161a88 100644 --- a/src/api.rs +++ b/src/api.rs @@ -1,6 +1,7 @@ //! The review API over HTTP: bearer authentication, bounded bodies, explicit //! timeouts, no redirects, and bounded retries for reads. +use std::collections::HashSet; use std::time::Duration; use reqwest::{Method, StatusCode, header}; @@ -24,6 +25,8 @@ const MAX_BODY: usize = 8 * 1024 * 1024; const REQUEST_TIMEOUT: Duration = Duration::from_secs(30); const READ_ATTEMPTS: u32 = 4; const MAX_RETRY_AFTER: u64 = 60; +const HISTORY_PAGE_SIZE: &str = "50"; +const HISTORY_MAX_PAGES: usize = 100; #[derive(Debug, thiserror::Error)] pub enum ApiError { @@ -444,13 +447,102 @@ impl Api { self.get(url).await } + /// Reads every recorded run for one pull request, following opaque cursors. + /// + /// The endpoint is paginated even though the CLI command presents one history. + /// Keep the traversal bounded and fail closed: an invalid cursor or exhausted + /// page budget must never look like a complete history to the caller. pub(crate) async fn history( &self, repository: &str, number: u64, ) -> Result { - self.get(self.url_list_pull_request_reviews(repository, &number.to_string())) - .await + let mut cursor: Option = None; + let mut seen = HashSet::new(); + let mut history: Option = None; + + for _ in 0..HISTORY_MAX_PAGES { + let mut url = + self.url_list_pull_request_reviews(repository, &number.to_string()); + { + let mut query = url.query_pairs_mut(); + query.append_pair("limit", HISTORY_PAGE_SIZE); + if let Some(cursor) = cursor.as_deref() { + query.append_pair("cursor", cursor); + } + } + + let mut page = self.get(url).await?; + let truncated = page + .get("truncated") + .and_then(serde_json::Value::as_bool) + .ok_or_else(|| self.http.protocol("pull-request history has no valid truncated flag"))?; + let next_cursor = match page.get("next_cursor") { + None | Some(serde_json::Value::Null) => None, + Some(serde_json::Value::String(value)) => Some(value.clone()), + Some(_) => { + return Err(self + .http + .protocol("pull-request history has an invalid continuation cursor")); + } + }; + + match (truncated, next_cursor.as_deref()) { + (false, None) => {} + (false, Some(_)) => { + return Err(self.http.protocol( + "pull-request history returned a continuation cursor without truncation", + )); + } + (true, Some(value)) if !value.is_empty() => { + if !seen.insert(value.to_owned()) { + return Err(self + .http + .protocol("pull-request history returned a repeated continuation cursor")); + } + } + (true, _) => { + return Err(self + .http + .protocol("pull-request history is truncated without a usable continuation cursor")); + } + } + + let page_items = page + .get_mut("items") + .and_then(serde_json::Value::as_array_mut) + .map(std::mem::take) + .ok_or_else(|| self.http.protocol("pull-request history has no items array"))?; + + match history.as_mut() { + Some(history) => { + let items = history + .get_mut("items") + .and_then(serde_json::Value::as_array_mut) + .ok_or_else(|| self.http.protocol("pull-request history accumulator is invalid"))?; + items.extend(page_items); + } + None => { + page["items"] = serde_json::Value::Array(page_items); + page["next_cursor"] = serde_json::Value::Null; + page["truncated"] = serde_json::Value::Bool(false); + history = Some(page); + } + } + + match next_cursor { + None => { + return history.ok_or_else(|| { + self.http.protocol("pull-request history returned no pages") + }); + } + Some(next) => cursor = Some(next), + } + } + + Err(self.http.protocol( + "pull-request history exceeded the 100-page safety limit before completing", + )) } pub(crate) async fn guidance(&self, repository: Uuid) -> Result { diff --git a/tests/http.rs b/tests/http.rs index eb6157d..9b1575c 100644 --- a/tests/http.rs +++ b/tests/http.rs @@ -2600,7 +2600,8 @@ async fn history_and_run_send_the_matched_name_without_its_owner() { let prefix = prefix.clone(); async move { let path = request.uri().path().to_owned(); - seen.lock().unwrap().push(path.clone()); + let uri = request.uri().to_string(); + seen.lock().unwrap().push(uri); if path == format!("{prefix}/reviews") { return Json(json!({ "items": [], @@ -2610,7 +2611,22 @@ async fn history_and_run_send_the_matched_name_without_its_owner() { })); } if path == format!("{prefix}/reviews/pr/Repo/7") { - return Json(json!({"items": [{"run_number": 2}]})); + assert_eq!(request.uri().query(), Some("limit=50")); + return Json(json!({ + "items": [{ + "id": SELECTED_REVIEW, + "kind": "PULL_REQUEST", + "status": "COMPLETED", + "created_at": "2026-11-21T00:00:00Z", + "head_commit_sha": null, + "pull_request_number": 7, + "repository_id": REPOSITORY, + "run_number": 2 + }], + "next_cursor": null, + "truncated": false, + "filters": {"repositories": []} + })); } if path == format!("{prefix}/reviews/pr/Repo/7/runs/2") { return Json(json!({"run_number": 2})); @@ -2643,7 +2659,7 @@ async fn history_and_run_send_the_matched_name_without_its_owner() { .lock() .unwrap() .drain(..) - .filter(|path| path.contains("/reviews/pr/")) + .filter(|uri| uri.contains("/reviews/pr/")) .collect::>() }; for (args, read) in [ @@ -2670,7 +2686,10 @@ async fn history_and_run_send_the_matched_name_without_its_owner() { ); assert_eq!( reads(&requests), - [format!("/api/v1/organizations/{ORG}/{read}")], + [format!( + "/api/v1/organizations/{ORG}/{read}{}", + if read == "reviews/pr/Repo/7" { "?limit=50" } else { "" } + )], "{args:?}" ); } @@ -2690,6 +2709,167 @@ async fn history_and_run_send_the_matched_name_without_its_owner() { server.abort(); } + +/// A history page keeps the same review-summary fields as the collection API. +fn history_page(run: i64, id: &str, next_cursor: Option<&str>, truncated: bool) -> Value { + json!({ + "items": [{ + "id": id, + "kind": "PULL_REQUEST", + "status": "COMPLETED", + "created_at": "2026-11-21T00:00:00Z", + "head_commit_sha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "pull_request_number": 7, + "repository_id": REPOSITORY, + "run_number": run + }], + "next_cursor": next_cursor, + "truncated": truncated, + "filters": {"repositories": []} + }) +} + +#[tokio::test] +async fn history_follows_every_cursor_and_preserves_server_order() { + let requests = Arc::new(Mutex::new(Vec::new())); + let seen = Arc::clone(&requests); + let prefix = format!("/api/v1/organizations/{ORG}"); + let app = Router::new().fallback(move |request: axum::extract::Request| { + let seen = Arc::clone(&seen); + let prefix = prefix.clone(); + async move { + let path = request.uri().path().to_owned(); + let query = request.uri().query().unwrap_or_default().to_owned(); + seen.lock().unwrap().push(format!("{path}?{query}")); + if path == format!("{prefix}/reviews") { + return Json(json!({ + "items": [], + "next_cursor": null, + "truncated": false, + "filters": {"repositories": [{"id": REPOSITORY, "name": "Owner/Repo"}]} + })); + } + if path == format!("{prefix}/reviews/pr/Repo/7") { + let (run, id, next, truncated) = match query.as_str() { + "limit=50" => ( + 3, + "00000000-0000-4000-8000-000000000003", + Some("opaque/+cursor"), + true, + ), + "limit=50&cursor=opaque%2F%2Bcursor" => ( + 2, + "00000000-0000-4000-8000-000000000002", + Some("last"), + true, + ), + "limit=50&cursor=last" => ( + 1, + "00000000-0000-4000-8000-000000000001", + None, + false, + ), + other => panic!("unexpected history query: {other}"), + }; + return Json(history_page(run, id, next, truncated)); + } + Json(json!({})) + } + }); + 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 output = cli(&origin, &["history", "--repo", "owner/repo", "--pr", "7"]).await; + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let result: Value = serde_json::from_slice(&output.stdout).unwrap(); + let runs = result["items"] + .as_array() + .unwrap() + .iter() + .map(|item| item["run_number"].as_i64().unwrap()) + .collect::>(); + assert_eq!(runs, [3, 2, 1]); + assert_eq!(result["truncated"], false); + assert_eq!(result["next_cursor"], Value::Null); + + let history_reads = requests + .lock() + .unwrap() + .iter() + .filter(|uri| uri.contains("/reviews/pr/")) + .cloned() + .collect::>(); + assert_eq!( + history_reads, + [ + format!("/api/v1/organizations/{ORG}/reviews/pr/Repo/7?limit=50"), + format!( + "/api/v1/organizations/{ORG}/reviews/pr/Repo/7?limit=50&cursor=opaque%2F%2Bcursor" + ), + format!("/api/v1/organizations/{ORG}/reviews/pr/Repo/7?limit=50&cursor=last"), + ] + ); + server.abort(); +} + +#[tokio::test] +async fn history_fails_closed_on_bad_cursors_and_the_page_limit() { + for failure in ["missing", "repeated", "page-limit"] { + let history_requests = Arc::new(AtomicUsize::new(0)); + let count = Arc::clone(&history_requests); + let prefix = format!("/api/v1/organizations/{ORG}"); + let app = Router::new().fallback(move |request: axum::extract::Request| { + let count = Arc::clone(&count); + let prefix = prefix.clone(); + async move { + let path = request.uri().path().to_owned(); + if path == format!("{prefix}/reviews") { + return Json(json!({ + "items": [], + "next_cursor": null, + "truncated": false, + "filters": {"repositories": [{"id": REPOSITORY, "name": "Owner/Repo"}]} + })); + } + if path == format!("{prefix}/reviews/pr/Repo/7") { + let index = count.fetch_add(1, Ordering::SeqCst); + let next = match failure { + "missing" => None, + "repeated" => Some("loop".to_owned()), + _ => Some(format!("cursor-{index}")), + }; + return Json(history_page(1, SELECTED_REVIEW, next.as_deref(), true)); + } + Json(json!({})) + } + }); + 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 output = cli(&origin, &["history", "--repo", "owner/repo", "--pr", "7"]).await; + assert!(!output.status.success(), "{failure}"); + assert!(output.stdout.is_empty(), "{failure}"); + assert!( + String::from_utf8_lossy(&output.stderr).contains("pull-request history"), + "{failure}: {}", + String::from_utf8_lossy(&output.stderr) + ); + let expected = match failure { + "missing" => 1, + "repeated" => 2, + _ => 100, + }; + assert_eq!(history_requests.load(Ordering::SeqCst), expected, "{failure}"); + server.abort(); + } +} + /// The CLI in `directory` with `git` on its path, for commands that read the /// checkout's remote. async fn cli_with_git(