agentmux_srv_core/backend/kanban/
pr_events.rs1use std::collections::HashMap;
21use std::sync::Mutex;
22
23use serde::Deserialize;
24use serde_json::Value;
25
26use crate::backend::storage::store::Store;
27use crate::backend::storage::work_card_prs::{github_repo, CardPrState, PrReport, PrSource};
28use crate::backend::storage::work_pr_match::{AgentRef, Matched, TaskRef, Why};
29
30const SEEN_FOR_MS: i64 = 60 * 60 * 1000;
32
33#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
34#[serde(rename_all = "snake_case")]
35pub enum PrAction {
36 Opened,
37 Reopened,
38 Closed,
39 Merged,
40 Review,
41 Checks,
42 Release,
43}
44
45#[derive(Debug, Clone, PartialEq, Deserialize)]
47pub struct PrEvent {
48 pub repo: String,
50 #[serde(default)]
51 pub number: u64,
52 pub action: PrAction,
53 #[serde(default)]
55 pub head: Option<String>,
56 #[serde(default)]
58 pub updated_at: Value,
59 #[serde(default)]
61 pub delivery: String,
62 #[serde(default)]
64 pub task_ref: Option<String>,
65 #[serde(default)]
67 pub agent: Option<String>,
68 #[serde(default)]
70 pub by_agentmux: bool,
71}
72
73pub fn parse_pr_event(text: &str) -> Option<PrEvent> {
75 let v: Value = serde_json::from_str(text).ok()?;
76 if v.get("kind").and_then(Value::as_str) != Some("pr_event") {
77 return None;
78 }
79 serde_json::from_value(with_our_names(v)).ok()
80}
81
82fn with_our_names(mut v: Value) -> Value {
86 let Some(obj) = v.as_object_mut() else { return v };
87 let absent = |obj: &serde_json::Map<String, Value>, k: &str| obj.get(k).is_none_or(Value::is_null);
88 if absent(obj, "delivery") {
89 if let Some(id) = obj.get("id").filter(|i| i.is_string()).cloned() {
90 obj.insert("delivery".into(), id);
91 }
92 }
93 if absent(obj, "by_agentmux") {
94 if let Some(flag) = obj.get("by_app").filter(|f| f.is_boolean()).cloned() {
95 obj.insert("by_agentmux".into(), flag);
96 }
97 }
98 if absent(obj, "task_ref") {
99 let task = obj.get("task").and_then(Value::as_object);
100 let n = task.and_then(|t| t.get("n")).and_then(Value::as_u64).filter(|n| *n > 0);
101 let board = task.and_then(|t| t.get("board")).and_then(Value::as_str).filter(|b| !b.is_empty());
102 if let Some(n) = n {
103 let text = board.map_or_else(|| n.to_string(), |b| format!("{b}#{n}"));
104 obj.insert("task_ref".into(), Value::String(text));
105 }
106 }
107 v
108}
109
110fn time_ms(v: &Value) -> Option<i64> {
111 match v {
112 Value::Number(n) => n.as_i64(),
113 Value::String(s) => chrono::DateTime::parse_from_rfc3339(s).ok().map(|d| d.timestamp_millis()),
114 _ => None,
115 }
116}
117
118#[derive(Debug, Clone, PartialEq, Eq)]
120pub enum Outcome {
121 Applied { work_id: String, changed: bool, newly_merged: bool },
123 Unmatched(Why),
125 Ignored(&'static str),
127 Dropped(&'static str),
129}
130
131pub struct Trust<'a> {
133 pub from_integration: bool,
135 pub trusted_owners: &'a [String],
137}
138
139#[derive(Default)]
141pub struct Intake {
142 seen: Mutex<HashMap<String, i64>>,
143 dropped: Mutex<HashMap<&'static str, u64>>,
144}
145
146impl Intake {
147 fn drop_with(&self, why: &'static str) -> Outcome {
148 *self.dropped.lock().unwrap_or_else(|e| e.into_inner()).entry(why).or_default() += 1;
149 Outcome::Dropped(why)
150 }
151
152 pub fn dropped(&self) -> HashMap<&'static str, u64> {
154 self.dropped.lock().unwrap_or_else(|e| e.into_inner()).clone()
155 }
156
157 fn replay(&self, delivery: &str, now_ms: i64) -> bool {
159 if delivery.is_empty() {
160 return false;
161 }
162 let mut seen = self.seen.lock().unwrap_or_else(|e| e.into_inner());
163 seen.retain(|_, at| now_ms - *at < SEEN_FOR_MS);
164 seen.insert(delivery.to_string(), now_ms).is_some()
165 }
166
167 pub fn apply(
169 &self,
170 identity: &Store,
171 ev: &PrEvent,
172 trust: &Trust<'_>,
173 agent_of: &dyn Fn(&str) -> Option<AgentRef>,
174 now_ms: i64,
175 ) -> Outcome {
176 if !trust.from_integration {
177 return self.drop_with("not from the integration");
178 }
179 let Some(repo) = github_repo(&ev.repo).filter(|_| ev.number > 0) else { return self.drop_with("not a pull request") };
180 let owner = repo.split('/').next().unwrap_or("");
181 if !trust.trusted_owners.iter().any(|o| o.eq_ignore_ascii_case(owner)) {
182 return self.drop_with("untrusted owner");
183 }
184 if self.replay(&ev.delivery, now_ms) {
185 return self.drop_with("replayed delivery");
186 }
187 let state = match ev.action {
188 PrAction::Opened | PrAction::Reopened => CardPrState::Open,
189 PrAction::Closed => CardPrState::Closed,
190 PrAction::Merged => CardPrState::Merged,
191 PrAction::Review | PrAction::Checks | PrAction::Release => return Outcome::Ignored("not shown on the card yet"),
192 };
193 let updated_at = time_ms(&ev.updated_at).unwrap_or(now_ms);
194 let agent = ev.agent.as_deref().and_then(agent_of);
195 let task_ref = ev.task_ref.as_deref().and_then(TaskRef::parse);
196 let Ok(matched) = identity.work_pr_match(&repo, ev.number, task_ref.as_ref(), agent.as_ref(), now_ms) else {
197 return self.drop_with("the store did not answer");
198 };
199 let why = match matched {
200 Matched::Card(work_id) => {
201 let on_card = identity.work_card_prs(&work_id).map(|l| l.iter().any(|p| p.repo == repo && p.number == ev.number)).unwrap_or(false);
202 if on_card || ev.by_agentmux {
203 let report = PrReport {
204 repo: repo.clone(),
205 number: ev.number,
206 state,
207 head: ev.head.clone(),
208 opened_at: (ev.action == PrAction::Opened).then_some(updated_at),
209 merged_at: (state == CardPrState::Merged).then_some(updated_at),
210 updated_at,
211 };
212 return match identity.work_card_pr_apply(&work_id, &report, PrSource::Event, now_ms) {
213 Ok(a) => Outcome::Applied { work_id, changed: a.changed, newly_merged: a.newly_merged },
214 Err(_) => self.drop_with("the store did not answer"),
215 };
216 }
217 Why::Outsider
219 }
220 Matched::Unmatched(why) => why,
221 };
222 match agent {
224 Some(a) => {
225 let _ = identity.work_pr_unmatched_note(
226 &repo,
227 ev.number,
228 state.as_str(),
229 &a.id,
230 ev.task_ref.as_deref().unwrap_or(""),
231 why,
232 ev.head.as_deref().unwrap_or(""),
233 updated_at,
234 now_ms,
235 );
236 Outcome::Unmatched(why)
237 }
238 None => self.drop_with("no card of this computer"),
239 }
240 }
241}
242
243#[cfg(test)]
244#[path = "pr_events_tests.rs"]
245mod tests;