1use 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
27pub const RECENT_MAX: usize = 100;
29
30const STATE_MAX: usize = 24;
33
34const HEAD_KEPT: usize = 12;
36
37const SAFE_MAX: u64 = (1 << 53) - 1;
39
40#[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#[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 Bot,
57 Codex,
59 Person,
61}
62
63#[derive(Debug, Clone, PartialEq, Eq, Serialize, ts_rs::TS)]
65#[ts(export, export_to = "../../../frontend/types/rpc/")]
66pub struct ReviewFlowEvent {
67 pub id: String,
69 #[ts(type = "number")]
71 pub at_ms: u64,
72 pub agent: String,
74 pub pr: PrRef,
75 #[ts(type = "\"approved\" | \"changes_requested\" | \"commented\" | (string & {})")]
77 pub state: String,
78 pub by: PrFlowBy,
79 #[serde(skip_serializing_if = "Option::is_none")]
81 #[ts(optional)]
82 pub head: Option<String>,
83}
84
85#[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 #[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#[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 #[ts(type = "\"merged\" | (string & {})")]
113 pub state: String,
114}
115
116#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, ts_rs::TS)]
118#[ts(export, export_to = "../../../frontend/types/rpc/")]
119pub struct PrFlowBot {
120 #[ts(type = "number | null")]
122 pub last_notice_at_ms: Option<u64>,
123}
124
125#[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#[derive(Debug, Clone, PartialEq, Eq)]
137pub enum Accepted {
138 Review(ReviewFlowEvent),
139 Checks(ChecksFlowEvent),
140 Merge(MergeFlowEvent),
141}
142
143pub struct Notice<'a> {
145 pub id: &'a str,
147 pub agent: &'a str,
149 pub text: &'a str,
151 pub genuine: bool,
153}
154
155fn 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
162fn positive(value: &Value) -> Option<u64> {
164 value.as_u64().filter(|n| (1..=SAFE_MAX).contains(n))
165}
166
167fn 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
175fn 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
185fn 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
193const OBJECTS_MAX: usize = 3;
195
196pub 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
206fn 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
236fn 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 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
280pub fn install(broker: Arc<Broker>) {
282 let _ = FLOW.set(Flow { broker, recent: Mutex::default() });
283}
284
285impl Flow {
286 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
299static CARDS: OnceLock<Arc<Store>> = OnceLock::new();
302
303pub fn install_cards(store: Arc<Store>) {
305 let _ = CARDS.set(store);
306}
307
308fn 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
318pub(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
334pub fn note(accepted: &Accepted) {
337 if let Some(cards) = CARDS.get() {
338 if let Err(e) = cards.work_card_pr_flow_apply(¬e_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
348pub fn accept_now(flow: Option<&Value>, notice: &Notice<'_>) -> Vec<Accepted> {
351 accept(flow, notice, agentmux_common::time::now_ms() as u64)
352}
353
354pub fn note_all(accepted: &[Accepted]) {
356 accepted.iter().for_each(note);
357}
358
359pub 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;