Skip to main content

agentmux_srv_core/backend/
reviews.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The Reviews pane's list (`GET /api/v1/reviews`, spec `SPEC_REVIEWS_PANE_2026_11_15.md`): every pull request a
5//! Kanban task names, with the review, checks and merge state srv was told of, and what each one waits on.
6//!
7//! Phase R1 makes no GitHub call and holds no credential. It joins two things srv already has: the board's cards
8//! (their PR address, repository, branch, holder and merge time) and the recent review, checks and merge events
9//! of [`super::pr_flow`]. The events name a repository only by its numeric id, so the join is by the card's
10//! holder and the PR number, and a repository id learned from one unambiguous match settles a later clash of two
11//! cards that hold PRs with the same number. An event no card claims is a row with no task and no address.
12//!
13//! This file is pure: the handler reads the board and the recent events and calls [`build`].
14
15use std::collections::{BTreeSet, HashMap};
16
17use serde::Serialize;
18
19use super::pr_flow::{ChecksFlowEvent, MergeFlowEvent, PrFlowBy, PrFlowSnapshot, ReviewFlowEvent};
20
21/// The task a pull request belongs to.
22#[derive(Debug, Clone, PartialEq, Eq, Serialize, ts_rs::TS)]
23#[ts(export, export_to = "../../../frontend/types/rpc/")]
24pub struct ReviewsTask {
25    /// How a message names it: `#12`, or `work#12` off the default board.
26    #[serde(rename = "ref")]
27    pub task_ref: String,
28    #[ts(type = "number")]
29    pub num: i64,
30    pub title: String,
31    /// The task's own state: `open`, `claimed`, `review`, `done`, ...
32    pub state: String,
33}
34
35/// A card that names a pull request, as [`build`] reads it.
36#[derive(Debug, Clone, PartialEq, Eq)]
37pub struct CardIn {
38    pub task: ReviewsTask,
39    /// The agent that holds (or last held) the task, lower case; empty when none.
40    pub agent: String,
41    /// `owner/repo`, lower case.
42    pub repo: String,
43    pub number: u64,
44    pub branch: String,
45    pub merged_at_ms: Option<i64>,
46    pub released_in: String,
47    pub updated_at_ms: i64,
48}
49
50/// One reviewer kind's latest verdict.
51#[derive(Debug, Clone, PartialEq, Eq, Serialize, ts_rs::TS)]
52#[ts(export, export_to = "../../../frontend/types/rpc/")]
53pub struct ReviewsVerdict {
54    pub by: PrFlowBy,
55    /// `approved`, `changes_requested`, `commented`, or another well-formed name.
56    pub state: String,
57    #[serde(skip_serializing_if = "Option::is_none")]
58    #[ts(optional)]
59    pub head: Option<String>,
60    #[ts(type = "number")]
61    pub at_ms: u64,
62    /// The pull request's head moved after this verdict: it was given on an older commit.
63    pub stale: bool,
64}
65
66/// The checks of the PR's newest head srv heard of. A PR whose newest head has no checks event (a push, or a verdict on a
67/// commit the checks did not name) has none: checks of an older head are not shown as the current ones.
68#[derive(Debug, Clone, PartialEq, Eq, Serialize, ts_rs::TS)]
69#[ts(export, export_to = "../../../frontend/types/rpc/")]
70pub struct ReviewsChecks {
71    /// `passing`, `failing`, or another well-formed name (`pending`).
72    pub state: String,
73    #[serde(skip_serializing_if = "Option::is_none")]
74    #[ts(optional)]
75    pub head: Option<String>,
76    #[ts(type = "number")]
77    pub at_ms: u64,
78}
79
80/// Who has to act next.
81#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, ts_rs::TS)]
82#[ts(export, export_to = "../../../frontend/types/rpc/")]
83#[serde(rename_all = "lowercase")]
84pub enum WaitsOn {
85    /// A decision only a person makes.
86    Person,
87    /// The agent that wrote it.
88    Author,
89    /// A reviewer: no verdict on the current head.
90    Reviewer,
91    /// A required check that is still running.
92    Ci,
93    /// The merge queue.
94    Queue,
95    /// Nothing: merged or closed.
96    None,
97    /// The rule could not place it.
98    Unknown,
99}
100
101impl WaitsOn {
102    /// The name the board and the route use for it (the same as its serialized form).
103    pub fn as_str(self) -> &'static str {
104        match self {
105            WaitsOn::Person => "person",
106            WaitsOn::Author => "author",
107            WaitsOn::Reviewer => "reviewer",
108            WaitsOn::Ci => "ci",
109            WaitsOn::Queue => "queue",
110            WaitsOn::None => "none",
111            WaitsOn::Unknown => "unknown",
112        }
113    }
114
115    /// The kind a name from [`WaitsOn::as_str`] stands for; a name it does not know is `Unknown`.
116    pub fn parse(name: &str) -> WaitsOn {
117        [WaitsOn::Person, WaitsOn::Author, WaitsOn::Reviewer, WaitsOn::Ci, WaitsOn::Queue, WaitsOn::None]
118            .into_iter()
119            .find(|w| w.as_str() == name)
120            .unwrap_or(WaitsOn::Unknown)
121    }
122
123    /// How urgently it needs someone, for the card that has several pull requests: the one that blocks it is the
124    /// most pressing (a person first, nothing last).
125    pub fn urgency(self) -> u8 {
126        match self {
127            WaitsOn::Person => 0,
128            WaitsOn::Author => 1,
129            WaitsOn::Reviewer => 2,
130            WaitsOn::Ci => 3,
131            WaitsOn::Queue => 4,
132            WaitsOn::Unknown => 5,
133            WaitsOn::None => 6,
134        }
135    }
136}
137
138/// A pull request and where it stands.
139#[derive(Debug, Clone, PartialEq, Eq, Serialize, ts_rs::TS)]
140#[ts(export, export_to = "../../../frontend/types/rpc/")]
141pub struct ReviewRow {
142    /// `owner/repo`; none for a PR only an event named.
143    #[serde(skip_serializing_if = "Option::is_none")]
144    #[ts(optional)]
145    pub repo: Option<String>,
146    /// GitHub's numeric repository id, when an event carried it.
147    #[serde(skip_serializing_if = "Option::is_none")]
148    #[ts(optional, type = "number")]
149    pub repo_id: Option<u64>,
150    #[ts(type = "number")]
151    pub number: u64,
152    /// Where it is on the web; none when the repository is unknown.
153    #[serde(skip_serializing_if = "Option::is_none")]
154    #[ts(optional)]
155    pub url: Option<String>,
156    #[serde(skip_serializing_if = "Option::is_none")]
157    #[ts(optional)]
158    pub task: Option<ReviewsTask>,
159    /// The agent it is for (the task's holder, else the one the notices went to).
160    #[serde(skip_serializing_if = "Option::is_none")]
161    #[ts(optional)]
162    pub agent: Option<String>,
163    pub branch: String,
164    /// The latest verdict of each reviewer kind.
165    pub reviews: Vec<ReviewsVerdict>,
166    #[serde(skip_serializing_if = "Option::is_none")]
167    #[ts(optional)]
168    pub checks: Option<ReviewsChecks>,
169    /// `open`, `merged`, or another well-formed name (`closed`).
170    pub merge: String,
171    #[serde(skip_serializing_if = "Option::is_none")]
172    #[ts(optional, type = "number")]
173    pub merged_at_ms: Option<i64>,
174    /// The release that holds the merge, when the task's card knows it.
175    #[serde(skip_serializing_if = "String::is_empty")]
176    pub released_in: String,
177    pub waits_on: WaitsOn,
178    /// A short code for why: `changes_requested`, `checks_failing`, `checks_running`, `no_review`,
179    /// `review_stale`, `awaiting_accept`, `ready_to_merge`, `merged`, `closed`, `task_finished`, `queued`, `unknown`.
180    pub why: String,
181    /// When anything about it last changed, in milliseconds since 1970.
182    #[ts(type = "number")]
183    pub updated_at_ms: i64,
184}
185
186/// The answer of `GET /api/v1/reviews`.
187#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, ts_rs::TS)]
188#[ts(export, export_to = "../../../frontend/types/rpc/")]
189pub struct ReviewsList {
190    /// Newest change first.
191    pub rows: Vec<ReviewRow>,
192    /// When this was built.
193    #[ts(type = "number")]
194    pub as_of_ms: i64,
195    /// When the newest review, checks or merge notice came; none before the first since srv started. A list built
196    /// from notices is only as complete as they are: this is how old that knowledge is.
197    #[serde(skip_serializing_if = "Option::is_none")]
198    #[ts(optional, type = "number")]
199    pub last_notice_at_ms: Option<u64>,
200}
201
202/// What [`waits_on`] reads of one pull request.
203pub struct WaitsInput<'a> {
204    /// `open`, `merged`, `closed`, `queued`, or another name.
205    pub merge: &'a str,
206    pub checks: Option<&'a str>,
207    /// The latest verdict of each reviewer kind: its state, and whether the head moved since.
208    pub reviews: &'a [(&'a str, bool)],
209    /// The task's own state.
210    pub task_state: Option<&'a str>,
211}
212
213/// Who has to act next on a PR, and why. One table; a change of the review system changes this function only.
214///
215/// A bot is never "the person who acts": `person` is only the task waiting for the operator's accept after the
216/// reviewers approved. A PR the table cannot place is `unknown`, never a guess.
217pub fn waits_on(i: &WaitsInput<'_>) -> (WaitsOn, &'static str) {
218    match i.merge {
219        "merged" => return (WaitsOn::None, "merged"),
220        "closed" => return (WaitsOn::None, "closed"),
221        "queued" => return (WaitsOn::Queue, "queued"),
222        _ => {}
223    }
224    // A task that is over (done, cancelled, failed) with a PR no one saw merge or close waits on no one.
225    if matches!(i.task_state, Some("done" | "cancelled" | "failed")) {
226        return (WaitsOn::None, "task_finished");
227    }
228    if i.checks == Some("failing") {
229        return (WaitsOn::Author, "checks_failing");
230    }
231    let fresh = |state: &str| i.reviews.iter().any(|(s, stale)| *s == state && !stale);
232    if fresh("changes_requested") {
233        return (WaitsOn::Author, "changes_requested");
234    }
235    if matches!(i.checks, Some(c) if c != "passing") {
236        return (WaitsOn::Ci, "checks_running");
237    }
238    if fresh("approved") {
239        return if i.task_state == Some("review") {
240            (WaitsOn::Person, "awaiting_accept")
241        } else {
242            (WaitsOn::Author, "ready_to_merge")
243        };
244    }
245    if i.reviews.is_empty() {
246        (WaitsOn::Reviewer, "no_review")
247    } else if i.reviews.iter().all(|(_, stale)| *stale) {
248        (WaitsOn::Reviewer, "review_stale")
249    } else {
250        // Only a comment on the current head: no verdict yet.
251        (WaitsOn::Reviewer, "no_review")
252    }
253}
254
255/// The key a pull request has in the events: its repository's id and its number.
256type EventKey = (u64, u64);
257
258/// Binds each pull request the events name to the cards that name it. A card is the one when it has the event's
259/// agent (the notices go to the PR's own agent) and the PR's number. Two cards of one agent with the same number in
260/// different repositories are told apart by a repository id learned from a match with one candidate; with none learned
261/// the event stays unbound. Once the repository is settled, every card of it with that number holds the same pull
262/// request (two tasks of one agent, or one whose holder changed), so each of them gets the events.
263fn bind(cards: &[CardIn], flow: &PrFlowSnapshot) -> HashMap<EventKey, Vec<usize>> {
264    let mut triples: BTreeSet<(String, u64, u64)> = BTreeSet::new();
265    let mut add = |agent: &str, repo_id: u64, number: u64| {
266        triples.insert((agent.to_ascii_lowercase(), repo_id, number));
267    };
268    flow.review.iter().for_each(|e| add(&e.agent, e.pr.repo_id, e.pr.number));
269    flow.checks.iter().for_each(|e| add(&e.agent, e.pr.repo_id, e.pr.number));
270    flow.merge.iter().for_each(|e| add(&e.agent, e.pr.repo_id, e.pr.number));
271
272    let candidates = |agent: &str, number: u64| -> Vec<usize> {
273        cards.iter().enumerate().filter(|(_, c)| c.number == number && !c.agent.is_empty() && c.agent == agent).map(|(i, _)| i).collect()
274    };
275    let of_pr = |repo: &str, number: u64| -> Vec<usize> {
276        cards.iter().enumerate().filter(|(_, c)| c.number == number && c.repo == repo).map(|(i, _)| i).collect()
277    };
278    let mut bound: HashMap<EventKey, Vec<usize>> = HashMap::new();
279    let mut known: HashMap<u64, String> = HashMap::new();
280    let mut later: Vec<EventKey> = Vec::new();
281    for (agent, repo_id, number) in &triples {
282        let found = candidates(agent, *number);
283        let repos: BTreeSet<&str> = found.iter().map(|&i| cards[i].repo.as_str()).collect();
284        if repos.len() == 1 {
285            let repo = &cards[found[0]].repo;
286            // One repository id is one repository: a card the id does not match is not this PR's card.
287            if known.iter().any(|(id, r)| (id == repo_id) != (r == repo)) {
288                continue;
289            }
290            known.insert(*repo_id, repo.clone());
291            let slot = bound.entry((*repo_id, *number)).or_default();
292            for i in of_pr(repo, *number) {
293                if !slot.contains(&i) {
294                    slot.push(i);
295                }
296            }
297        } else {
298            later.push((*repo_id, *number));
299        }
300    }
301    for (repo_id, number) in later {
302        if bound.contains_key(&(repo_id, number)) {
303            continue;
304        }
305        let Some(repo) = known.get(&repo_id) else { continue };
306        // The repository is known: every card of it with this number (a holder may have changed).
307        let all = of_pr(repo, number);
308        if !all.is_empty() {
309            bound.insert((repo_id, number), all);
310        }
311    }
312    bound
313}
314
315/// The newest of `events` by time, per `key`.
316fn newest<'a, T>(events: &'a [T], at: impl Fn(&T) -> u64) -> Option<&'a T> {
317    events.iter().max_by_key(|e| at(e))
318}
319
320/// One pull request's events, picked from the snapshot by its key.
321struct Events<'a> {
322    review: Vec<&'a ReviewFlowEvent>,
323    checks: Vec<&'a ChecksFlowEvent>,
324    merge: Vec<&'a MergeFlowEvent>,
325}
326
327fn events_of<'a>(flow: &'a PrFlowSnapshot, key: EventKey) -> Events<'a> {
328    let is = |repo_id: u64, number: u64| (repo_id, number) == key;
329    Events {
330        review: flow.review.iter().filter(|e| is(e.pr.repo_id, e.pr.number)).collect(),
331        checks: flow.checks.iter().filter(|e| is(e.pr.repo_id, e.pr.number)).collect(),
332        merge: flow.merge.iter().filter(|e| is(e.pr.repo_id, e.pr.number)).collect(),
333    }
334}
335
336/// The row for one pull request from its events and, when a task names it, its card.
337fn row_of(ev: &Events<'_>, key: Option<EventKey>, card: Option<&CardIn>, orphan_agent: Option<&str>) -> ReviewRow {
338    // The newest commit anything named: the latest event of any kind (a verdict of any reviewer, or checks) that carries
339    // a head. A verdict given on another commit, no later than that event, is of an older head.
340    let newest_head: Option<(&str, u64)> = ev
341        .review
342        .iter()
343        .filter_map(|e| e.head.as_deref().map(|h| (h, e.at_ms)))
344        .chain(ev.checks.iter().filter_map(|e| e.head.as_deref().map(|h| (h, e.at_ms))))
345        .max_by_key(|(_, at)| *at);
346    // The checks of that commit: the newest checks event that names it, or names no commit (it cannot be told apart).
347    // Failing checks of commit A followed by an approval of commit B are not B's failure, and passing ones of A are
348    // not B's pass: with no checks event for B there are none to show, and none to wait on.
349    let checks = ev
350        .checks
351        .iter()
352        .copied()
353        .filter(|e| match (&e.head, newest_head) {
354            (Some(h), Some((nh, _))) => h.as_str() == nh,
355            _ => true,
356        })
357        .max_by_key(|e| e.at_ms)
358        .map(|e| ReviewsChecks { state: e.state.clone(), head: e.head.clone(), at_ms: e.at_ms });
359    // Verdicts: the newest of each reviewer kind.
360    let mut verdicts: Vec<ReviewsVerdict> = Vec::new();
361    for by in [PrFlowBy::Bot, PrFlowBy::Codex, PrFlowBy::Person] {
362        let mine: Vec<&ReviewFlowEvent> = ev.review.iter().copied().filter(|e| e.by == by).collect();
363        if let Some(e) = newest(&mine, |e| e.at_ms) {
364            let moved = match (&e.head, newest_head) {
365                (Some(h), Some((nh, at))) => nh != h.as_str() && at >= e.at_ms,
366                _ => false,
367            };
368            verdicts.push(ReviewsVerdict { by, state: e.state.clone(), head: e.head.clone(), at_ms: e.at_ms, stale: moved });
369        }
370    }
371    let merge_event = ev.merge.iter().max_by_key(|e| e.at_ms).map(|e| e.state.clone());
372    let merge = merge_event.or_else(|| card.and_then(|c| c.merged_at_ms).map(|_| "merged".to_string())).unwrap_or_else(|| "open".into());
373    let pairs: Vec<(&str, bool)> = verdicts.iter().map(|v| (v.state.as_str(), v.stale)).collect();
374    let task_state = card.map(|c| c.task.state.as_str());
375    let (waits, why) = waits_on(&WaitsInput { merge: &merge, checks: checks.as_ref().map(|c| c.state.as_str()), reviews: &pairs, task_state });
376    let latest_event = ev
377        .review
378        .iter()
379        .map(|e| e.at_ms)
380        .chain(ev.checks.iter().map(|e| e.at_ms))
381        .chain(ev.merge.iter().map(|e| e.at_ms))
382        .max()
383        .map_or(0, |ms| ms as i64);
384    let agent = card.map(|c| c.agent.clone()).filter(|a| !a.is_empty()).or_else(|| orphan_agent.map(str::to_string));
385    ReviewRow {
386        repo: card.map(|c| c.repo.clone()),
387        repo_id: key.map(|k| k.0),
388        number: card.map(|c| c.number).or(key.map(|k| k.1)).unwrap_or(0),
389        url: card.map(|c| format!("https://github.com/{}/pull/{}", c.repo, c.number)),
390        task: card.map(|c| c.task.clone()),
391        agent,
392        branch: card.map(|c| c.branch.clone()).unwrap_or_default(),
393        reviews: verdicts,
394        checks,
395        merge,
396        merged_at_ms: card.and_then(|c| c.merged_at_ms),
397        released_in: card.map(|c| c.released_in.clone()).unwrap_or_default(),
398        waits_on: waits,
399        why: why.to_string(),
400        updated_at_ms: latest_event.max(card.map_or(0, |c| c.updated_at_ms)),
401    }
402}
403
404/// The list: a row for each card that names a pull request, and one for each pull request an event named that
405/// no card holds, newest change first. `cards` is whatever the caller may see.
406pub fn build(cards: &[CardIn], flow: &PrFlowSnapshot, now_ms: i64) -> ReviewsList {
407    let bound = bind(cards, flow);
408    let mut by_card: HashMap<usize, EventKey> = HashMap::new();
409    for (key, idxs) in &bound {
410        for &i in idxs {
411            // A card holds one PR; if two keys claim it, the older binding (lower repo id) keeps it.
412            by_card.entry(i).and_modify(|k| *k = (*k).min(*key)).or_insert(*key);
413        }
414    }
415    let mut rows: Vec<ReviewRow> = Vec::new();
416    for (i, card) in cards.iter().enumerate() {
417        let key = by_card.get(&i).copied();
418        let ev = key.map(|k| events_of(flow, k)).unwrap_or(Events { review: vec![], checks: vec![], merge: vec![] });
419        rows.push(row_of(&ev, key, Some(card), None));
420    }
421    // Pull requests the events named and no card holds.
422    let used: BTreeSet<EventKey> = by_card.values().copied().collect();
423    let mut orphans: HashMap<EventKey, String> = HashMap::new();
424    let all = flow
425        .review
426        .iter()
427        .map(|e| (e.pr, e.agent.as_str()))
428        .chain(flow.checks.iter().map(|e| (e.pr, e.agent.as_str())))
429        .chain(flow.merge.iter().map(|e| (e.pr, e.agent.as_str())));
430    for (pr, agent) in all {
431        let key = (pr.repo_id, pr.number);
432        if !used.contains(&key) {
433            orphans.entry(key).or_insert_with(|| agent.to_string());
434        }
435    }
436    for (key, agent) in orphans {
437        rows.push(row_of(&events_of(flow, key), Some(key), None, Some(&agent)));
438    }
439    rows.sort_by(|a, b| b.updated_at_ms.cmp(&a.updated_at_ms).then(a.number.cmp(&b.number)));
440    ReviewsList { rows, as_of_ms: now_ms, last_notice_at_ms: flow.bot.last_notice_at_ms }
441}
442
443#[cfg(test)]
444#[path = "reviews_tests.rs"]
445mod tests;