diff --git a/docs/api/openapi.json b/docs/api/openapi.json index 87a99409c..66a88a633 100644 --- a/docs/api/openapi.json +++ b/docs/api/openapi.json @@ -2963,6 +2963,16 @@ ], "type": "string" }, + "session_id": { + "description": "The review job that wrote this review: its session\n(`/api/reviewer/session?id=`). Null on older reviews.", + "examples": [ + "3f2c9a1e-5b7d-4c8e-9a0b-1c2d3e4f5a6b" + ], + "type": [ + "string", + "null" + ] + }, "sk": { "description": "The review's key: pass it as `sk` to get the review.", "examples": [ @@ -3309,6 +3319,16 @@ ], "type": "string" }, + "review_sk": { + "description": "The review this session wrote (its `sk`, for `/api/reviewer/review`).\nNull while it runs, when it ended without one, and on older sessions.", + "examples": [ + "REVIEW#acme/web#000318#2026-10-22T14:20:05+00:00" + ], + "type": [ + "string", + "null" + ] + }, "review_url": { "description": "The review posted on GitHub; empty when nothing new was posted.", "examples": [ @@ -3607,6 +3627,17 @@ "minimum": 0, "type": "integer" }, + "checks": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/RunChecks", + "description": "The CI checks on the head of the run's open pull request, read from\nGitHub (reused for up to a minute). Null when the run has no open\npull request or GitHub can't be read." + } + ] + }, "close_reason": { "description": "Why it was closed.", "examples": [ @@ -3884,6 +3915,17 @@ "null" ] }, + "pr_review": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/RunPrReview", + "description": "CoderHelm's latest review verdict on the run's pull request. Null\nbefore any." + } + ] + }, "pr_url": { "description": "The pull request the run opened.", "examples": [ @@ -4184,6 +4226,165 @@ ], "type": "object" }, + "RunCheck": { + "description": "One check on the pull request's head.", + "properties": { + "completed_at": { + "description": "When it ended (RFC 3339). Null while it runs.", + "examples": [ + "2026-10-22T14:21:40Z" + ], + "type": [ + "string", + "null" + ] + }, + "conclusion": { + "description": "GitHub's word for how it ended (`success`, `failure`, `neutral`,\n`cancelled`, `timed_out`, `skipped`, `error`, ...). Null until it ends.", + "examples": [ + "success" + ], + "type": [ + "string", + "null" + ] + }, + "name": { + "description": "The check's name (a check run's name or a commit status's context).", + "examples": [ + "build" + ], + "type": "string" + }, + "required": { + "description": "The branch's rules require it before merging. False when they can't\nbe read.", + "examples": [ + true + ], + "type": "boolean" + }, + "started_at": { + "description": "When it started (RFC 3339), when known.", + "examples": [ + "2026-10-22T14:18:00Z" + ], + "type": [ + "string", + "null" + ] + }, + "state": { + "description": "`passed`, `failed`, `running`, `queued` or `skipped`. A required check\nthat hasn't reported yet is `queued`.", + "examples": [ + "passed" + ], + "type": "string" + }, + "url": { + "description": "Its page on GitHub or in the CI system.", + "examples": [ + "https://github.com/acme/web/actions/runs/1/job/2" + ], + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "name", + "state", + "required" + ], + "type": "object" + }, + "RunCheckCounts": { + "description": "How many checks are in each state.", + "properties": { + "failed": { + "description": "Failed, timed out or cancelled.", + "examples": [ + 0 + ], + "format": "int32", + "minimum": 0, + "type": "integer" + }, + "passed": { + "description": "Passed.", + "examples": [ + 5 + ], + "format": "int32", + "minimum": 0, + "type": "integer" + }, + "queued": { + "description": "Waiting to start, or required and not reported yet.", + "examples": [ + 0 + ], + "format": "int32", + "minimum": 0, + "type": "integer" + }, + "running": { + "description": "Running now.", + "examples": [ + 1 + ], + "format": "int32", + "minimum": 0, + "type": "integer" + }, + "skipped": { + "description": "Skipped or neutral.", + "examples": [ + 1 + ], + "format": "int32", + "minimum": 0, + "type": "integer" + } + }, + "required": [ + "passed", + "failed", + "running", + "queued", + "skipped" + ], + "type": "object" + }, + "RunChecks": { + "description": "The CI checks on the run's open pull request's head.", + "properties": { + "counts": { + "$ref": "#/components/schemas/RunCheckCounts", + "description": "How many checks are in each state." + }, + "items": { + "description": "Failed first, then running, queued, passed and skipped; by name\nwithin each.", + "items": { + "$ref": "#/components/schemas/RunCheck" + }, + "type": "array" + }, + "sha": { + "description": "The commit they ran on: the pull request's head.", + "examples": [ + "9fceb02d0ae598e95dc970b74767f19372d61af8" + ], + "type": "string" + } + }, + "required": [ + "sha", + "items", + "counts" + ], + "type": "object" + }, "RunCoveredBy": { "description": "The open pull request that already does a run's work.", "properties": { @@ -4472,6 +4673,56 @@ }, "type": "object" }, + "RunPrReview": { + "description": "CoderHelm's latest review verdict on the run's pull request.", + "properties": { + "at": { + "description": "When it was written (RFC 3339).", + "examples": [ + "2026-10-22T14:20:05+00:00" + ], + "type": "string" + }, + "review_sk": { + "description": "The review's key, for `/api/reviewer/review?sk=`.", + "examples": [ + "REVIEW#acme/web#000318#2026-10-22T14:20:05+00:00" + ], + "type": "string" + }, + "reviewed_sha": { + "description": "The commit it reviewed.", + "examples": [ + "9fceb02d0ae598e95dc970b74767f19372d61af8" + ], + "type": "string" + }, + "session_id": { + "description": "The review job that wrote it (`/api/reviewer/session?id=`). Null on\nolder reviews.", + "examples": [ + "3f2c9a1e-5b7d-4c8e-9a0b-1c2d3e4f5a6b" + ], + "type": [ + "string", + "null" + ] + }, + "verdict": { + "description": "`APPROVE` or `REQUEST_CHANGES`.", + "examples": [ + "APPROVE" + ], + "type": "string" + } + }, + "required": [ + "verdict", + "review_sk", + "reviewed_sha", + "at" + ], + "type": "object" + }, "RunQuestion": { "description": "A question a run asked a person.", "properties": { diff --git a/services/common/src/review_session.rs b/services/common/src/review_session.rs index 2d1571cde..ac1cadf9a 100644 --- a/services/common/src/review_session.rs +++ b/services/common/src/review_session.rs @@ -440,6 +440,69 @@ pub async fn set_overview( log_unless_missing(named(req, update).send().await.err(), job, "overview"); } +/// Attribute on a session naming the review record (`REVIEW#…` sort key) +/// the job wrote. +pub const REVIEW_SK: &str = "review_sk"; + +/// Attribute on a review record naming the job (its session id) that wrote +/// it. +pub const REVIEW_SESSION_ID: &str = "session_id"; + +/// Pure: the update that links a session to the review record it wrote. A +/// verdict always takes the link; an answer to a question takes it only +/// when the job wrote no review (a job that reviews and then answers links +/// its review). +pub fn review_link_update(is_verdict: bool) -> String { + if is_verdict { + "SET #review_sk = :r, #updated_at = :at".to_string() + } else { + "SET #review_sk = if_not_exists(#review_sk, :r), #updated_at = :at".to_string() + } +} + +/// Link `job`'s session to the review record `review_sk` it wrote. Nothing +/// happens for a job that never opened a session. +pub async fn link_review( + dynamo: &DynamoClient, + table: &str, + team_id: &str, + job: &str, + review_sk: &str, + is_verdict: bool, +) { + if review_sk.is_empty() { + return; + } + let update = review_link_update(is_verdict); + let req = dynamo + .update_item() + .table_name(table) + .key("pk", s(team_id)) + .key("sk", s(&record_sk(job))) + .update_expression(&update) + .condition_expression(EXISTS) + .expression_attribute_values(":r", s(review_sk)) + .expression_attribute_values(":at", s(&chrono::Utc::now().to_rfc3339())); + log_unless_missing(named(req, &update).send().await.err(), job, "review link"); +} + +/// Pure: the review record a session wrote, when it is linked to one. +pub fn review_sk_of(item: &HashMap) -> Option { + item.get(REVIEW_SK) + .and_then(|v| v.as_s().ok()) + .filter(|s| s.starts_with("REVIEW#")) + .cloned() +} + +/// Pure: the session that wrote a review record, when the record names one +/// (older records don't). +pub fn session_id_of(item: &HashMap) -> Option { + item.get(REVIEW_SESSION_ID) + .and_then(|v| v.as_s().ok()) + .filter(|s| valid_id(s)) + .cloned() +} + /// A condition miss is a job that never opened a session (it stopped before /// real work); anything else is logged and dropped. fn log_unless_missing( @@ -641,4 +704,38 @@ mod tests { } assert_eq!(placeholders(&step_update()), vec!["steps", "updated_at"]); } + + #[test] + fn a_verdict_links_its_session_and_an_answer_never_replaces_it() { + assert_eq!( + review_link_update(true), + "SET #review_sk = :r, #updated_at = :at" + ); + let answer = review_link_update(false); + assert!(answer.contains("if_not_exists(#review_sk, :r)"), "{answer}"); + for expr in [review_link_update(true), review_link_update(false)] { + assert_eq!(placeholders(&expr), vec!["review_sk", "updated_at"]); + assert!(!expr.contains("#steps")); + } + } + + #[test] + fn the_links_read_back_and_old_records_have_none() { + let job = "3f2c9a1e-5b7d-4c8e-9a0b-1c2d3e4f5a6b"; + let review = "REVIEW#acme/web#000318#2026-10-22T14:20:05+00:00"; + let session = HashMap::from([(REVIEW_SK.to_string(), s(review))]); + assert_eq!(review_sk_of(&session).as_deref(), Some(review)); + let record = HashMap::from([(REVIEW_SESSION_ID.to_string(), s(job))]); + assert_eq!(session_id_of(&record).as_deref(), Some(job)); + // Older records: nothing. + assert_eq!(review_sk_of(&HashMap::new()), None); + assert_eq!(session_id_of(&HashMap::new()), None); + // Anything that isn't a key or a job id is not a link. + let bad = HashMap::from([ + (REVIEW_SK.to_string(), s("REVIEWSESSION#x")), + (REVIEW_SESSION_ID.to_string(), s("not-a-job")), + ]); + assert_eq!(review_sk_of(&bad), None); + assert_eq!(session_id_of(&bad), None); + } } diff --git a/services/gateway/src/routes/api.rs b/services/gateway/src/routes/api.rs index 4e8e00842..c1de6c386 100644 --- a/services/gateway/src/routes/api.rs +++ b/services/gateway/src/routes/api.rs @@ -1249,6 +1249,15 @@ pub struct Run { /// is ready or closed. #[schema(example = json!(null))] pub draft_hold: Option, + /// The CI checks on the head of the run's open pull request, read from + /// GitHub (reused for up to a minute). Null when the run has no open + /// pull request or GitHub can't be read. + #[schema(example = json!(null))] + pub checks: Option, + /// CoderHelm's latest review verdict on the run's pull request. Null + /// before any. + #[schema(example = json!(null))] + pub pr_review: Option, } /// The public values a run's code generator was missing, as the API shows them. @@ -1602,7 +1611,7 @@ pub async fn get_run( }; let lookups = run_trigger::load_lookups(&state, &claims.team_id, [item]).await; - Ok(Json(run_of( + let mut run = run_of( item, &run_id, RunUsage { @@ -1613,7 +1622,34 @@ pub async fn get_run( cost_usd, }, &lookups, - ))) + ); + // The open pull request's CI checks and review verdict: never fail the + // run for them. + let primary = common::run_prs::primary(&run.prs, run.repo.as_deref().unwrap_or("")) + .map(|p| (p.repo.clone(), p.pr_number)) + .filter(|(_, n)| *n > 0); + if let Some((repo, pr)) = primary { + let open = super::run_checks::open_pr(&run.prs, run.repo.as_deref().unwrap_or("")); + let installation_id = item + .get("installation_id") + .and_then(|v| v.as_n().ok()) + .and_then(|n| n.parse::().ok()) + .unwrap_or(0); + let checks = async { + match &open { + Some((repo, pr)) => { + super::run_checks::for_run(&state, &claims.team_id, installation_id, repo, *pr) + .await + } + None => None, + } + }; + let review = super::run_checks::pr_review(&state, &claims.team_id, &repo, pr); + let (checks, review) = tokio::join!(checks, review); + run.checks = checks; + run.pr_review = review; + } + Ok(Json(run)) } /// A run's token use and cost: the run's own, or summed from its traces. @@ -1790,6 +1826,8 @@ fn run_of( None }, draft_hold: draft_hold_of(item), + checks: None, + pr_review: None, } } diff --git a/services/gateway/src/routes/mod.rs b/services/gateway/src/routes/mod.rs index 4125813ab..967692189 100644 --- a/services/gateway/src/routes/mod.rs +++ b/services/gateway/src/routes/mod.rs @@ -59,6 +59,7 @@ pub mod review_lessons; pub mod reviewer; pub mod roles; pub mod run_answer; +pub mod run_checks; pub mod run_close; pub mod run_search; pub mod run_start; diff --git a/services/gateway/src/routes/reviewer.rs b/services/gateway/src/routes/reviewer.rs index 3e2c88f7b..10c7ce15f 100644 --- a/services/gateway/src/routes/reviewer.rs +++ b/services/gateway/src/routes/reviewer.rs @@ -638,6 +638,10 @@ pub struct Review { /// The team standards the review was given in full ("always apply"). #[schema(example = json!(["api-error-format"]))] pub applied_standards: Vec, + /// The review job that wrote this review: its session + /// (`/api/reviewer/session?id=`). Null on older reviews. + #[schema(example = "3f2c9a1e-5b7d-4c8e-9a0b-1c2d3e4f5a6b")] + pub session_id: Option, } /// A page of reviews. @@ -727,6 +731,7 @@ fn review_of(item: &HashMap, truncate_body: bool) -> Rev .collect::>() }) .unwrap_or_default(), + session_id: common::review_session::session_id_of(item), } } @@ -1449,6 +1454,10 @@ pub struct ReviewSession { pub activity_dropped: u64, /// The "PR Overview" the review posted, once there is one. pub overview: Option, + /// The review this session wrote (its `sk`, for `/api/reviewer/review`). + /// Null while it runs, when it ended without one, and on older sessions. + #[schema(example = "REVIEW#acme/web#000318#2026-10-22T14:20:05+00:00")] + pub review_sk: Option, } /// Pure: the session in `item` as `team_id` sees it. `None` for a record @@ -1502,6 +1511,7 @@ fn session_of( activity: activity_groups(item), activity_dropped: common::review_session::activity_dropped(item), overview: overview_of(item), + review_sk: common::review_session::review_sk_of(item), }) } @@ -1910,6 +1920,38 @@ mod tests { assert_eq!(done.check_run_id, Some(77)); } + #[test] + fn a_review_and_its_session_link_both_ways_and_old_records_show_null() { + use common::review_session as rs; + let job = "3f2c9a1e-5b7d-4c8e-9a0b-1c2d3e4f5a6b"; + let review_sk = "REVIEW#acme/web#000318#2026-10-22T14:20:05+00:00"; + let mut review = item(&[ + ("sk", attr_s(review_sk)), + ("verdict", attr_s("APPROVE")), + (rs::REVIEW_SESSION_ID, attr_s(job)), + ]); + let j = review_item_to_json(&review, false); + assert_eq!(j["session_id"], job); + // The list carries it too. + assert_eq!(review_item_to_json(&review, true)["session_id"], job); + review.remove(rs::REVIEW_SESSION_ID); + let j = review_item_to_json(&review, false); + assert!(j.as_object().unwrap().contains_key("session_id")); + assert!(j["session_id"].is_null()); + + let mut session = session_item("t", "done", 2_000); + session.insert(rs::REVIEW_SK.into(), attr_s(review_sk)); + let s = serde_json::to_value(session_of(&session, "t", 9_999).unwrap()).unwrap(); + assert_eq!(s["review_sk"], review_sk); + assert_eq!(s["id"], job); + let s = serde_json::to_value( + session_of(&session_item("t", "done", 2_000), "t", 9_999).unwrap(), + ) + .unwrap(); + assert!(s.as_object().unwrap().contains_key("review_sk")); + assert!(s["review_sk"].is_null()); + } + #[test] fn a_session_returns_its_activity_in_groups_and_its_overview() { use common::review_activity::Event; diff --git a/services/gateway/src/routes/run_checks.rs b/services/gateway/src/routes/run_checks.rs new file mode 100644 index 000000000..4bd16f812 --- /dev/null +++ b/services/gateway/src/routes/run_checks.rs @@ -0,0 +1,799 @@ +//! What a run's page shows about its open pull request: the CI checks on +//! the pull request's head (GitHub check runs and commit statuses, required +//! ones marked from the branch's rules), and CoderHelm's latest review +//! verdict on it. +//! +//! The checks are read from GitHub when the page asks, never stored. Pages +//! poll, and an installation has hit GitHub's hourly limit before, so every +//! read goes through short in-memory caches: the pull request's head for +//! [`PR_TTL`], the checks on a commit for [`CHECKS_TTL`] (keyed by repository +//! and commit, see [`cache_key`]), the branch's required checks for +//! [`REQUIRED_TTL`], and the installation token for [`TOKEN_TTL`]. A read +//! GitHub refused is cached as "nothing" for as long, so a limited install is +//! not asked again on every poll. Anything that can't be read is `None`: the +//! run itself is always returned. + +use std::collections::HashMap; +use std::sync::{LazyLock, Mutex}; +use std::time::{Duration, Instant}; + +use aws_sdk_dynamodb::types::AttributeValue; +use serde_json::Value; +use tracing::warn; + +use crate::AppState; + +/// How long a pull request's head and state are reused. +pub const PR_TTL: Duration = Duration::from_secs(30); +/// How long the checks on one commit are reused. +pub const CHECKS_TTL: Duration = Duration::from_secs(45); +/// How long a branch's required checks are reused. +pub const REQUIRED_TTL: Duration = Duration::from_secs(600); +/// How long an installation token is reused (GitHub's last an hour). +pub const TOKEN_TTL: Duration = Duration::from_secs(45 * 60); +/// The most GitHub may take for the whole read before the run is returned +/// without its checks. +const READ_BUDGET: Duration = Duration::from_secs(6); +/// Entries one cache holds before expired ones are dropped. +const CACHE_CAP: usize = 2_000; + +const API: &str = "https://api.github.com"; + +/// One check on the pull request's head. +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, utoipa::ToSchema)] +pub struct RunCheck { + /// The check's name (a check run's name or a commit status's context). + #[schema(example = "build")] + pub name: String, + /// `passed`, `failed`, `running`, `queued` or `skipped`. A required check + /// that hasn't reported yet is `queued`. + #[schema(example = "passed")] + pub state: String, + /// GitHub's word for how it ended (`success`, `failure`, `neutral`, + /// `cancelled`, `timed_out`, `skipped`, `error`, ...). Null until it ends. + #[schema(example = "success")] + pub conclusion: Option, + /// The branch's rules require it before merging. False when they can't + /// be read. + #[schema(example = true)] + pub required: bool, + /// When it started (RFC 3339), when known. + #[schema(example = "2026-10-22T14:18:00Z")] + pub started_at: Option, + /// When it ended (RFC 3339). Null while it runs. + #[schema(example = "2026-10-22T14:21:40Z")] + pub completed_at: Option, + /// Its page on GitHub or in the CI system. + #[schema(example = "https://github.com/acme/web/actions/runs/1/job/2")] + pub url: Option, +} + +/// How many checks are in each state. +#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, utoipa::ToSchema)] +pub struct RunCheckCounts { + /// Passed. + #[schema(example = 5)] + pub passed: u32, + /// Failed, timed out or cancelled. + #[schema(example = 0)] + pub failed: u32, + /// Running now. + #[schema(example = 1)] + pub running: u32, + /// Waiting to start, or required and not reported yet. + #[schema(example = 0)] + pub queued: u32, + /// Skipped or neutral. + #[schema(example = 1)] + pub skipped: u32, +} + +/// The CI checks on the run's open pull request's head. +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, utoipa::ToSchema)] +pub struct RunChecks { + /// The commit they ran on: the pull request's head. + #[schema(example = "9fceb02d0ae598e95dc970b74767f19372d61af8")] + pub sha: String, + /// Failed first, then running, queued, passed and skipped; by name + /// within each. + pub items: Vec, + /// How many checks are in each state. + pub counts: RunCheckCounts, +} + +/// CoderHelm's latest review verdict on the run's pull request. +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, utoipa::ToSchema)] +pub struct RunPrReview { + /// `APPROVE` or `REQUEST_CHANGES`. + #[schema(example = "APPROVE")] + pub verdict: String, + /// The review's key, for `/api/reviewer/review?sk=`. + #[schema(example = "REVIEW#acme/web#000318#2026-10-22T14:20:05+00:00")] + pub review_sk: String, + /// The review job that wrote it (`/api/reviewer/session?id=`). Null on + /// older reviews. + #[schema(example = "3f2c9a1e-5b7d-4c8e-9a0b-1c2d3e4f5a6b")] + pub session_id: Option, + /// The commit it reviewed. + #[schema(example = "9fceb02d0ae598e95dc970b74767f19372d61af8")] + pub reviewed_sha: String, + /// When it was written (RFC 3339). + #[schema(example = "2026-10-22T14:20:05+00:00")] + pub at: String, +} + +// ─── Pure mapping ─────────────────────────────────────────────────── + +/// Pure: a check run's state from its `status` and `conclusion`. +pub fn check_run_state(status: &str, conclusion: &str) -> &'static str { + match status { + "completed" => match conclusion { + "success" => "passed", + "neutral" | "skipped" | "stale" => "skipped", + _ => "failed", + }, + "in_progress" => "running", + _ => "queued", + } +} + +/// Pure: a commit status's state from its `state`. +pub fn status_state(state: &str) -> &'static str { + match state { + "success" => "passed", + "pending" => "running", + _ => "failed", + } +} + +fn rank(state: &str) -> u8 { + match state { + "failed" => 0, + "running" => 1, + "queued" => 2, + "passed" => 3, + _ => 4, + } +} + +fn opt(v: &Value) -> Option { + v.as_str().filter(|s| !s.is_empty()).map(str::to_string) +} + +/// Pure: the checks on a commit from a `check-runs` listing and the combined +/// status's `statuses`, without `required` marked. The newest run of each +/// name counts; a status whose context a check run already has is left out. +pub fn checks_of(check_runs: &[Value], statuses: &[Value]) -> Vec { + // name -> (started_at, id, check) + let mut runs: Vec<(String, u64, RunCheck)> = Vec::new(); + for c in check_runs { + let Some(name) = opt(&c["name"]) else { + continue; + }; + let status = c["status"].as_str().unwrap_or(""); + let conclusion = c["conclusion"].as_str().unwrap_or(""); + let started = c["started_at"].as_str().unwrap_or("").to_string(); + let id = c["id"].as_u64().unwrap_or(0); + let check = RunCheck { + name: name.clone(), + state: check_run_state(status, conclusion).to_string(), + conclusion: (status == "completed") + .then(|| opt(&c["conclusion"])) + .flatten(), + required: false, + started_at: opt(&c["started_at"]), + completed_at: opt(&c["completed_at"]), + url: opt(&c["html_url"]).or_else(|| opt(&c["details_url"])), + }; + match runs.iter_mut().find(|(_, _, x)| x.name == name) { + Some((at, rid, x)) => { + if (started.as_str(), id) >= (at.as_str(), *rid) { + *at = started; + *rid = id; + *x = check; + } + } + None => runs.push((started, id, check)), + } + } + let mut out: Vec = runs.into_iter().map(|(_, _, c)| c).collect(); + for s in statuses { + let Some(name) = opt(&s["context"]) else { + continue; + }; + if out.iter().any(|c| c.name == name) { + continue; + } + let state = s["state"].as_str().unwrap_or(""); + out.push(RunCheck { + name, + state: status_state(state).to_string(), + conclusion: (state != "pending").then(|| opt(&s["state"])).flatten(), + required: false, + started_at: opt(&s["created_at"]), + completed_at: if state == "pending" { + None + } else { + opt(&s["updated_at"]) + }, + url: opt(&s["target_url"]), + }); + } + out +} + +/// Pure: the checks with the branch's required ones marked, a required +/// check that hasn't reported added as `queued`, sorted, and counted. +pub fn with_required(sha: &str, mut items: Vec, required: &[String]) -> RunChecks { + for c in items.iter_mut() { + c.required = required.iter().any(|r| r == &c.name); + } + for r in required { + if !items.iter().any(|c| &c.name == r) { + items.push(RunCheck { + name: r.clone(), + state: "queued".to_string(), + conclusion: None, + required: true, + started_at: None, + completed_at: None, + url: None, + }); + } + } + items.sort_by(|a, b| { + rank(&a.state) + .cmp(&rank(&b.state)) + .then_with(|| a.name.cmp(&b.name)) + }); + let mut counts = RunCheckCounts::default(); + for c in &items { + match c.state.as_str() { + "passed" => counts.passed += 1, + "failed" => counts.failed += 1, + "running" => counts.running += 1, + "queued" => counts.queued += 1, + _ => counts.skipped += 1, + } + } + RunChecks { + sha: sha.to_string(), + items, + counts, + } +} + +/// Pure: the cache key of the checks on one commit of one repository. +/// GitHub names are case-insensitive; a commit id is not. +pub fn cache_key(repo: &str, sha: &str) -> String { + format!("{}@{sha}", repo.to_ascii_lowercase()) +} + +/// Pure: the pull request the run's checks are for: its primary one, while +/// it is open. `None` when the run has none or it has ended. +pub fn open_pr(prs: &[common::run_prs::RunPr], run_repo: &str) -> Option<(String, u64)> { + let pr = common::run_prs::primary(prs, run_repo)?; + (pr.outcome.is_empty() && pr.pr_number > 0 && pr.repo.contains('/')) + .then(|| (pr.repo.clone(), pr.pr_number)) +} + +/// The opening words of an old error review: not a verdict on the code. +const LEGACY_FAILED_PREFIX: &str = "Automated review could not complete"; + +/// Pure: the latest verdict among a PR's review records, newest first. +/// Answers to questions and old error reviews are skipped. +pub fn latest_verdict(items: &[HashMap]) -> Option { + items.iter().find_map(|it| { + let get = |k: &str| { + it.get(k) + .and_then(|v| v.as_s().ok()) + .cloned() + .unwrap_or_default() + }; + let verdict = get("verdict"); + if verdict != "APPROVE" && verdict != "REQUEST_CHANGES" { + return None; + } + if get("body").trim_start().starts_with(LEGACY_FAILED_PREFIX) { + return None; + } + Some(RunPrReview { + verdict, + review_sk: get("sk"), + session_id: common::review_session::session_id_of(it), + reviewed_sha: get("head_sha"), + at: get("created_at"), + }) + }) +} + +// ─── Caches ───────────────────────────────────────────────────────── + +/// A small map whose entries expire. +pub struct TtlCache { + map: Mutex>, +} + +impl TtlCache { + pub fn new() -> Self { + Self { + map: Mutex::new(HashMap::new()), + } + } + + /// The value under `key`, unless it expired by `now`. + pub fn get(&self, key: &str, now: Instant) -> Option { + let map = self.map.lock().unwrap_or_else(|p| p.into_inner()); + map.get(key) + .filter(|(until, _)| *until > now) + .map(|(_, v)| v.clone()) + } + + /// Keep `v` under `key` for `ttl` from `now`. + pub fn put(&self, key: String, v: V, ttl: Duration, now: Instant) { + let mut map = self.map.lock().unwrap_or_else(|p| p.into_inner()); + if map.len() >= CACHE_CAP { + map.retain(|_, (until, _)| *until > now); + if map.len() >= CACHE_CAP { + map.clear(); + } + } + map.insert(key, (now + ttl, v)); + } +} + +impl Default for TtlCache { + fn default() -> Self { + Self::new() + } +} + +/// A pull request's state, head commit and base branch. +#[derive(Debug, Clone, PartialEq, Eq)] +struct PrHead { + open: bool, + sha: String, + base: String, +} + +static TOKENS: LazyLock> = LazyLock::new(TtlCache::new); +static PR_HEADS: LazyLock>> = LazyLock::new(TtlCache::new); +static CHECKS: LazyLock>>> = LazyLock::new(TtlCache::new); +static REQUIRED: LazyLock>> = LazyLock::new(TtlCache::new); + +// ─── GitHub reads ─────────────────────────────────────────────────── + +async fn token(state: &AppState, installation_id: u64) -> Option { + let key = installation_id.to_string(); + if let Some(t) = TOKENS.get(&key, Instant::now()) { + return Some(t); + } + match crate::auth::github_app::get_installation_token(state, installation_id).await { + Ok(t) => { + TOKENS.put(key, t.clone(), TOKEN_TTL, Instant::now()); + Some(t) + } + Err(e) => { + warn!(installation_id, error = %e, "Run checks: no installation token"); + None + } + } +} + +/// GET a GitHub API path; `None` unless it answered 200. +async fn get_ok(state: &AppState, token: &str, path: &str) -> Option { + match super::merge_control::gh_get(state, token, &format!("{API}{path}")).await { + Ok((200, v)) => Some(v), + Ok((code, _)) => { + if code != 404 { + warn!(path, code, "Run checks: GitHub refused a read"); + } + None + } + Err(e) => { + warn!(path, error = %e, "Run checks: GitHub read failed"); + None + } + } +} + +async fn pr_head(state: &AppState, token: &str, repo: &str, pr: u64) -> Option { + let key = format!("{}#{pr}", repo.to_ascii_lowercase()); + if let Some(h) = PR_HEADS.get(&key, Instant::now()) { + return h; + } + let head = get_ok(state, token, &format!("/repos/{repo}/pulls/{pr}")) + .await + .and_then(|v| { + Some(PrHead { + open: v["state"].as_str() == Some("open"), + sha: opt(&v["head"]["sha"])?, + base: opt(&v["base"]["ref"])?, + }) + }); + PR_HEADS.put(key, head.clone(), PR_TTL, Instant::now()); + head +} + +/// Required checks of `base` from the branch's rules and its classic +/// protection, either of which may be unreadable (then it adds nothing). +async fn required_checks(state: &AppState, token: &str, repo: &str, base: &str) -> Vec { + let key = format!("{}:{base}", repo.to_ascii_lowercase()); + if let Some(r) = REQUIRED.get(&key, Instant::now()) { + return r; + } + let branch = urlencoding::encode(base); + let rules_path = format!("/repos/{repo}/rules/branches/{branch}"); + let protection_path = + format!("/repos/{repo}/branches/{branch}/protection/required_status_checks"); + let (rules, protection) = tokio::join!( + get_ok(state, token, &rules_path), + get_ok(state, token, &protection_path), + ); + let names = common::e2e::check_gate::required(rules.as_ref(), protection.as_ref()); + REQUIRED.put(key, names.clone(), REQUIRED_TTL, Instant::now()); + names +} + +async fn commit_checks( + state: &AppState, + token: &str, + repo: &str, + sha: &str, +) -> Option> { + let key = cache_key(repo, sha); + if let Some(c) = CHECKS.get(&key, Instant::now()) { + return c; + } + let runs_path = format!("/repos/{repo}/commits/{sha}/check-runs?filter=latest&per_page=100"); + let status_path = format!("/repos/{repo}/commits/{sha}/status?per_page=100"); + let (runs, status) = tokio::join!( + get_ok(state, token, &runs_path), + get_ok(state, token, &status_path), + ); + // The check runs are what CI reports; without them there is no answer. + let checks = runs.map(|r| { + let runs = r["check_runs"].as_array().cloned().unwrap_or_default(); + let statuses = status + .as_ref() + .and_then(|s| s["statuses"].as_array().cloned()) + .unwrap_or_default(); + checks_of(&runs, &statuses) + }); + CHECKS.put(key, checks.clone(), CHECKS_TTL, Instant::now()); + checks +} + +async fn read_checks( + state: &AppState, + installation_id: u64, + repo: &str, + pr: u64, +) -> Option { + let token = token(state, installation_id).await?; + let head = pr_head(state, &token, repo, pr).await?; + if !head.open || !head.sha.chars().all(|c| c.is_ascii_hexdigit()) { + return None; + } + let (items, required) = tokio::join!( + commit_checks(state, &token, repo, &head.sha), + required_checks(state, &token, repo, &head.base), + ); + Some(with_required(&head.sha, items?, &required)) +} + +/// The checks on the head of the run's open pull request. `None` when there +/// is none, or GitHub can't be read in time. +pub async fn for_run( + state: &AppState, + team_id: &str, + run_installation_id: u64, + repo: &str, + pr: u64, +) -> Option { + let valid = |s: &str| { + !s.is_empty() + && s.chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.')) + }; + let (owner, name) = repo.split_once('/')?; + if !valid(owner) || !valid(name) || owner == ".." || name == ".." { + return None; + } + let installation_id = if run_installation_id > 0 { + run_installation_id + } else { + super::api::get_team_installation_id(state, team_id) + .await + .ok()? + }; + tokio::time::timeout(READ_BUDGET, read_checks(state, installation_id, repo, pr)) + .await + .unwrap_or_else(|_| { + warn!(repo, pr, "Run checks: GitHub took too long"); + None + }) +} + +/// CoderHelm's latest verdict on `repo`#`pr`, from the team's review records +/// (newest first, as the reviewer pages list them). +pub async fn pr_review( + state: &AppState, + team_id: &str, + repo: &str, + pr: u64, +) -> Option { + let prefix = format!("REVIEW#{repo}#{pr:0>6}#"); + let mut start: Option> = None; + // Answers to questions sit between verdicts; two pages reach far enough. + for _ in 0..2 { + let resp = state + .dynamo + .query() + .table_name(&state.config.settings_table_name) + .key_condition_expression("pk = :pk AND begins_with(sk, :sk)") + .expression_attribute_values(":pk", AttributeValue::S(team_id.to_string())) + .expression_attribute_values(":sk", AttributeValue::S(prefix.clone())) + .projection_expression("sk, verdict, head_sha, created_at, session_id, body") + .scan_index_forward(false) + .limit(25) + .set_exclusive_start_key(start.take()) + .send() + .await + .map_err(|e| warn!(repo, pr, error = %e, "Run PR review: read failed")) + .ok()?; + if let Some(r) = latest_verdict(resp.items()) { + return Some(r); + } + match resp.last_evaluated_key() { + Some(k) => start = Some(k.clone()), + None => break, + } + } + None +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn run(name: &str, status: &str, conclusion: Option<&str>, started: &str, id: u64) -> Value { + json!({ + "id": id, + "name": name, + "status": status, + "conclusion": conclusion, + "started_at": started, + "completed_at": if status == "completed" { json!("2026-11-10T10:05:00Z") } else { Value::Null }, + "html_url": format!("https://github.com/o/r/runs/{id}"), + }) + } + + #[test] + fn check_runs_map_to_five_states() { + assert_eq!(check_run_state("completed", "success"), "passed"); + for c in [ + "failure", + "cancelled", + "timed_out", + "action_required", + "startup_failure", + "", + ] { + assert_eq!(check_run_state("completed", c), "failed", "{c}"); + } + for c in ["neutral", "skipped", "stale"] { + assert_eq!(check_run_state("completed", c), "skipped", "{c}"); + } + assert_eq!(check_run_state("in_progress", ""), "running"); + for s in ["queued", "waiting", "requested", "pending", ""] { + assert_eq!(check_run_state(s, ""), "queued", "{s}"); + } + assert_eq!(status_state("success"), "passed"); + assert_eq!(status_state("pending"), "running"); + assert_eq!(status_state("failure"), "failed"); + assert_eq!(status_state("error"), "failed"); + } + + #[test] + fn counts_cover_every_state_and_required_checks_are_marked() { + let runs = vec![ + run( + "build", + "completed", + Some("success"), + "2026-11-10T10:00:00Z", + 1, + ), + // An older failed run of the same name is replaced by the rerun. + run( + "test", + "completed", + Some("failure"), + "2026-11-10T09:00:00Z", + 2, + ), + run("test", "in_progress", None, "2026-11-10T10:01:00Z", 3), + run( + "lint", + "completed", + Some("failure"), + "2026-11-10T10:00:00Z", + 4, + ), + run( + "deploy", + "completed", + Some("skipped"), + "2026-11-10T10:00:00Z", + 5, + ), + run("e2e", "queued", None, "", 6), + json!({"name": "", "status": "completed"}), + ]; + let statuses = vec![ + json!({"context": "ci/legacy", "state": "success", "target_url": "https://ci.example.com/1", "created_at": "2026-11-10T10:00:00Z", "updated_at": "2026-11-10T10:02:00Z"}), + json!({"context": "ci/pending", "state": "pending", "created_at": "2026-11-10T10:00:00Z", "updated_at": "2026-11-10T10:00:00Z"}), + // A status named like a check run is left to the check run. + json!({"context": "build", "state": "failure"}), + ]; + let items = checks_of(&runs, &statuses); + assert_eq!(items.len(), 7); + let required = vec![ + "build".to_string(), + "test".to_string(), + "security".to_string(), + ]; + let c = with_required("abc", items, &required); + assert_eq!(c.sha, "abc"); + assert_eq!( + c.counts, + RunCheckCounts { + passed: 2, + failed: 1, + running: 2, + queued: 2, + skipped: 1, + } + ); + let by = |n: &str| c.items.iter().find(|i| i.name == n).unwrap(); + assert!(by("build").required && by("test").required); + assert!(!by("lint").required && !by("ci/legacy").required); + assert_eq!(by("test").state, "running"); + assert_eq!(by("test").conclusion, None); + assert_eq!(by("test").completed_at, None); + assert_eq!(by("lint").conclusion.as_deref(), Some("failure")); + assert_eq!( + by("build").url.as_deref(), + Some("https://github.com/o/r/runs/1") + ); + assert_eq!( + by("ci/legacy").url.as_deref(), + Some("https://ci.example.com/1") + ); + assert_eq!(by("ci/legacy").conclusion.as_deref(), Some("success")); + assert_eq!( + by("ci/legacy").completed_at.as_deref(), + Some("2026-11-10T10:02:00Z") + ); + assert_eq!(by("ci/pending").completed_at, None); + assert_eq!(by("deploy").state, "skipped"); + // A required check that never reported waits as queued. + let sec = by("security"); + assert_eq!( + (sec.state.as_str(), sec.required, sec.url.clone()), + ("queued", true, None) + ); + // Failed first. + assert_eq!(c.items[0].name, "lint"); + assert_eq!(c.items.last().unwrap().name, "deploy"); + } + + #[test] + fn unreadable_branch_rules_leave_every_check_optional() { + let items = checks_of(&[run("build", "completed", Some("success"), "t", 1)], &[]); + let c = with_required("abc", items, &[]); + assert!(c.items.iter().all(|i| !i.required)); + assert_eq!(c.counts.passed, 1); + // No checks at all is an empty list, not an error. + let none = with_required("abc", checks_of(&[], &[]), &[]); + assert!(none.items.is_empty()); + assert_eq!(none.counts, RunCheckCounts::default()); + } + + #[test] + fn the_cache_key_is_the_repository_and_the_commit() { + assert_eq!(cache_key("Acme/Web", "9fceb02"), "acme/web@9fceb02"); + assert_eq!( + cache_key("acme/web", "9fceb02"), + cache_key("ACME/WEB", "9fceb02") + ); + assert_ne!( + cache_key("acme/web", "9fceb02"), + cache_key("acme/web", "9FCEB02") + ); + assert_ne!(cache_key("acme/web", "a"), cache_key("acme/api", "a")); + } + + #[test] + fn the_cache_forgets_after_its_ttl() { + let cache: TtlCache> = TtlCache::new(); + let t0 = Instant::now(); + assert_eq!(cache.get("k", t0), None); + cache.put("k".into(), Some(7), CHECKS_TTL, t0); + assert_eq!(cache.get("k", t0 + Duration::from_secs(44)), Some(Some(7))); + assert_eq!(cache.get("k", t0 + CHECKS_TTL), None); + // A refused read is remembered as nothing, so it isn't asked again. + cache.put("gone".into(), None, CHECKS_TTL, t0); + assert_eq!(cache.get("gone", t0), Some(None)); + } + + #[test] + fn only_an_open_pull_request_gets_checks() { + use common::run_prs::RunPr; + let pr = |repo: &str, n: u64, outcome: &str| RunPr { + repo: repo.into(), + pr_number: n, + branch: "b".into(), + url: String::new(), + outcome: outcome.into(), + }; + assert_eq!(open_pr(&[], "acme/web"), None); + assert_eq!( + open_pr(&[pr("acme/api", 3, ""), pr("acme/web", 7, "")], "acme/web"), + Some(("acme/web".into(), 7)) + ); + assert_eq!(open_pr(&[pr("acme/web", 7, "merged")], "acme/web"), None); + assert_eq!(open_pr(&[pr("acme/web", 7, "closed")], "acme/web"), None); + assert_eq!(open_pr(&[pr("acme/web", 0, "")], "acme/web"), None); + } + + #[test] + fn the_latest_verdict_skips_answers_and_error_reviews() { + let rec = |sk: &str, verdict: &str, body: &str, session: Option<&str>| { + let mut m: HashMap = [ + ("sk", sk), + ("verdict", verdict), + ("body", body), + ("head_sha", "abc"), + ("created_at", "2026-11-10T10:00:00+00:00"), + ] + .into_iter() + .map(|(k, v)| (k.to_string(), AttributeValue::S(v.to_string()))) + .collect(); + if let Some(s) = session { + m.insert("session_id".into(), AttributeValue::S(s.into())); + } + m + }; + let job = "3f2c9a1e-5b7d-4c8e-9a0b-1c2d3e4f5a6b"; + let items = vec![ + rec("REVIEW#a/b#000007#4", "QUESTION", "An answer", Some(job)), + rec( + "REVIEW#a/b#000007#3", + "REQUEST_CHANGES", + "Automated review could not complete: x", + None, + ), + rec("REVIEW#a/b#000007#2", "APPROVE", "Fine", Some(job)), + rec("REVIEW#a/b#000007#1", "REQUEST_CHANGES", "Fix it", None), + ]; + let r = latest_verdict(&items).unwrap(); + assert_eq!( + r, + RunPrReview { + verdict: "APPROVE".into(), + review_sk: "REVIEW#a/b#000007#2".into(), + session_id: Some(job.into()), + reviewed_sha: "abc".into(), + at: "2026-11-10T10:00:00+00:00".into(), + } + ); + // An older review has no session. + assert_eq!(latest_verdict(&items[3..]).unwrap().session_id, None); + // Only answers: no verdict. + assert_eq!(latest_verdict(&items[..1]), None); + assert_eq!(latest_verdict(&[]), None); + } +} diff --git a/services/worker/src/passes/review_pr.rs b/services/worker/src/passes/review_pr.rs index 11c3f8a78..c12085b8a 100644 --- a/services/worker/src/passes/review_pr.rs +++ b/services/worker/src/passes/review_pr.rs @@ -515,6 +515,11 @@ impl LiveJob { } } + /// The job's session id, once its session page exists. + fn session_id(&self) -> Option { + self.session().opened.then(|| self.id.clone()) + } + fn session(&self) -> std::sync::MutexGuard<'_, Session> { self.session.lock().unwrap_or_else(|p| p.into_inner()) } @@ -1048,7 +1053,7 @@ pub async fn run( FormalResult::Failed } }; - let out = post_reply(state, &msg, *reply, formal).await; + let out = post_reply(state, &msg, &job, *reply, formal).await; // A failed formal review already shows its retry. if formal != FormalResult::Failed { job.finished(state, &msg, common::review_live::Finished::Done) @@ -1126,6 +1131,7 @@ pub(crate) fn reply_after_formal(answer: &str, head: &str, formal: FormalResult) async fn post_reply( state: &WorkerState, msg: &ReviewMessage, + job: &LiveJob, reply: PendingReply, formal: FormalResult, ) -> Result<(), Box> { @@ -1140,6 +1146,7 @@ async fn post_reply( state, &github, msg, + job, &reply.head_sha, &answer, &reply.consulted, @@ -1156,6 +1163,7 @@ async fn send_reply( state: &WorkerState, github: &GitHubClient, msg: &ReviewMessage, + job: &LiveJob, head_sha: &str, answer: &str, consulted: &str, @@ -1184,6 +1192,7 @@ async fn send_reply( let record_sk = store_review_record( state, msg, + job, head_sha, "QUESTION", "N/A", @@ -2138,7 +2147,7 @@ async fn run_once( } } send_reply( - state, &github, &msg, &head_sha, &answer, &consulted, &applied, &usage, + state, &github, &msg, live_job, &head_sha, &answer, &consulted, &applied, &usage, ) .await?; live_job @@ -2175,7 +2184,18 @@ async fn run_once( super::review_policy::standing_answer(&head_sha, &prev.verdict, &prev.holding); let mut asked = msg.clone(); asked.reply_to_comment_id = asked_in; - send_reply(state, &github, &asked, &head_sha, &answer, "", &[], &usage).await?; + send_reply( + state, + &github, + &asked, + live_job, + &head_sha, + &answer, + "", + &[], + &usage, + ) + .await?; live_job .step( state, @@ -2315,6 +2335,7 @@ async fn run_once( state, &github, &msg, + live_job, &head_sha, &approved, own_change_unchanged, @@ -3644,6 +3665,7 @@ async fn run_once( let record_sk = store_review_record( state, &msg, + live_job, &head_sha, verdict, &risk, @@ -3907,6 +3929,7 @@ async fn carry_approval( state: &WorkerState, github: &GitHubClient, msg: &ReviewMessage, + job: &LiveJob, head: &str, approved: &str, only_base_merged: bool, @@ -3955,6 +3978,7 @@ async fn carry_approval( store_review_record( state, msg, + job, head, "APPROVE", "N/A", @@ -4590,6 +4614,66 @@ fn head_commit_by_bot(compare: &serde_json::Value, head_sha: &str) -> bool { .is_some_and(|login| login.contains("coderhelm")) } +/// What one review record holds besides the PR it is on. +struct ReviewRecord<'a> { + head_sha: &'a str, + verdict: &'a str, + risk: &'a str, + body: &'a str, + posted_as: &'a str, + action_summary: &'a str, + /// RFC 3339; also the end of the sort key. + created_at: &'a str, + /// The job (session) that wrote it, when its session page exists. + session_id: Option<&'a str>, +} + +/// Pure: a review record's sort key and item. +fn review_record_item( + msg: &ReviewMessage, + r: &ReviewRecord<'_>, +) -> ( + String, + std::collections::HashMap, +) { + let repo = format!("{}/{}", msg.repo_owner, msg.repo_name); + let sk = format!("REVIEW#{repo}#{:0>6}#{}", msg.pr_number, r.created_at); + // Truncate the stored body so a huge review can't blow the 400KB item limit. + let body = common::head_tail_str(r.body, 30_000); + let mut item: std::collections::HashMap = [ + ("pk", attr_s(&msg.team_id)), + ("sk", attr_s(&sk)), + ("record_type", attr_s("review")), + ("repo", attr_s(&repo)), + ("pr_number", attr_n(msg.pr_number)), + ("head_sha", attr_s(r.head_sha)), + ("verdict", attr_s(r.verdict)), + ("risk", attr_s(r.risk)), + ("body", attr_s(&body)), + ("posted_as", attr_s(r.posted_as)), + ("trigger", attr_s(&msg.trigger)), + ("thumbs_up", attr_n(0)), + ("thumbs_down", attr_n(0)), + ("created_at", attr_s(r.created_at)), + ] + .into_iter() + .map(|(k, v)| (k.to_string(), v)) + .collect(); + if !r.action_summary.is_empty() { + item.insert( + "action_summary".to_string(), + attr_s(&common::head_tail_str(r.action_summary, 8_000)), + ); + } + if let Some(id) = r.session_id.filter(|id| !id.is_empty()) { + item.insert( + common::review_session::REVIEW_SESSION_ID.to_string(), + attr_s(id), + ); + } + (sk, item) +} + /// Persist a review record to the settings table so the dashboard can list it and /// ratings/actions can attach. Keyed pk=team_id, sk=REVIEW#{repo}#{pr:06}#{ts}. /// Best-effort: a storage failure must never break the actual GitHub review. @@ -4600,6 +4684,7 @@ fn head_commit_by_bot(compare: &serde_json::Value, head_sha: &str) -> bool { async fn store_review_record( state: &WorkerState, msg: &ReviewMessage, + job: &LiveJob, head_sha: &str, verdict: &str, risk: &str, @@ -4610,37 +4695,42 @@ async fn store_review_record( ) -> String { let created_at = chrono::Utc::now().to_rfc3339(); let repo = format!("{}/{}", msg.repo_owner, msg.repo_name); - let sk = format!("REVIEW#{repo}#{:0>6}#{created_at}", msg.pr_number); - // Truncate the stored body so a huge review can't blow the 400KB item limit. - let body = common::head_tail_str(body, 30_000); - - let mut put = state + let session_id = job.session_id(); + let (sk, item) = review_record_item( + msg, + &ReviewRecord { + head_sha, + verdict, + risk, + body, + posted_as, + action_summary, + created_at: &created_at, + session_id: session_id.as_deref(), + }, + ); + if let Err(e) = state .dynamo .put_item() .table_name(&state.config.settings_table_name) - .item("pk", attr_s(&msg.team_id)) - .item("sk", attr_s(&sk)) - .item("record_type", attr_s("review")) - .item("repo", attr_s(&repo)) - .item("pr_number", attr_n(msg.pr_number)) - .item("head_sha", attr_s(head_sha)) - .item("verdict", attr_s(verdict)) - .item("risk", attr_s(risk)) - .item("body", attr_s(&body)) - .item("posted_as", attr_s(posted_as)) - .item("trigger", attr_s(&msg.trigger)) - .item("thumbs_up", attr_n(0)) - .item("thumbs_down", attr_n(0)) - .item("created_at", attr_s(&created_at)); - if !action_summary.is_empty() { - put = put.item( - "action_summary", - attr_s(&common::head_tail_str(action_summary, 8_000)), - ); - } - if let Err(e) = put.send().await { + .set_item(Some(item)) + .send() + .await + { warn!(pr = msg.pr_number, error = %e, "Failed to persist review record (non-fatal)"); } + // The session that wrote it points back at it, for its page. + if let Some(id) = &session_id { + common::review_session::link_review( + &state.dynamo, + &state.config.settings_table_name, + &msg.team_id, + id, + &sk, + verdict != "QUESTION", + ) + .await; + } // A posted review is an event for the team's webhooks (an answer to a // question isn't a review). if counts.posted && verdict != "QUESTION" { @@ -5812,6 +5902,45 @@ mod failure_tests { } } + #[test] + fn a_review_record_names_the_session_that_wrote_it() { + let job = LiveJob::start(); + // No session page yet: no link. + assert_eq!(job.session_id(), None); + job.session().opened = true; + let id = job.session_id().unwrap(); + assert_eq!(id, job.id); + let record = |session_id: Option<&str>| { + review_record_item( + &msg(), + &ReviewRecord { + head_sha: "a1b2c3d4", + verdict: "APPROVE", + risk: "LOW", + body: "Looks right.", + posted_as: "APPROVE", + action_summary: "", + created_at: "2026-11-10T12:00:00+00:00", + session_id, + }, + ) + }; + let (sk, item) = record(Some(&id)); + assert_eq!(sk, "REVIEW#o/r#000042#2026-11-10T12:00:00+00:00"); + assert_eq!(item["sk"].as_s().unwrap(), &sk); + assert_eq!(item["verdict"].as_s().unwrap(), "APPROVE"); + assert!(!item.contains_key("action_summary")); + // What the review page reads back is the job's id. + assert_eq!( + common::review_session::session_id_of(&item).as_deref(), + Some(id.as_str()) + ); + // A job without a session page writes no link. + let (_, item) = record(None); + assert!(!item.contains_key(common::review_session::REVIEW_SESSION_ID)); + assert_eq!(common::review_session::session_id_of(&item), None); + } + /// A review that fails (a 520 that outlasted the client's retries, an /// unreadable answer) is sent again at 2, 10 and 30 minutes, then the /// PR is told. Nothing on this path is a verdict.