Skip to main content

agentmux_srv_core/backend/
pr_flow.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! "The review of PR N for agent A: approved, at T" and "the checks of PR N: failing": the `review-flow`,
5//! `checks-flow` and `merge-flow` events and their short lists of recent ones, for the review bot and CI nodes
6//! of the Atlas agent map (spec `SPEC_REVIEW_AND_CHECKS_FLOW_EVENTS_2026_11_14.md`).
7//!
8//! They carry ids, numbers, states and times only. A repository is its numeric id, never a name; there is no
9//! field for a title, a branch, a URL, a review body, a log or a login, so none can leak through them.
10//!
11//! The data is a small `flow` object the relay sends beside a review, CI or merge notice. It is not part of
12//! the notice's signature, so it is advisory and applied only with the notice it belongs to: that notice must
13//! have verified and be fresh, and the object's PR number must be the one in the signed text's first line
14//! (see [`accept`]). The recent lists live in memory only and are read with `GET /api/v1/pr-flow`.
15
16use std::collections::VecDeque;
17use std::sync::{Arc, Mutex, OnceLock};
18
19use serde::Serialize;
20use serde_json::Value;
21
22use super::mps::Broker;
23use super::mps_events::{ChecksFlow, MergeFlow, ReviewFlow};
24use super::storage::store::Store;
25use super::storage::work_card_prs::{FlowFact, FlowNote};
26
27/// How many recent events of each kind are kept.
28pub const RECENT_MAX: usize = 100;
29
30/// The longest a state name is: it is a token of lower-case letters and `_`, so a state this version does not
31/// name (`pending`, `requested`, `closed`) is carried, not refused.
32const STATE_MAX: usize = 24;
33
34/// Characters of the head commit kept.
35const HEAD_KEPT: usize = 12;
36
37/// The largest whole number a JavaScript number holds exactly (2^53 - 1).
38const SAFE_MAX: u64 = (1 << 53) - 1;
39
40/// A pull request by GitHub's own numbers.
41#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, ts_rs::TS)]
42#[ts(export, export_to = "../../../frontend/types/rpc/")]
43pub struct PrRef {
44    #[ts(type = "number")]
45    pub repo_id: u64,
46    #[ts(type = "number")]
47    pub number: u64,
48}
49
50/// What kind of reviewer: coarse, never a login.
51#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, ts_rs::TS)]
52#[ts(export, export_to = "../../../frontend/types/rpc/")]
53#[serde(rename_all = "lowercase")]
54pub enum PrFlowBy {
55    /// The review bot (muxreview).
56    Bot,
57    /// The Codex reviewer.
58    Codex,
59    /// A person.
60    Person,
61}
62
63/// A review of a PR, for the agent it belongs to.
64#[derive(Debug, Clone, PartialEq, Eq, Serialize, ts_rs::TS)]
65#[ts(export, export_to = "../../../frontend/types/rpc/")]
66pub struct ReviewFlowEvent {
67    /// The relay message's id: a redelivery is the same event.
68    pub id: String,
69    /// When this srv accepted the notice, in milliseconds since 1970.
70    #[ts(type = "number")]
71    pub at_ms: u64,
72    /// The local agent the notice was delivered to: the PR's own agent.
73    pub agent: String,
74    pub pr: PrRef,
75    /// `approved`, `changes_requested` or `commented`; any other well-formed name is kept and drawn neutral.
76    #[ts(type = "\"approved\" | \"changes_requested\" | \"commented\" | (string & {})")]
77    pub state: String,
78    pub by: PrFlowBy,
79    /// The first 12 hex characters of the reviewed commit, when the notice has one.
80    #[serde(skip_serializing_if = "Option::is_none")]
81    #[ts(optional)]
82    pub head: Option<String>,
83}
84
85/// The checks of a PR's head commit.
86#[derive(Debug, Clone, PartialEq, Eq, Serialize, ts_rs::TS)]
87#[ts(export, export_to = "../../../frontend/types/rpc/")]
88pub struct ChecksFlowEvent {
89    pub id: String,
90    #[ts(type = "number")]
91    pub at_ms: u64,
92    pub agent: String,
93    pub pr: PrRef,
94    /// `passing` or `failing`; any other well-formed name (`pending`) is kept and drawn neutral.
95    #[ts(type = "\"passing\" | \"failing\" | (string & {})")]
96    pub state: String,
97    #[serde(skip_serializing_if = "Option::is_none")]
98    #[ts(optional)]
99    pub head: Option<String>,
100}
101
102/// The end of a PR's lines on the map.
103#[derive(Debug, Clone, PartialEq, Eq, Serialize, ts_rs::TS)]
104#[ts(export, export_to = "../../../frontend/types/rpc/")]
105pub struct MergeFlowEvent {
106    pub id: String,
107    #[ts(type = "number")]
108    pub at_ms: u64,
109    pub agent: String,
110    pub pr: PrRef,
111    /// `merged`; any other well-formed name (`closed`) is kept and drawn neutral.
112    #[ts(type = "\"merged\" | (string & {})")]
113    pub state: String,
114}
115
116/// The bot's own state as this srv sees it.
117#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, ts_rs::TS)]
118#[ts(export, export_to = "../../../frontend/types/rpc/")]
119pub struct PrFlowBot {
120    /// When the newest accepted notice of any kind came; `null` before the first since this srv started.
121    #[ts(type = "number | null")]
122    pub last_notice_at_ms: Option<u64>,
123}
124
125/// The answer of `GET /api/v1/pr-flow`: the recent events of each kind, oldest first.
126#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, ts_rs::TS)]
127#[ts(export, export_to = "../../../frontend/types/rpc/")]
128pub struct PrFlowSnapshot {
129    pub review: Vec<ReviewFlowEvent>,
130    pub checks: Vec<ChecksFlowEvent>,
131    pub merge: Vec<MergeFlowEvent>,
132    pub bot: PrFlowBot,
133}
134
135/// A notice's `flow` object that passed every check, as the event it makes.
136#[derive(Debug, Clone, PartialEq, Eq)]
137pub enum Accepted {
138    Review(ReviewFlowEvent),
139    Checks(ChecksFlowEvent),
140    Merge(MergeFlowEvent),
141}
142
143/// What the call site knows of one pulled notice.
144pub struct Notice<'a> {
145    /// The relay message's id.
146    pub id: &'a str,
147    /// The local agent it was delivered to.
148    pub agent: &'a str,
149    /// The signed text: its first line names the PR.
150    pub text: &'a str,
151    /// Its signature verified under a trusted key and it is fresh (not expired, not forged, not unsigned).
152    pub genuine: bool,
153}
154
155/// `value` as a token of lower-case letters and `_`, 1 to [`STATE_MAX`] long.
156fn token(value: &Value) -> Option<String> {
157    let s = value.as_str()?;
158    let ok = (1..=STATE_MAX).contains(&s.len()) && s.bytes().all(|b| b.is_ascii_lowercase() || b == b'_');
159    ok.then(|| s.to_string())
160}
161
162/// `value` as a positive whole number a JavaScript number holds exactly.
163fn positive(value: &Value) -> Option<u64> {
164    value.as_u64().filter(|n| (1..=SAFE_MAX).contains(n))
165}
166
167/// The commit in `value`, kept to [`HEAD_KEPT`] characters: 7 to 40 hex characters, or `Err` when it is
168/// there and is not.
169fn head_of(value: Option<&Value>) -> Result<Option<String>, ()> {
170    let Some(value) = value.filter(|v| !v.is_null()) else { return Ok(None) };
171    let s = value.as_str().filter(|s| (7..=40).contains(&s.len()) && s.bytes().all(|b| b.is_ascii_hexdigit())).ok_or(())?;
172    Ok(Some(s[..HEAD_KEPT.min(s.len())].to_ascii_lowercase()))
173}
174
175/// The reviewer kind in `value`.
176fn by_of(value: Option<&Value>) -> Option<PrFlowBy> {
177    match value?.as_str()? {
178        "bot" => Some(PrFlowBy::Bot),
179        "codex" => Some(PrFlowBy::Codex),
180        "person" => Some(PrFlowBy::Person),
181        _ => None,
182    }
183}
184
185/// The number after the first `PR #` of `text`'s first line.
186fn pr_in_first_line(text: &str) -> Option<u64> {
187    let line = text.lines().next()?;
188    let rest = &line[line.find("PR #")? + 4..];
189    let end = rest.find(|c: char| !c.is_ascii_digit()).unwrap_or(rest.len());
190    rest[..end].parse().ok()
191}
192
193/// The most objects one notice may carry: a "ready to merge" notice is both an approval and green checks.
194const OBJECTS_MAX: usize = 3;
195
196/// The events `flow` makes for `notice`, at `at_ms`: `flow` is one object, or a list of up to [`OBJECTS_MAX`]
197/// (the rest are ignored), each judged on its own by [`accept_one`]. None for a notice that has none, is not
198/// genuine and fresh, or whose objects are all malformed.
199pub fn accept(flow: Option<&Value>, notice: &Notice<'_>, at_ms: u64) -> Vec<Accepted> {
200    match flow {
201        Some(Value::Array(list)) => list.iter().take(OBJECTS_MAX).filter_map(|one| accept_one(Some(one), notice, at_ms)).collect(),
202        other => accept_one(other, notice, at_ms).into_iter().collect(),
203    }
204}
205
206/// The event one `flow` object makes for `notice`, at `at_ms`, or `None`: the notice carries no object, the notice
207/// is not genuine and fresh, the object is malformed in any field, or its PR is not the one the signed text names.
208///
209/// The last check ties the unsigned object to the signed message: a wording change that moves the PR number
210/// out of the first line fails closed (no event) instead of drawing a wrong line.
211fn accept_one(flow: Option<&Value>, notice: &Notice<'_>, at_ms: u64) -> Option<Accepted> {
212    let flow = flow?.as_object().filter(|_| notice.genuine && !notice.id.is_empty() && !notice.agent.is_empty())?;
213    let pr = PrRef { repo_id: positive(flow.get("repo_id")?)?, number: positive(flow.get("pr")?)? };
214    if pr_in_first_line(notice.text) != Some(pr.number) {
215        return None;
216    }
217    let state = token(flow.get("state")?)?;
218    let head = head_of(flow.get("head")).ok()?;
219    let (id, agent) = (notice.id.to_string(), notice.agent.to_string());
220    match flow.get("kind")?.as_str()? {
221        "review" => Some(Accepted::Review(ReviewFlowEvent { id, at_ms, agent, pr, state, by: by_of(flow.get("by"))?, head })),
222        "checks" => Some(Accepted::Checks(ChecksFlowEvent { id, at_ms, agent, pr, state, head })),
223        "merge" => Some(Accepted::Merge(MergeFlowEvent { id, at_ms, agent, pr, state })),
224        _ => None,
225    }
226}
227
228#[derive(Default)]
229struct Recent {
230    review: VecDeque<ReviewFlowEvent>,
231    checks: VecDeque<ChecksFlowEvent>,
232    merge: VecDeque<MergeFlowEvent>,
233    last_notice_at_ms: Option<u64>,
234}
235
236/// Adds `event` to `recent` unless one with its `id` is already there, dropping the oldest once there are
237/// [`RECENT_MAX`]. Whether it was added.
238fn remember<T>(recent: &mut VecDeque<T>, event: T, id: impl Fn(&T) -> &str) -> bool {
239    if recent.iter().any(|e| id(e) == id(&event)) {
240        return false;
241    }
242    if recent.len() >= RECENT_MAX {
243        recent.pop_front();
244    }
245    recent.push_back(event);
246    true
247}
248
249impl Recent {
250    /// Keeps `accepted`; whether it is new, so it is published once.
251    fn keep(&mut self, accepted: &Accepted) -> bool {
252        let (added, at_ms) = match accepted {
253            Accepted::Review(e) => (remember(&mut self.review, e.clone(), |e| &e.id), e.at_ms),
254            Accepted::Checks(e) => (remember(&mut self.checks, e.clone(), |e| &e.id), e.at_ms),
255            Accepted::Merge(e) => (remember(&mut self.merge, e.clone(), |e| &e.id), e.at_ms),
256        };
257        if added {
258            self.last_notice_at_ms = Some(self.last_notice_at_ms.map_or(at_ms, |last| last.max(at_ms)));
259        }
260        added
261    }
262
263    fn snapshot(&self) -> PrFlowSnapshot {
264        PrFlowSnapshot {
265            review: self.review.iter().cloned().collect(),
266            checks: self.checks.iter().cloned().collect(),
267            merge: self.merge.iter().cloned().collect(),
268            bot: PrFlowBot { last_notice_at_ms: self.last_notice_at_ms },
269        }
270    }
271}
272
273struct Flow {
274    broker: Arc<Broker>,
275    recent: Mutex<Recent>,
276}
277
278static FLOW: OnceLock<Flow> = OnceLock::new();
279
280/// Start publishing on `broker` for the rest of the process. The first call wins.
281pub fn install(broker: Arc<Broker>) {
282    let _ = FLOW.set(Flow { broker, recent: Mutex::default() });
283}
284
285impl Flow {
286    /// Keeps `accepted` and, when it is new, publishes it as its kind's event.
287    fn record(&self, accepted: &Accepted) {
288        if !self.recent.lock().unwrap_or_else(|e| e.into_inner()).keep(accepted) {
289            return;
290        }
291        match accepted {
292            Accepted::Review(e) => self.broker.publish_event::<ReviewFlow>(e, vec![], 0),
293            Accepted::Checks(e) => self.broker.publish_event::<ChecksFlow>(e, vec![], 0),
294            Accepted::Merge(e) => self.broker.publish_event::<MergeFlow>(e, vec![], 0),
295        }
296    }
297}
298
299/// The board's store, where a notice is also put on the card rows of the pull request it names (the card's badge and
300/// chips ride with the card and survive a restart: SPEC_FOLD_REVIEWS_INTO_THE_KANBAN_2026_11_22.md ยง3).
301static CARDS: OnceLock<Arc<Store>> = OnceLock::new();
302
303/// Start putting accepted notices on the cards in `store` for the rest of the process. The first call wins.
304pub fn install_cards(store: Arc<Store>) {
305    let _ = CARDS.set(store);
306}
307
308/// `accepted` as what it says about a pull request.
309fn note_of(accepted: &Accepted) -> FlowNote {
310    let (id, agent, pr, at_ms, fact) = match accepted {
311        Accepted::Review(e) => (&e.id, &e.agent, e.pr, e.at_ms, FlowFact::Review { by: by_name(e.by).into(), state: e.state.clone(), head: e.head.clone() }),
312        Accepted::Checks(e) => (&e.id, &e.agent, e.pr, e.at_ms, FlowFact::Checks { state: e.state.clone(), head: e.head.clone() }),
313        Accepted::Merge(e) => (&e.id, &e.agent, e.pr, e.at_ms, FlowFact::Merge { state: e.state.clone() }),
314    };
315    FlowNote { id: id.clone(), agent: agent.to_ascii_lowercase(), repo_id: pr.repo_id, number: pr.number, at_ms: at_ms as i64, fact }
316}
317
318/// Every event of `snapshot` as what it says about a pull request.
319pub(crate) fn notes_of(snapshot: &PrFlowSnapshot) -> Vec<FlowNote> {
320    let review = snapshot.review.iter().cloned().map(Accepted::Review);
321    let checks = snapshot.checks.iter().cloned().map(Accepted::Checks);
322    let merge = snapshot.merge.iter().cloned().map(Accepted::Merge);
323    review.chain(checks).chain(merge).map(|a| note_of(&a)).collect()
324}
325
326fn by_name(by: PrFlowBy) -> &'static str {
327    match by {
328        PrFlowBy::Bot => "bot",
329        PrFlowBy::Codex => "codex",
330        PrFlowBy::Person => "person",
331    }
332}
333
334/// Records and publishes `accepted`, after putting it on the cards it names, so a board read on the event sees it.
335/// Does nothing before [`install`] and [`install_cards`].
336pub fn note(accepted: &Accepted) {
337    if let Some(cards) = CARDS.get() {
338        // Applying is idempotent (a notice older than a row's own is ignored), so a redelivery changes nothing.
339        if let Err(e) = cards.work_card_pr_flow_apply(&note_of(accepted), agentmux_common::time::now_ms()) {
340            tracing::warn!(error = %e, "pr flow: could not put a notice on the cards; the badge may lag the event");
341        }
342    }
343    if let Some(flow) = FLOW.get() {
344        flow.record(accepted);
345    }
346}
347
348/// The event `flow` makes for a notice delivered now, if any, to be passed to [`note`] once the notice is
349/// accepted. See [`accept`].
350pub fn accept_now(flow: Option<&Value>, notice: &Notice<'_>) -> Vec<Accepted> {
351    accept(flow, notice, agentmux_common::time::now_ms() as u64)
352}
353
354/// [`note`] for each of `accepted`.
355pub fn note_all(accepted: &[Accepted]) {
356    accepted.iter().for_each(note);
357}
358
359/// The recent events, oldest first.
360pub fn recent() -> PrFlowSnapshot {
361    FLOW.get().map(|f| f.recent.lock().unwrap_or_else(|e| e.into_inner()).snapshot()).unwrap_or_default()
362}
363
364#[cfg(test)]
365#[path = "pr_flow_tests.rs"]
366mod tests;