1use std::collections::HashMap;
13use std::sync::{Mutex, OnceLock};
14use std::time::{Duration, Instant};
15
16use serde_json::{json, Value};
17
18const CACHE_TTL: Duration = Duration::from_secs(120);
19const LIST_LIMIT: &str = "1000";
22const PR_FIELDS: &str = "number,title,headRefName,files,author";
23const GH_TIMEOUT: Duration = Duration::from_secs(20);
24const FILES_NAMED: usize = 3;
26
27#[cfg(windows)]
28const GH_AGENT: &str = "gh-agent.cmd";
29#[cfg(not(windows))]
30const GH_AGENT: &str = "gh-agent";
31const GH: &str = "gh";
33
34#[derive(Debug, Clone, PartialEq, Eq)]
35pub(super) struct OpenPr {
36 pub number: u64,
37 pub title: String,
38 pub branch: String,
39 pub files: Vec<String>,
40 pub agent: String,
42 pub host: Option<String>,
44}
45
46pub(super) fn title_author(title: &str) -> Option<(String, String)> {
48 let (prefix, _) = title.split_once(": ")?;
49 let (agent, host) = prefix.split_once('@')?;
50 let ok = |s: &str| !s.is_empty() && s.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'));
51 (ok(agent) && ok(host)).then(|| (agent.to_string(), host.to_string()))
52}
53
54pub(super) fn parse_pr_list(text: &str) -> Result<Vec<OpenPr>, String> {
56 let list: Value = serde_json::from_str(text.trim()).map_err(|e| format!("the GitHub CLI printed something other than JSON: {e}"))?;
57 let items = list.as_array().ok_or("the GitHub CLI printed something other than a list")?;
58 Ok(items.iter().filter_map(parse_pr).collect())
59}
60
61fn parse_pr(p: &Value) -> Option<OpenPr> {
63 let title = p.get("title")?.as_str()?.to_string();
64 let (agent, host) = match title_author(&title) {
65 Some((agent, host)) => (agent, Some(host)),
66 None => {
67 let login = p.pointer("/author/login").and_then(Value::as_str).unwrap_or("unknown");
68 (login.to_string(), None)
69 }
70 };
71 let files = p
72 .get("files")
73 .and_then(Value::as_array)
74 .map(|fs| fs.iter().filter_map(|f| f.get("path")?.as_str().map(str::to_string)).collect())
75 .unwrap_or_default();
76 Some(OpenPr {
77 number: p.get("number")?.as_u64()?,
78 branch: p.get("headRefName").and_then(Value::as_str).unwrap_or_default().to_string(),
79 title,
80 files,
81 agent,
82 host,
83 })
84}
85
86pub(super) async fn open_pr(repo: &str, number: u64) -> Result<Option<OpenPr>, String> {
89 let (repo, n) = (repo.to_string(), number.to_string());
90 let text = tokio::task::spawn_blocking(move || {
91 run_gh_agent(&["pr", "view", &n, "--repo", &repo, "--json", &format!("{PR_FIELDS},state")])
92 })
93 .await
94 .map_err(|e| format!("GitHub CLI: {e}"))??;
95 let pr: Value = serde_json::from_str(text.trim()).map_err(|e| format!("the GitHub CLI printed something other than JSON: {e}"))?;
96 Ok(if pr.get("state").and_then(Value::as_str) == Some("OPEN") { parse_pr(&pr) } else { None })
97}
98
99type Cache = HashMap<String, (Instant, Vec<OpenPr>)>;
101
102fn cache() -> std::sync::MutexGuard<'static, Cache> {
103 static CACHE: OnceLock<Mutex<Cache>> = OnceLock::new();
104 CACHE.get_or_init(Default::default).lock().unwrap_or_else(|e| e.into_inner())
105}
106
107pub(super) async fn open_prs(repo: &str) -> Result<Vec<OpenPr>, String> {
109 if let Some((at, prs)) = cache().get(repo) {
110 if at.elapsed() < CACHE_TTL {
111 return Ok(prs.clone());
112 }
113 }
114 let repo_arg = repo.to_string();
115 let text = tokio::task::spawn_blocking(move || {
116 run_gh_agent(&["pr", "list", "--repo", &repo_arg, "--state", "open", "--limit", LIST_LIMIT, "--json", PR_FIELDS])
117 })
118 .await
119 .map_err(|e| format!("GitHub CLI: {e}"))??;
120 let prs = parse_pr_list(&text)?;
121 cache().insert(repo.to_string(), (Instant::now(), prs.clone()));
122 Ok(prs)
123}
124
125fn run_gh_agent(args: &[&str]) -> Result<String, String> {
127 match run_cli(GH_AGENT, "gh-agent", args, &[]) {
128 Err(CliError::NotInstalled) => run_cli(GH, "gh", args, &broker_env(args)).map_err(CliError::into_message),
129 other => other.map_err(CliError::into_message),
130 }
131}
132
133fn broker_env(args: &[&str]) -> Vec<(&'static str, String)> {
137 use std::process::{Command, Stdio};
138 if std::env::var_os("AGENTMUX_GITHUB_BROKER").is_none() {
139 return Vec::new();
140 }
141 let token = Command::new("agentmux-bashwrap")
142 .args(["github-token", "--"])
143 .args(args)
144 .stdin(Stdio::null())
145 .stderr(Stdio::null())
146 .output()
147 .ok()
148 .filter(|o| o.status.success())
149 .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
150 .unwrap_or_default();
151 token_env(&token)
152}
153
154fn token_env(token: &str) -> Vec<(&'static str, String)> {
156 vec![("GH_TOKEN", token.to_string()), ("GITHUB_TOKEN", token.to_string())]
157}
158
159enum CliError {
160 NotInstalled,
161 Failed(String),
162}
163
164impl CliError {
165 fn into_message(self) -> String {
166 match self {
167 CliError::NotInstalled => "neither gh-agent nor gh is installed".to_string(),
168 CliError::Failed(m) => m,
169 }
170 }
171}
172
173fn run_cli(program: &str, name: &str, args: &[&str], envs: &[(&str, String)]) -> Result<String, CliError> {
175 use std::io::Read;
176 use std::process::{Command, Stdio};
177 let failed = |m: String| CliError::Failed(m);
178 let mut cmd = Command::new(program);
179 cmd.args(args)
180 .envs(envs.iter().map(|(k, v)| (*k, v.as_str())))
181 .stdin(Stdio::null())
182 .stdout(Stdio::piped())
183 .stderr(Stdio::piped());
184 #[cfg(windows)]
185 {
186 use agentmux_common::win32::NoWindow;
187 cmd.no_window();
188 }
189 let mut child = cmd.spawn().map_err(|e| {
190 if e.kind() == std::io::ErrorKind::NotFound {
191 CliError::NotInstalled
192 } else {
193 failed(format!("can't run {name}: {e}"))
194 }
195 })?;
196 let mut stdout = child.stdout.take().ok_or_else(|| failed("no stdout".to_string()))?;
197 let mut stderr = child.stderr.take().ok_or_else(|| failed("no stderr".to_string()))?;
198 let out = std::thread::spawn(move || {
199 let mut s = String::new();
200 let _ = stdout.read_to_string(&mut s);
201 s
202 });
203 let err = std::thread::spawn(move || {
204 let mut s = String::new();
205 let _ = stderr.read_to_string(&mut s);
206 s
207 });
208 let deadline = Instant::now() + GH_TIMEOUT;
209 let status = loop {
210 match child.try_wait() {
211 Ok(Some(status)) => break status,
212 Ok(None) if Instant::now() < deadline => std::thread::sleep(Duration::from_millis(50)),
213 Ok(None) => {
214 let _ = child.kill();
215 let _ = child.wait();
216 return Err(failed(format!("{name} took over {} s", GH_TIMEOUT.as_secs())));
217 }
218 Err(e) => return Err(failed(format!("{name}: {e}"))),
219 }
220 };
221 let (out, err) = (out.join().unwrap_or_default(), err.join().unwrap_or_default());
222 if !status.success() {
223 let why = err.lines().filter(|l| !l.starts_with("gh-agent:")).collect::<Vec<_>>().join(" ");
225 return Err(failed(format!("{name} {} failed: {}", args.iter().take(2).copied().collect::<Vec<_>>().join(" "), why.trim())));
226 }
227 Ok(out)
228}
229
230#[derive(Debug, Default)]
232pub(super) struct Asked<'a> {
233 pub path: Option<&'a str>,
235 pub branch: Option<&'a str>,
236 pub query: Option<&'a str>,
237 pub pr: Option<u64>,
238}
239
240#[derive(Debug, Clone, PartialEq, Eq)]
241pub(super) struct PrMatch {
242 pub agent: String,
243 pub host: Option<String>,
244 pub detail: String,
245}
246
247fn under(file: &str, path: &str) -> bool {
248 let path = path.trim_end_matches('/');
249 file == path || file.strip_prefix(path).is_some_and(|rest| rest.starts_with('/'))
250}
251
252fn files_phrase(files: &[&String]) -> String {
253 let named: Vec<&str> = files.iter().take(FILES_NAMED).map(|f| f.as_str()).collect();
254 match files.len().saturating_sub(FILES_NAMED) {
255 0 => named.join(", "),
256 more => format!("{} and {more} more", named.join(", ")),
257 }
258}
259
260pub(super) fn pr_matches(prs: &[OpenPr], asked: &Asked, me_agent: &str, me_host: &str) -> Result<Vec<PrMatch>, String> {
264 let mine = |p: &OpenPr| {
265 p.agent.eq_ignore_ascii_case(me_agent) && p.host.as_deref().is_some_and(|h| h.eq_ignore_ascii_case(me_host))
266 };
267 let asked_files: Option<&[String]> = match asked.pr {
268 Some(n) => Some(
269 &prs.iter()
270 .find(|p| p.number == n)
271 .ok_or_else(|| format!("PR #{n} is not an open PR in this repository"))?
272 .files,
273 ),
274 None => None,
275 };
276 let path = asked.path.filter(|p| !p.is_empty());
277 let words: Vec<String> = asked.query.map(|q| q.split_whitespace().map(str::to_lowercase).collect()).unwrap_or_default();
278 let mut out = Vec::new();
279 for p in prs.iter().filter(|p| !mine(p) && Some(p.number) != asked.pr) {
280 let label = format!("PR #{} ({})", p.number, p.title);
281 let detail = if let Some(files) = asked_files {
282 let shared: Vec<&String> = p.files.iter().filter(|f| files.contains(f)).collect();
283 if shared.is_empty() {
284 continue;
285 }
286 format!("{label} also changes {}", files_phrase(&shared))
287 } else if path.is_none() && asked.branch.is_none() && words.is_empty() {
288 format!("{label} changes {} files", p.files.len())
289 } else {
290 let mut why = Vec::new();
292 if let Some(path) = path {
293 let touched: Vec<&String> = p.files.iter().filter(|f| under(f, path)).collect();
294 if !touched.is_empty() {
295 why.push(format!("changes {}", files_phrase(&touched)));
296 }
297 }
298 if let Some(branch) = asked.branch.filter(|b| p.branch == *b) {
299 why.push(format!("is on branch {branch}"));
300 }
301 let title = p.title.to_lowercase();
302 if !words.is_empty() && words.iter().all(|w| title.contains(w.as_str())) {
303 why.push("matches the query".to_string());
304 }
305 if why.is_empty() {
306 continue;
307 }
308 format!("{label} {}", why.join("; "))
309 };
310 out.push(PrMatch { agent: p.agent.clone(), host: p.host.clone(), detail });
311 }
312 Ok(out)
313}
314
315pub(super) fn merge_into(body: &mut Value, matches: Vec<PrMatch>, me_host: &str, repo: &str) {
319 let Some(agents) = body.get_mut("agents").and_then(Value::as_array_mut) else {
320 return;
321 };
322 for m in matches {
323 let entry = json!({ "kind": "pr", "detail": m.detail, "since_ms": null });
324 let local = m.host.as_deref().is_some_and(|h| h.eq_ignore_ascii_case(me_host));
325 let existing = agents.iter_mut().find(|a| {
326 let name = a.get("agent").and_then(Value::as_str).unwrap_or_default();
327 let host = a.get("host").and_then(Value::as_str);
328 name.eq_ignore_ascii_case(&m.agent)
329 && match (host, m.host.as_deref()) {
330 (Some(h), Some(mh)) => h.eq_ignore_ascii_case(mh),
331 (Some(_), None) => false,
332 (None, _) => local,
333 }
334 });
335 match existing {
336 Some(a) => {
337 if let Some(list) = a.get_mut("matches").and_then(Value::as_array_mut) {
338 list.push(entry);
339 }
340 }
341 None => agents.push(json!({
342 "agent": m.agent,
343 "host": m.host,
344 "channel": "github",
345 "status": "open PR",
346 "goal": null,
347 "repo": repo,
348 "branch": null,
349 "git_checked_ms": null,
350 "matches": [entry],
351 })),
352 }
353 }
354}
355
356pub(super) fn this_host() -> String {
358 sysinfo::System::host_name().unwrap_or_default()
359}
360
361#[cfg(test)]
362mod tests {
363 use super::*;
364
365 fn pr(number: u64, title: &str, branch: &str, files: &[&str]) -> OpenPr {
366 let (agent, host) = title_author(title).map(|(a, h)| (a, Some(h))).unwrap_or(("someone".into(), None));
367 OpenPr { number, title: title.into(), branch: branch.into(), files: files.iter().map(|f| f.to_string()).collect(), agent, host }
368 }
369
370 #[test]
371 fn gh_is_given_the_connections_token_or_none() {
372 assert_eq!(token_env("t0k"), vec![("GH_TOKEN", "t0k".to_string()), ("GITHUB_TOKEN", "t0k".to_string())]);
373 assert!(token_env("").iter().all(|(_, v)| v.is_empty()));
375 }
376
377 #[test]
378 fn the_title_prefix_names_the_agent() {
379 assert_eq!(title_author("AgentY@narko: fix(x): y"), Some(("AgentY".into(), "narko".into())));
380 assert_eq!(title_author("Manoz@Area54: chore: z"), Some(("Manoz".into(), "Area54".into())));
381 assert_eq!(title_author("chore(deps): bump serde"), None);
382 assert_eq!(title_author("Bump a@b from 1 to 2"), None);
383 assert_eq!(title_author("a b@c: x"), None);
384 }
385
386 #[test]
387 fn reads_gh_output_crediting_a_pr_without_the_prefix_to_its_author() {
388 let text = r#"[
389 {"number": 12, "title": "Agent4@narko: feat: x", "headRefName": "agent4/x", "author": {"login": "app/muxagent"},
390 "files": [{"path": "crates/a.rs", "additions": 1, "deletions": 0}]},
391 {"number": 13, "title": "Bump serde from 1.0 to 1.1", "headRefName": "dependabot/x",
392 "author": {"login": "app/dependabot"}, "files": [{"path": "Cargo.lock"}]}
393 ]"#;
394 let prs = parse_pr_list(text).unwrap();
395 assert_eq!(prs[0], pr(12, "Agent4@narko: feat: x", "agent4/x", &["crates/a.rs"]));
396 assert_eq!((prs[1].agent.as_str(), prs[1].host.as_deref()), ("app/dependabot", None));
397 assert_eq!(prs[1].files, vec!["Cargo.lock".to_string()]);
398 assert!(parse_pr_list("not json").is_err());
399 }
400
401 fn sample() -> Vec<OpenPr> {
402 vec![
403 pr(10, "AgentY@narko: mine", "agenty/x", &["crates/srv/a.rs"]),
404 pr(11, "Agent4@narko: presence", "agent4/p", &["crates/srv/a.rs", "crates/srv/b.rs"]),
405 pr(12, "Lark@area54: widgets catalog", "lark/w", &["frontend/w.ts"]),
406 pr(13, "AgentY@area54: same name, other computer", "agenty/y", &["crates/srv/a.rs"]),
407 ]
408 }
409
410 #[test]
411 fn a_path_matches_prs_changing_it_or_anything_under_it() {
412 let asked = Asked { path: Some("crates/srv"), ..Default::default() };
413 let got = pr_matches(&sample(), &asked, "AgentY", "narko").unwrap();
414 let names: Vec<_> = got.iter().map(|m| (m.agent.as_str(), m.host.as_deref())).collect();
415 assert_eq!(names, vec![("Agent4", Some("narko")), ("AgentY", Some("area54"))], "my own PR is left out, my namesake isn't");
416 assert_eq!(got[0].detail, "PR #11 (Agent4@narko: presence) changes crates/srv/a.rs, crates/srv/b.rs");
417 let file = Asked { path: Some("crates/srv/b.rs"), ..Default::default() };
418 assert_eq!(pr_matches(&sample(), &file, "AgentY", "narko").unwrap().len(), 1);
419 let not_a_prefix = Asked { path: Some("crates/sr"), ..Default::default() };
420 assert!(pr_matches(&sample(), ¬_a_prefix, "AgentY", "narko").unwrap().is_empty());
421 }
422
423 #[test]
424 fn a_pr_number_finds_other_prs_changing_the_same_files() {
425 let asked = Asked { pr: Some(10), ..Default::default() };
426 let got = pr_matches(&sample(), &asked, "Someone", "else").unwrap();
427 assert_eq!(got.iter().map(|m| m.detail.as_str()).collect::<Vec<_>>(), vec![
428 "PR #11 (Agent4@narko: presence) also changes crates/srv/a.rs",
429 "PR #13 (AgentY@area54: same name, other computer) also changes crates/srv/a.rs",
430 ]);
431 assert!(pr_matches(&sample(), &Asked { pr: Some(99), ..Default::default() }, "x", "y").is_err());
432 }
433
434 #[test]
437 fn a_pr_without_the_prefix_can_be_asked_about_and_is_listed() {
438 let mut prs = sample();
439 prs.push(pr(30, "Bump serde", "dependabot/serde", &["crates/srv/a.rs"]));
440 let asked = Asked { pr: Some(30), ..Default::default() };
441 let got = pr_matches(&prs, &asked, "AgentY", "narko").unwrap();
442 assert_eq!(got.len(), 2, "#11 and #13 share its file; my own #10 is left out");
443 let by_path = pr_matches(&prs, &Asked { path: Some("crates/srv/a.rs"), ..Default::default() }, "AgentY", "narko").unwrap();
444 assert!(by_path.iter().any(|m| m.agent == "someone" && m.host.is_none()));
445 }
446
447 #[test]
448 fn a_branch_a_query_or_the_whole_repository() {
449 let branch = Asked { branch: Some("lark/w"), ..Default::default() };
450 assert_eq!(pr_matches(&sample(), &branch, "AgentY", "narko").unwrap()[0].agent, "Lark");
451 let query = Asked { query: Some("Widgets CATALOG"), ..Default::default() };
452 assert_eq!(pr_matches(&sample(), &query, "AgentY", "narko").unwrap().len(), 1);
453 let all = pr_matches(&sample(), &Asked { path: Some(""), ..Default::default() }, "AgentY", "narko").unwrap();
454 assert_eq!(all.len(), 3);
455 assert_eq!(all[1].detail, "PR #12 (Lark@area54: widgets catalog) changes 1 files");
456 }
457
458 #[test]
460 fn every_selector_given_counts() {
461 let asked = Asked { path: Some("crates/srv/b.rs"), branch: Some("lark/w"), query: Some("presence"), ..Default::default() };
462 let got = pr_matches(&sample(), &asked, "AgentY", "narko").unwrap();
463 let details: Vec<_> = got.iter().map(|m| m.detail.as_str()).collect();
464 assert_eq!(details, vec![
465 "PR #11 (Agent4@narko: presence) changes crates/srv/b.rs; matches the query",
466 "PR #12 (Lark@area54: widgets catalog) is on branch lark/w",
467 ]);
468 }
469
470 #[test]
471 fn many_files_are_counted() {
472 let p = pr(20, "A@h: big", "a/b", &["d/1", "d/2", "d/3", "d/4", "d/5"]);
473 let got = pr_matches(&[p], &Asked { path: Some("d"), ..Default::default() }, "x", "y").unwrap();
474 assert_eq!(got[0].detail, "PR #20 (A@h: big) changes d/1, d/2, d/3 and 2 more");
475 }
476
477 #[test]
478 fn matches_join_a_local_agent_or_stand_alone() {
479 let mut body = json!({ "agents": [
480 { "agent": "Agent4", "channel": "local-main", "matches": [{ "kind": "dirty", "detail": "x" }] }
481 ]});
482 let matches = vec![
483 PrMatch { agent: "agent4".into(), host: Some("narko".into()), detail: "PR #11".into() },
484 PrMatch { agent: "Agent4".into(), host: Some("area54".into()), detail: "PR #14".into() },
485 PrMatch { agent: "app/dependabot".into(), host: None, detail: "PR #15".into() },
486 ];
487 merge_into(&mut body, matches, "narko", "o/r");
488 let agents = body["agents"].as_array().unwrap();
489 assert_eq!(agents.len(), 3);
490 assert_eq!(agents[2]["host"], Value::Null);
491 assert_eq!(agents[0]["matches"][1], json!({ "kind": "pr", "detail": "PR #11", "since_ms": null }));
492 assert_eq!(agents[1]["host"], "area54");
493 assert_eq!(agents[1]["channel"], "github");
494 }
495}