Skip to main content

agentmux_srv_core/backend/kanban/
pr_events.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4//! A change to a pull request, as it reaches this install (the Kanban and GitHub spec, §5): the intake that
5//! trusts it or not, matches it to a card and writes the card's list.
6//!
7//! An event is a claim until its sender is proven. It is applied only when **both** hold: the signed sender is
8//! the GitHub integration's own service identity, and the signed text itself says `"kind":"pr_event"` (the
9//! signature covers the text, not a row's own kind). Anything else is dropped and counted, never applied. The
10//! repository's owner must be one the install already trusts for pull request notices. A proven event can still
11//! carry a forged hint (any agent can write any agent tag), so a hint alone only ever **shows** (§10): a pull
12//! request that is not already on the card, and was not opened by AgentMux's own identity, is kept as an
13//! unmatched line and never linked.
14//!
15//! The relay delivers it as the field of a signed notice; wiring that in is the relay half's seam. This is what
16//! happens once an event is read from the verified text. The kinds of event it applies today are the pull
17//! request's own states (`opened`, `reopened`, `closed`, `merged`); `review`, `checks` and `release` are read
18//! and set aside until the card shows them.
19
20use 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
30/// How long a delivery id is remembered, so a replay is ignored.
31const 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/// One change to a pull request. Ids, numbers and states only: no title, body, branch, diff or author.
46#[derive(Debug, Clone, PartialEq, Deserialize)]
47pub struct PrEvent {
48    /// `owner/name`.
49    pub repo: String,
50    #[serde(default)]
51    pub number: u64,
52    pub action: PrAction,
53    /// The pull request's head commit, when the event says.
54    #[serde(default)]
55    pub head: Option<String>,
56    /// GitHub's own time for the change: epoch milliseconds, or an RFC 3339 string.
57    #[serde(default)]
58    pub updated_at: Value,
59    /// One per change, so a replay is ignored (`id` is read as it when `delivery` is absent).
60    #[serde(default)]
61    pub delivery: String,
62    /// The task reference read from the pull request (`#12`, `board#12`).
63    #[serde(default)]
64    pub task_ref: Option<String>,
65    /// The agent tag read from the pull request: an agent id.
66    #[serde(default)]
67    pub agent: Option<String>,
68    /// Whether AgentMux's own GitHub identity opened the pull request (`by_app` is read as it when it is absent).
69    #[serde(default)]
70    pub by_agentmux: bool,
71}
72
73/// The `pr_event` a verified signed text carries, or `None` when its kind is not that or it is malformed.
74pub 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
82/// `v` with the fields an event may name another way written as ours, where ours is absent (or null): `id` as
83/// `delivery`, `by_app` as `by_agentmux`, and `task` (a board and a number, either null) as `task_ref`. Ours wins
84/// when both are there, and a value of another type is left for the parse to refuse, as it is for any field.
85fn 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/// What the intake did with an event.
119#[derive(Debug, Clone, PartialEq, Eq)]
120pub enum Outcome {
121    /// It reached a card's list.
122    Applied { work_id: String, changed: bool, newly_merged: bool },
123    /// No card: kept on the unmatched list for a person to link.
124    Unmatched(Why),
125    /// Read and set aside: a kind the card does not show yet.
126    Ignored(&'static str),
127    /// Not applied, and counted.
128    Dropped(&'static str),
129}
130
131/// What the install trusts the sender and the repository on.
132pub struct Trust<'a> {
133    /// The signed sender is the GitHub integration's own service identity.
134    pub from_integration: bool,
135    /// The organisations whose pull request notices this install takes (lower case).
136    pub trusted_owners: &'a [String],
137}
138
139/// The intake: remembers the deliveries it saw and what it dropped.
140#[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    /// How many events were dropped, by reason.
153    pub fn dropped(&self) -> HashMap<&'static str, u64> {
154        self.dropped.lock().unwrap_or_else(|e| e.into_inner()).clone()
155    }
156
157    /// A delivery id seen in the last hour is a replay; otherwise it is remembered.
158    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    /// Apply one event. `agent_of` says whether an agent id is an agent of this computer.
168    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                // A pull request from outside that names one of our task numbers: shown, never linked.
218                Why::Outsider
219            }
220            Matched::Unmatched(why) => why,
221        };
222        // Only a pull request whose tag names an agent of this computer is kept; anything else is no card's here.
223        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;