Skip to main content

agentmux_srv_core/backend/work_facts/
matching.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `WhoIsWorkingOn`: which other agents' work facts touch a path,
5//! repository, branch or topic
6//! (docs/specs/SPEC_AGENT_OVERLAP_AWARENESS_2026_10_10.md ยง3.2). Pure, so
7//! every rule is tested without a running srv.
8
9use std::collections::HashSet;
10
11use serde::{Deserialize, Serialize};
12
13use super::paths::{clean_relative, is_absolute, normalize_path, normalize_repo, path_matches, relative_to};
14use super::{BuildSlotHold, WorkFacts};
15
16/// What the caller asked about. Every field is optional; with none, the
17/// caller's own repository is the question.
18#[derive(Debug, Clone, Default, Deserialize)]
19pub struct WhoQuery {
20    pub path: Option<String>,
21    pub repo: Option<String>,
22    pub branch: Option<String>,
23    pub query: Option<String>,
24}
25
26/// The question after resolving it against the caller's own facts.
27#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
28pub struct Target {
29    /// Repository key (`owner/repo`, or `local:<folder>` without a remote).
30    pub repo: Option<String>,
31    /// Repository-relative path or folder; `""` is the whole repository.
32    pub path: Option<String>,
33    /// An absolute path that is in no known clone: compared as written.
34    #[serde(skip_serializing_if = "Option::is_none")]
35    pub absolute_path: Option<String>,
36    pub branch: Option<String>,
37    pub query: Option<String>,
38}
39
40/// How one agent's work touches the question. Ordered by strength.
41#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize)]
42#[serde(rename_all = "lowercase")]
43pub enum MatchKind {
44    /// That agent claimed it (`ClaimWork`, [`super::claims`]): its own word
45    /// that it is working on this, so it comes first.
46    Claim,
47    /// The file has uncommitted changes in that agent's clone.
48    Dirty,
49    /// That agent's edit tools changed the file recently.
50    Edited,
51    /// Same repository and branch.
52    Branch,
53    /// Same repository (asked about the repository as a whole).
54    Repo,
55    Goal,
56    Todo,
57}
58
59#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
60pub struct WhoMatch {
61    pub kind: MatchKind,
62    pub detail: String,
63    /// When the matched activity happened (Unix ms), where known.
64    pub since_ms: Option<u64>,
65}
66
67#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
68pub struct WhoResult {
69    pub agent: String,
70    pub channel: String,
71    pub status: String,
72    pub goal: Option<String>,
73    pub repo: Option<String>,
74    pub branch: Option<String>,
75    /// When this agent's git facts were taken (Unix ms), so a reader can
76    /// tell how fresh `dirty` and `branch` matches are.
77    pub git_checked_ms: Option<u64>,
78    /// Set while this agent holds the host's build slot, so a reader knows why its builds and
79    /// tests are slow to start for everyone else.
80    #[serde(skip_serializing_if = "Option::is_none")]
81    pub build_slot: Option<BuildSlotHold>,
82    pub matches: Vec<WhoMatch>,
83}
84
85/// How many file names one match's detail lists before "+N more".
86const DETAIL_FILES: usize = 5;
87
88/// Resolve `q` against the caller's facts (`caller`) and every known clone
89/// (`all`): a path absolute in some clone becomes (repository, relative
90/// path), and the caller's repository is assumed when none is named.
91pub fn resolve(q: &WhoQuery, caller: Option<&WorkFacts>, all: &[WorkFacts]) -> Result<Target, String> {
92    let nonempty = |s: &Option<String>| s.as_deref().map(str::trim).filter(|s| !s.is_empty()).map(str::to_string);
93    let mut t = Target { branch: nonempty(&q.branch), query: nonempty(&q.query), ..Default::default() };
94    let named_repo = match nonempty(&q.repo) {
95        Some(r) => Some(normalize_repo(&r).ok_or_else(|| format!("repo {r:?} is not owner/repo or a remote URL"))?),
96        None => None,
97    };
98    let caller_repo = caller.and_then(WorkFacts::repo_key);
99
100    if let Some(raw) = nonempty(&q.path) {
101        if is_absolute(&raw) {
102            let abs = normalize_path(&raw);
103            // The caller's own clone first, then any other agent's.
104            let owner = caller.into_iter().chain(all.iter()).find_map(|f| {
105                let rel = relative_to(&abs, f.repo_root.as_deref()?)?;
106                Some((f.repo_key()?, rel))
107            });
108            match owner {
109                Some((repo, rel)) => {
110                    t.repo = named_repo.clone().or(Some(repo));
111                    t.path = Some(rel);
112                }
113                None => t.absolute_path = Some(abs),
114            }
115        } else {
116            t.path = Some(clean_relative(&raw));
117        }
118    }
119    if t.repo.is_none() {
120        t.repo = named_repo.or(caller_repo);
121    }
122    if t.path.is_some() && t.repo.is_none() {
123        return Err("path is relative to a repository, but no repository is known: pass `repo`, \
124                    an absolute path, or call this from inside a repository"
125            .to_string());
126    }
127    if t.path.is_none() && t.absolute_path.is_none() && t.branch.is_none() && t.query.is_none() && t.repo.is_none() {
128        return Err("nothing to look for: pass path, repo, branch or query (or call this from inside a \
129                    repository to ask about it)"
130            .to_string());
131    }
132    Ok(t)
133}
134
135/// Lowercase alphanumeric words.
136pub(super) fn words(s: &str) -> HashSet<String> {
137    s.split(|c: char| !c.is_alphanumeric()).filter(|w| !w.is_empty()).map(str::to_lowercase).collect()
138}
139
140/// Every word of the query appears in `text`, case-insensitively.
141pub(super) fn mentions(query_words: &HashSet<String>, text: &str) -> bool {
142    !query_words.is_empty() && query_words.is_subset(&words(text))
143}
144
145/// The first few of `files`, then "(+N more)" up to `total`.
146fn list_files(files: &[String], total: usize) -> String {
147    let mut s = files.iter().take(DETAIL_FILES).cloned().collect::<Vec<_>>().join(", ");
148    let shown = files.len().min(DETAIL_FILES);
149    if total > shown {
150        s.push_str(&format!(" (+{} more)", total - shown));
151    }
152    s
153}
154
155/// What `other`'s facts say about `t`, strongest first.
156fn matches_for(t: &Target, other: &WorkFacts) -> Vec<WhoMatch> {
157    let mut out = Vec::new();
158    let same_repo = t.repo.is_some() && other.repo_key() == t.repo;
159    let repo_name = other.repo.clone().or_else(|| other.repo_root.clone()).unwrap_or_default();
160
161    // Files: repository-relative within the same repository, else (a path in
162    // no known clone) the absolute path as written.
163    let file_target: Option<(&str, bool)> = match (&t.path, &t.absolute_path) {
164        (Some(rel), _) if same_repo => Some((rel.as_str(), false)),
165        (None, Some(abs)) => Some((abs.as_str(), true)),
166        _ => None,
167    };
168    let repo_only = t.path.is_none() && t.absolute_path.is_none() && t.branch.is_none() && t.query.is_none();
169    if let Some((target, absolute)) = file_target.or(if repo_only && same_repo { Some(("", false)) } else { None }) {
170        let dirty: Vec<String> = other
171            .dirty_files
172            .iter()
173            .filter(|f| {
174                if absolute {
175                    let abs = format!("{}/{}", other.repo_root.as_deref().unwrap_or(""), f);
176                    path_matches(&normalize_path(&abs), target)
177                } else {
178                    path_matches(f, target)
179                }
180            })
181            .cloned()
182            .collect();
183        let edited: Vec<&super::FactFile> = other
184            .recent_files
185            .iter()
186            .filter(|r| {
187                if absolute {
188                    path_matches(&r.path, target)
189                } else {
190                    same_repo && r.rel.as_deref().is_some_and(|rel| path_matches(rel, target))
191                }
192            })
193            .collect();
194        let last_edit = |file: &str| {
195            edited.iter().filter(|r| r.rel.as_deref() == Some(file) || r.path == file).map(|r| r.ts_ms).max()
196        };
197        if !dirty.is_empty() {
198            // The whole repository has `dirty_count` files even past the
199            // stored list; a narrower target counts what matched.
200            let total = if target.is_empty() && !absolute { other.dirty_count.max(dirty.len()) } else { dirty.len() };
201            out.push(WhoMatch {
202                kind: MatchKind::Dirty,
203                detail: format!("uncommitted in {repo_name}: {}", list_files(&dirty, total)),
204                since_ms: dirty.iter().filter_map(|f| last_edit(f)).max(),
205            });
206        }
207        if !edited.is_empty() {
208            let names: Vec<String> =
209                edited.iter().map(|r| format!("{} ({})", r.rel.as_deref().unwrap_or(&r.path), r.tool)).collect();
210            out.push(WhoMatch {
211                kind: MatchKind::Edited,
212                detail: format!("recently edited: {}", list_files(&names, names.len())),
213                since_ms: edited.iter().map(|r| r.ts_ms).max(),
214            });
215        }
216        if repo_only && out.is_empty() {
217            out.push(WhoMatch {
218                kind: MatchKind::Repo,
219                detail: match &other.branch {
220                    Some(b) => format!("working in {repo_name} on branch {b}"),
221                    None => format!("working in {repo_name}"),
222                },
223                since_ms: None,
224            });
225        }
226    }
227
228    if let Some(branch) = &t.branch {
229        let repo_ok = t.repo.is_none() || same_repo;
230        if repo_ok && other.branch.as_deref() == Some(branch.as_str()) {
231            out.push(WhoMatch {
232                kind: MatchKind::Branch,
233                detail: format!("on branch {branch} in {repo_name}"),
234                since_ms: None,
235            });
236        }
237    }
238
239    if let Some(q) = &t.query {
240        let qw = words(q);
241        if let Some(goal) = other.goal.as_deref().filter(|g| mentions(&qw, g)) {
242            out.push(WhoMatch { kind: MatchKind::Goal, detail: goal.to_string(), since_ms: None });
243        }
244        for todo in other.todos.iter().filter(|td| mentions(&qw, &td.text)).take(3) {
245            out.push(WhoMatch {
246                kind: MatchKind::Todo,
247                detail: format!("[{}] {}", todo.status, todo.text),
248                since_ms: None,
249            });
250        }
251    }
252
253    out.sort_by_key(|m| m.kind);
254    out
255}
256
257/// Every agent in `others` (the caller already left out) whose work touches
258/// `t`, strongest match first, then most recent.
259pub fn who_is_working_on(t: &Target, others: &[WorkFacts]) -> Vec<WhoResult> {
260    let mut results: Vec<WhoResult> = others
261        .iter()
262        .filter_map(|f| {
263            let matches = matches_for(t, f);
264            (!matches.is_empty()).then(|| WhoResult {
265                agent: f.agent.clone(),
266                channel: f.channel.clone(),
267                status: f.status.clone(),
268                goal: f.goal.clone(),
269                repo: f.repo.clone(),
270                branch: f.branch.clone(),
271                git_checked_ms: f.git_checked_ms,
272                build_slot: f.build_slot.clone(),
273                matches,
274            })
275        })
276        .collect();
277    sort_results(&mut results);
278    results
279}
280
281/// Strongest match first, then most recent, then by name.
282pub(super) fn sort_results(results: &mut [WhoResult]) {
283    results.sort_by(|a, b| {
284        let strongest = |r: &WhoResult| r.matches.first().map(|m| m.kind);
285        let newest = |r: &WhoResult| r.matches.iter().filter_map(|m| m.since_ms).max();
286        strongest(a)
287            .cmp(&strongest(b))
288            .then_with(|| newest(b).cmp(&newest(a)))
289            .then_with(|| a.agent.cmp(&b.agent))
290    });
291}
292
293#[cfg(test)]
294mod tests {
295    use super::*;
296    use crate::backend::reactive::progress_watcher::TodoItem;
297    use crate::backend::work_facts::FactFile;
298
299    /// An agent with its own clone of `repo` at `root`.
300    fn agent(name: &str, repo: &str, root: &str, branch: &str) -> WorkFacts {
301        WorkFacts {
302            agent: name.into(),
303            block_id: format!("block-{name}"),
304            channel: "stable".into(),
305            status: "busy".into(),
306            repo: Some(repo.into()),
307            repo_root: Some(root.into()),
308            branch: Some(branch.into()),
309            ..Default::default()
310        }
311    }
312
313    fn edited(root: &str, rel: &str, ts: u64) -> FactFile {
314        FactFile { path: format!("{root}/{rel}"), rel: Some(rel.into()), tool: "Edit".into(), ts_ms: ts }
315    }
316
317    fn q(path: Option<&str>, repo: Option<&str>, branch: Option<&str>, query: Option<&str>) -> WhoQuery {
318        WhoQuery {
319            path: path.map(Into::into),
320            repo: repo.map(Into::into),
321            branch: branch.map(Into::into),
322            query: query.map(Into::into),
323        }
324    }
325
326    fn ask(query: WhoQuery, caller: &WorkFacts, others: &[WorkFacts]) -> Vec<WhoResult> {
327        let mut all = vec![caller.clone()];
328        all.extend_from_slice(others);
329        let t = resolve(&query, Some(caller), &all).unwrap();
330        who_is_working_on(&t, others)
331    }
332
333    /// Two clones of the same remote in different folders match on the
334    /// repository-relative path, whichever spelling the caller used.
335    #[test]
336    fn clones_in_different_folders_match_on_repository_relative_paths() {
337        let me = agent("Me", "o/r", "C:/a/me/r", "main");
338        let mut other = agent("Other", "o/r", "C:/a/other/clone", "feat");
339        other.dirty_files = vec!["crates/srv/lib.rs".into()];
340        other.dirty_count = 1;
341        other.recent_files = vec![edited("C:/a/other/clone", "crates/srv/lib.rs", 50)];
342
343        for path in ["C:/a/me/r/crates/srv/lib.rs", r"C:\a\me\r\crates\srv\lib.rs", "crates/srv/lib.rs"] {
344            let r = ask(q(Some(path), None, None, None), &me, std::slice::from_ref(&other));
345            assert_eq!(r.len(), 1, "{path}");
346            assert_eq!(r[0].agent, "Other");
347            let kinds: Vec<MatchKind> = r[0].matches.iter().map(|m| m.kind).collect();
348            assert_eq!(kinds, vec![MatchKind::Dirty, MatchKind::Edited]);
349            assert_eq!(r[0].matches[0].since_ms, Some(50));
350            assert!(r[0].matches[0].detail.contains("crates/srv/lib.rs"));
351        }
352
353        // A different repository with the same relative path is not a match.
354        let stranger = WorkFacts { dirty_files: vec!["crates/srv/lib.rs".into()], ..agent("S", "o/other", "C:/s", "main") };
355        assert!(ask(q(Some("crates/srv/lib.rs"), None, None, None), &me, &[stranger]).is_empty());
356    }
357
358    /// The holder of the build slot says so in the answer, and nobody else carries the field.
359    #[test]
360    fn the_build_slot_holder_is_marked_in_the_answer() {
361        let me = agent("Me", "o/r", "/me", "main");
362        let mut holder = agent("Holder", "o/r", "/holder", "feat");
363        holder.dirty_files = vec!["a.rs".into()];
364        holder.build_slot = Some(BuildSlotHold { since_ms: 7, reason: "cargo test".into(), command: "cargo test -p x".into() });
365        let mut other = agent("Other", "o/r", "/other", "feat");
366        other.dirty_files = vec!["a.rs".into()];
367
368        let r = ask(q(Some("a.rs"), None, None, None), &me, &[holder, other]);
369        let json: Vec<serde_json::Value> = r.iter().map(|x| serde_json::to_value(x).unwrap()).collect();
370        let by = |name: &str| json.iter().find(|j| j["agent"] == name).unwrap();
371        assert_eq!(by("Holder")["build_slot"]["reason"], "cargo test");
372        assert_eq!(by("Holder")["build_slot"]["command"], "cargo test -p x");
373        assert!(by("Other").get("build_slot").is_none(), "only the holder carries it");
374    }
375
376    #[test]
377    fn a_folder_matches_files_inside_it_by_prefix() {
378        let me = agent("Me", "o/r", "/me", "main");
379        let mut other = agent("Other", "o/r", "/other", "feat");
380        other.dirty_files = vec!["crates/srv/src/a.rs".into(), "docs/x.md".into()];
381        other.recent_files = vec![edited("/other", "crates/srv/src/b.rs", 9)];
382
383        let r = ask(q(Some("crates/srv"), None, None, None), &me, std::slice::from_ref(&other));
384        assert_eq!(r.len(), 1);
385        assert!(r[0].matches[0].detail.contains("crates/srv/src/a.rs"));
386        assert!(!r[0].matches[0].detail.contains("docs/x.md"));
387        assert!(r[0].matches[1].detail.contains("crates/srv/src/b.rs"));
388
389        assert!(ask(q(Some("crates/sr"), None, None, None), &me, &[other]).is_empty(), "a name prefix isn't a folder");
390    }
391
392    #[test]
393    fn query_matches_words_in_goals_and_todos_case_insensitively() {
394        let me = agent("Me", "o/r", "/me", "main");
395        let mut a = agent("A", "o/x", "/a", "main");
396        a.goal = Some("Add the MuxBus allowlist for presence".into());
397        let mut b = agent("B", "o/y", "/b", "main");
398        b.todos = vec![TodoItem { text: "Wire the muxbus Allowlist check".into(), status: "in_progress".into() }];
399        let mut c = agent("C", "o/z", "/c", "main");
400        c.goal = Some("Allowlists everywhere".into());
401
402        let r = ask(q(None, None, None, Some("muxbus ALLOWLIST")), &me, &[a, b, c]);
403        let got: Vec<(&str, MatchKind)> = r.iter().map(|r| (r.agent.as_str(), r.matches[0].kind)).collect();
404        assert_eq!(got, vec![("A", MatchKind::Goal), ("B", MatchKind::Todo)], "whole words, any order, any case");
405        assert_eq!(r[1].matches[0].detail, "[in_progress] Wire the muxbus Allowlist check");
406    }
407
408    #[test]
409    fn branch_matches_within_the_repository() {
410        let me = agent("Me", "o/r", "/me", "main");
411        let a = agent("A", "o/r", "/a", "agenty/x");
412        let b = agent("B", "o/other", "/b", "agenty/x");
413        let r = ask(q(None, None, Some("agenty/x"), None), &me, &[a, b]);
414        assert_eq!(r.len(), 1);
415        assert_eq!(r[0].agent, "A");
416        assert_eq!(r[0].matches[0].kind, MatchKind::Branch);
417    }
418
419    #[test]
420    fn with_nothing_named_the_callers_repository_is_the_question() {
421        let me = agent("Me", "o/r", "/me", "main");
422        let mut a = agent("A", "o/r", "/a", "feat");
423        a.dirty_files = vec!["x.rs".into()];
424        a.dirty_count = 12;
425        let b = agent("B", "o/r", "/b", "fix");
426        let c = agent("C", "o/else", "/c", "main");
427        let r = ask(WhoQuery::default(), &me, &[b, a, c]);
428        let got: Vec<(&str, MatchKind)> = r.iter().map(|r| (r.agent.as_str(), r.matches[0].kind)).collect();
429        assert_eq!(got, vec![("A", MatchKind::Dirty), ("B", MatchKind::Repo)], "ordered by strength");
430        assert!(r[0].matches[0].detail.contains("x.rs (+11 more)"), "{}", r[0].matches[0].detail);
431        assert_eq!(r[1].matches[0].detail, "working in o/r on branch fix");
432    }
433
434    #[test]
435    fn an_explicit_repo_wins_and_bad_input_is_explained() {
436        let me = agent("Me", "o/r", "/me", "main");
437        let mut a = agent("A", "agentmuxai/agentmux", "/a", "feat");
438        a.dirty_files = vec!["src/x.rs".into()];
439        let r = ask(q(Some("src/x.rs"), Some("https://github.com/AgentMuxAI/agentmux.git"), None, None), &me, &[a]);
440        assert_eq!(r.len(), 1);
441
442        assert!(resolve(&q(Some("a.rs"), None, None, None), None, &[]).is_err(), "relative path, no repository");
443        assert!(resolve(&WhoQuery::default(), None, &[]).is_err(), "nothing asked");
444        assert!(resolve(&q(None, Some("not a repo"), None, None), None, &[]).is_err());
445    }
446
447    #[test]
448    fn an_absolute_path_in_another_agents_clone_resolves_through_it() {
449        let me = WorkFacts { agent: "Me".into(), ..Default::default() };
450        let mut a = agent("A", "o/r", "/a/clone", "feat");
451        a.dirty_files = vec!["lib.rs".into()];
452        let b = WorkFacts { dirty_files: vec!["lib.rs".into()], ..agent("B", "o/r", "/b/clone", "main") };
453        let r = ask(q(Some("/a/clone/lib.rs"), None, None, None), &me, &[a, b]);
454        let names: Vec<&str> = r.iter().map(|r| r.agent.as_str()).collect();
455        assert_eq!(names, vec!["A", "B"], "both clones of o/r have lib.rs uncommitted");
456    }
457
458    #[test]
459    fn a_path_in_no_known_clone_is_compared_as_written() {
460        let me = WorkFacts { agent: "Me".into(), ..Default::default() };
461        let other = WorkFacts {
462            agent: "O".into(),
463            recent_files: vec![FactFile { path: "/tmp/notes/a.md".into(), rel: None, tool: "Write".into(), ts_ms: 3 }],
464            ..Default::default()
465        };
466        let r = ask(q(Some("/tmp/notes"), None, None, None), &me, &[other]);
467        assert_eq!(r.len(), 1);
468        assert_eq!(r[0].matches[0].kind, MatchKind::Edited);
469    }
470
471    #[test]
472    fn results_order_by_strength_then_recency() {
473        let me = agent("Me", "o/r", "/me", "main");
474        let mut old = agent("Old", "o/r", "/old", "x");
475        old.recent_files = vec![edited("/old", "a.rs", 10)];
476        let mut new = agent("New", "o/r", "/new", "y");
477        new.recent_files = vec![edited("/new", "a.rs", 20)];
478        let mut dirty = agent("Dirty", "o/r", "/d", "z");
479        dirty.dirty_files = vec!["a.rs".into()];
480        let r = ask(q(Some("a.rs"), None, None, None), &me, &[old, new, dirty]);
481        let names: Vec<&str> = r.iter().map(|r| r.agent.as_str()).collect();
482        assert_eq!(names, vec!["Dirty", "New", "Old"]);
483    }
484}