Skip to main content

agentmux_mcp/tools/
overlap.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Who else is working on the same thing
5//! (docs/specs/SPEC_AGENT_OVERLAP_AWARENESS_2026_10_10.md §3.2), and saying
6//! what you are working on (`ClaimWork`, `ReleaseWork`, §3.4).
7
8use super::*;
9
10/// The query srv's `/api/v1/work-facts/who` takes for these arguments, plus
11/// who is asking (srv prefers the request's agent token to both).
12fn who_query(arguments: &Value, agent: &str, block_id: &str) -> Vec<(&'static str, String)> {
13    let mut q: Vec<(&'static str, String)> = Vec::new();
14    for key in ["path", "repo", "branch", "query"] {
15        if let Some(v) = arguments.get(key).and_then(|v| v.as_str()).map(str::trim).filter(|v| !v.is_empty()) {
16            q.push((key, v.to_string()));
17        }
18    }
19    if !agent.trim().is_empty() {
20        q.push(("agent", agent.trim().to_string()));
21    }
22    if !block_id.trim().is_empty() {
23        q.push(("block", block_id.trim().to_string()));
24    }
25    q
26}
27
28pub(super) async fn call(name: &str, arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
29    match name {
30        "WhoIsWorkingOn" => run_who_is_working_on(arguments, cx).await,
31        "ClaimWork" | "ReleaseWork" => run_claim_work(name, arguments, cx).await,
32        "SetStatus" => run_set_status(arguments, cx).await,
33        "QuotaMode" => run_quota_mode(arguments, cx).await,
34        "PostBulletin" | "ReadBulletin" => run_post_bulletin(name, arguments, cx).await,
35        "PostToChannel" | "ReadChannel" => run_post_to_channel(name, arguments, cx).await,
36        _ => Err(not_in_family()),
37    }
38}
39
40async fn run_who_is_working_on(arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
41    let ToolCtx { local_url, auth_key, block_id, client, .. } = *cx;
42    if local_url.is_empty() || auth_key.is_empty() {
43        anyhow::bail!(
44            "AGENTMUX_LOCAL_URL and AGENTMUX_AUTH_KEY must be set. \
45             Is this agent pane opened via AgentMux?"
46        );
47    }
48    let agent = std::env::var("AGENTMUX_AGENT_ID").unwrap_or_default();
49    let (pr_repo, pr) = match arguments.get("pr").filter(|v| !v.is_null()) {
50        Some(v) => {
51            let (repo, n) = pr_ref(v)
52                .ok_or_else(|| anyhow::anyhow!("pr must be a PR number (12, \"#12\") or its GitHub URL"))?;
53            (repo, Some(n))
54        }
55        None => (None, None),
56    };
57    let mut query = who_query(arguments, &agent, block_id);
58    // srv's recent_posts then holds the PR's own posts.
59    if let Some(n) = pr {
60        query.push(("pr", n.to_string()));
61    }
62    // A PR's URL names its repository: ask about that one.
63    if let Some(url_repo) = pr_repo {
64        match arg(arguments, "repo") {
65            Some(r) if normalize_repo(r) != normalize_repo(&url_repo) => {
66                anyhow::bail!("pr is a PR of {url_repo}, but repo is {r}: pass one or the other");
67            }
68            Some(_) => {}
69            None => query.push(("repo", url_repo)),
70        }
71    }
72    let url = format!("{}/api/v1/work-facts/who", local_url.trim_end_matches('/'));
73    let mut body = srv_get_json(client, &url, auth_key, &query, "Presence who").await?;
74    add_open_prs(&mut body, arguments, pr, &agent, |path| {
75        // Only the file, its repository and who is asking: srv
76        // matches each criterion on its own, so a branch or query
77        // here would list agents that touch none of the PR's files.
78        let mut q = query.clone();
79        q.retain(|(k, _)| matches!(*k, "repo" | "agent" | "block"));
80        // Not `pr`: these ask about one of its files, whose posts are merged in.
81        q.push(("path", path));
82        let url = url.clone();
83        async move { srv_get_json(client, &url, auth_key, &q, "Presence who").await.ok() }
84    })
85    .await;
86    Ok(serde_json::to_string_pretty(&body).unwrap_or_else(|_| body.to_string()))
87}
88
89async fn run_claim_work(name: &str, arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
90    let ToolCtx { local_url, auth_key, block_id, client, .. } = *cx;
91    if local_url.is_empty() || auth_key.is_empty() {
92        anyhow::bail!(
93            "AGENTMUX_LOCAL_URL and AGENTMUX_AUTH_KEY must be set. \
94             Is this agent pane opened via AgentMux?"
95        );
96    }
97    let agent = std::env::var("AGENTMUX_AGENT_ID").unwrap_or_default();
98    let base = local_url.trim_end_matches('/');
99    let (url, body) = if name == "ClaimWork" {
100        (format!("{base}/api/v1/work-claims"), claim_body(arguments, &agent, block_id))
101    } else {
102        (format!("{base}/api/v1/work-claims/release"), release_body(arguments, &agent, block_id))
103    };
104    let answer = srv_post_json(client, &url, auth_key, &body, name).await?;
105    Ok(serde_json::to_string_pretty(&answer).unwrap_or_else(|_| answer.to_string()))
106}
107
108/// `Presence status`: the agent says what it is doing now. srv keeps the line (cleaned, with the
109/// time) in the agent's pane meta, where the Swarm row and `work.goal` read it.
110async fn run_set_status(arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
111    let ToolCtx { local_url, auth_key, block_id, client, .. } = *cx;
112    if local_url.is_empty() || auth_key.is_empty() {
113        anyhow::bail!(
114            "AGENTMUX_LOCAL_URL and AGENTMUX_AUTH_KEY must be set. \
115             Is this agent pane opened via AgentMux?"
116        );
117    }
118    let line = arguments.get("line").and_then(|v| v.as_str()).unwrap_or("");
119    if line.trim().is_empty() {
120        anyhow::bail!("SetStatus: line is required: say what you are doing in 5 to 10 words, verb first");
121    }
122    let mut body = serde_json::Map::new();
123    body.insert("line".into(), json!(line));
124    if let Some(state) = arguments.get("state").filter(|v| !v.is_null()) {
125        body.insert("state".into(), state.clone());
126    }
127    if let Some(minutes) = arguments.get("until_minutes").filter(|v| !v.is_null()) {
128        body.insert("until_minutes".into(), minutes.clone());
129    }
130    body.insert("agent".into(), json!(std::env::var("AGENTMUX_AGENT_ID").unwrap_or_default().trim()));
131    body.insert("block".into(), json!(block_id.trim()));
132    let url = format!("{}/api/v1/agent/status", local_url.trim_end_matches('/'));
133    let answer = srv_post_json(client, &url, auth_key, &Value::Object(body), "SetStatus").await?;
134    Ok(serde_json::to_string_pretty(&answer).unwrap_or_else(|_| answer.to_string()))
135}
136
137async fn run_quota_mode(arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
138    let ToolCtx { local_url, auth_key, block_id, client, .. } = *cx;
139    if local_url.is_empty() || auth_key.is_empty() {
140        anyhow::bail!(
141            "AGENTMUX_LOCAL_URL and AGENTMUX_AUTH_KEY must be set. \
142             Is this agent pane opened via AgentMux?"
143        );
144    }
145    let url = format!("{}/api/v1/quota-mode", local_url.trim_end_matches('/'));
146    let given = |k: &str| arguments.get(k).is_some_and(|v| !v.is_null());
147    if given("min_priority") && !given("mode") {
148        anyhow::bail!("quota_mode: min_priority only applies together with mode (off or tight)");
149    }
150    let answer = if given("mode") {
151        let mut body = serde_json::Map::new();
152        for key in ["mode", "min_priority"] {
153            if let Some(v) = arguments.get(key).filter(|v| !v.is_null()) {
154                body.insert(key.into(), v.clone());
155            }
156        }
157        body.insert("agent".into(), json!(std::env::var("AGENTMUX_AGENT_ID").unwrap_or_default().trim()));
158        body.insert("block".into(), json!(block_id.trim()));
159        srv_post_json(client, &url, auth_key, &Value::Object(body), "QuotaMode").await?
160    } else {
161        srv_get_json(client, &url, auth_key, &[], "QuotaMode").await?
162    };
163    Ok(serde_json::to_string_pretty(&answer).unwrap_or_else(|_| answer.to_string()))
164}
165
166async fn run_post_bulletin(name: &str, arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
167    let ToolCtx { local_url, auth_key, block_id, client, .. } = *cx;
168    if local_url.is_empty() || auth_key.is_empty() {
169        anyhow::bail!(
170            "AGENTMUX_LOCAL_URL and AGENTMUX_AUTH_KEY must be set. \
171             Is this agent pane opened via AgentMux?"
172        );
173    }
174    let agent = std::env::var("AGENTMUX_AGENT_ID").unwrap_or_default();
175    let url = format!("{}/api/v1/bulletin", local_url.trim_end_matches('/'));
176    let answer = if name == "PostBulletin" {
177        let mut body = serde_json::Map::new();
178        for key in ["message", "key", "targets", "expires_minutes"] {
179            if let Some(v) = arguments.get(key).filter(|v| !v.is_null()) {
180                body.insert(key.into(), v.clone());
181            }
182        }
183        body.insert("agent".into(), json!(agent.trim()));
184        body.insert("block".into(), json!(block_id.trim()));
185        srv_post_json(client, &url, auth_key, &Value::Object(body), name).await?
186    } else {
187        let query = vec![("agent", agent.trim().to_string()), ("block", block_id.trim().to_string())];
188        srv_get_json(client, &url, auth_key, &query, name).await?
189    };
190    Ok(serde_json::to_string_pretty(&answer).unwrap_or_else(|_| answer.to_string()))
191}
192
193async fn run_post_to_channel(name: &str, arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
194    let ToolCtx { local_url, auth_key, block_id, client, .. } = *cx;
195    if local_url.is_empty() || auth_key.is_empty() {
196        anyhow::bail!(
197            "AGENTMUX_LOCAL_URL and AGENTMUX_AUTH_KEY must be set. \
198             Is this agent pane opened via AgentMux?"
199        );
200    }
201    let agent = std::env::var("AGENTMUX_AGENT_ID").unwrap_or_default();
202    let url = format!("{}/api/v1/coord/posts", local_url.trim_end_matches('/'));
203    let answer = if name == "PostToChannel" {
204        let body = channel_post_body(arguments, &agent, block_id)?;
205        srv_post_json(client, &url, auth_key, &body, name).await?
206    } else {
207        let query = channel_read_query(arguments, &agent, block_id)?;
208        srv_get_json(client, &url, auth_key, &query, name).await?
209    };
210    Ok(serde_json::to_string_pretty(&answer).unwrap_or_else(|_| answer.to_string()))
211}
212
213/// A coordination post's PR argument: its number, and the repository its URL
214/// names (which must agree with `repo` when both are given).
215fn channel_pr(arguments: &Value) -> Result<(Option<String>, Option<u64>)> {
216    let Some(v) = arguments.get("pr").filter(|v| !v.is_null()) else { return Ok((None, None)) };
217    let (url_repo, n) =
218        pr_ref(v).ok_or_else(|| anyhow::anyhow!("pr must be a PR number (12, \"#12\") or its GitHub URL"))?;
219    let repo = match (url_repo, arg(arguments, "repo")) {
220        (Some(u), Some(r)) if normalize_repo(r) != normalize_repo(&u) => {
221            anyhow::bail!("pr is a PR of {u}, but repo is {r}: pass one or the other")
222        }
223        (Some(u), None) => Some(u),
224        _ => None,
225    };
226    Ok((repo, Some(n)))
227}
228
229/// `PostToChannel`'s request body.
230fn channel_post_body(arguments: &Value, agent: &str, block_id: &str) -> Result<Value> {
231    let mut body = serde_json::Map::new();
232    for key in ["message", "path", "repo", "branch", "topic"] {
233        if let Some(v) = arg(arguments, key) {
234            body.insert(key.into(), json!(v));
235        }
236    }
237    let (pr_repo, pr) = channel_pr(arguments)?;
238    if let Some(r) = pr_repo {
239        body.insert("repo".into(), json!(r));
240    }
241    if let Some(n) = pr {
242        body.insert("pr".into(), json!(n));
243    }
244    body.insert("agent".into(), json!(agent.trim()));
245    body.insert("block".into(), json!(block_id.trim()));
246    Ok(Value::Object(body))
247}
248
249/// `ReadChannel`'s query string.
250fn channel_read_query(arguments: &Value, agent: &str, block_id: &str) -> Result<Vec<(&'static str, String)>> {
251    let mut q = who_query(arguments, agent, block_id);
252    let (pr_repo, pr) = channel_pr(arguments)?;
253    if let Some(r) = pr_repo {
254        q.push(("repo", r));
255    }
256    if let Some(n) = pr {
257        q.push(("pr", n.to_string()));
258    }
259    for key in ["since_minutes", "limit"] {
260        if let Some(n) = arguments.get(key).and_then(|v| v.as_u64()) {
261            q.push((key, n.to_string()));
262        }
263    }
264    Ok(q)
265}
266
267/// A PR: `12`, `"12"`, `"#12"`, or its URL
268/// (`https://github.com/<owner>/<repo>/pull/12`, with anything after the
269/// number, like `/files` or `#issuecomment-…`), which also names its
270/// repository: `(Some("owner/repo"), 12)`.
271fn pr_ref(v: &Value) -> Option<(Option<String>, u64)> {
272    if let Some(n) = v.as_u64() {
273        return (n > 0).then_some((None, n));
274    }
275    let s = v.as_str()?.trim();
276    let number = |t: &str| t.parse::<u64>().ok().filter(|n| *n > 0);
277    let Some((before, after)) = s.split_once("/pull/") else {
278        return number(s.trim_start_matches('#')).map(|n| (None, n));
279    };
280    let digits: String = after.chars().take_while(char::is_ascii_digit).collect();
281    let rest = &after[digits.len()..];
282    if !(rest.is_empty() || rest.starts_with(['/', '#', '?'])) {
283        return None;
284    }
285    let mut parts = before.rsplit('/');
286    let (repo, owner) = (parts.next()?, parts.next()?);
287    if repo.is_empty() || owner.is_empty() || owner.contains(':') {
288        return None;
289    }
290    Some((Some(format!("{owner}/{repo}")), number(&digits)?))
291}
292
293/// `owner/repo`, lowercased, from `owner/repo`, a remote URL
294/// (`https://github.com/o/r.git`) or an ssh remote (`git@github.com:o/r`).
295fn normalize_repo(repo: &str) -> String {
296    let s = repo.trim().trim_end_matches('/').trim_end_matches(".git").replace(':', "/");
297    let mut parts = s.rsplit('/').filter(|p| !p.is_empty());
298    match (parts.next(), parts.next()) {
299        (Some(name), Some(owner)) => format!("{owner}/{name}").to_ascii_lowercase(),
300        _ => s.to_ascii_lowercase(),
301    }
302}
303
304/// Files of the asked PR whose local facts are fetched, at most.
305const PR_FILES_CHECKED: usize = 10;
306
307/// Add the open PRs that touch the question (`open_prs.rs`) to srv's answer,
308/// for the repository srv resolved. With `pr`, the agents on this computer
309/// are the ones with that PR's files changed or edited (`ask_path`, srv's
310/// answer for one file), not everyone in the repository. A failure is
311/// reported in the answer (`pr_error`) and never fails the call.
312async fn add_open_prs<F, Fut>(body: &mut Value, arguments: &Value, pr: Option<u64>, me: &str, ask_path: F)
313where
314    F: Fn(String) -> Fut,
315    Fut: std::future::Future<Output = Option<Value>>,
316{
317    let repo = body.pointer("/asked/repo").and_then(Value::as_str).map(str::to_string);
318    let Some(repo) = repo.filter(|r| r.contains('/') && !r.starts_with("local:")) else {
319        if pr.is_some() {
320            body["pr_error"] = json!("pr needs a repository on GitHub (owner/repo)");
321        }
322        return;
323    };
324    let mut prs = match open_prs::open_prs(&repo).await {
325        Ok(prs) => prs,
326        Err(e) => {
327            body["pr_error"] = json!(e);
328            return;
329        }
330    };
331    // An asked PR the list didn't hold (opened since it was cached): read it.
332    if let Some(n) = pr.filter(|n| !prs.iter().any(|p| p.number == *n)) {
333        match open_prs::open_pr(&repo, n).await {
334            Ok(Some(p)) => prs.push(p),
335            Ok(None) => {}
336            Err(e) => {
337                body["pr_error"] = json!(e);
338                return;
339            }
340        }
341    }
342    let host = open_prs::this_host();
343    let path = body.pointer("/asked/path").and_then(Value::as_str).map(str::to_string);
344    let asked = open_prs::Asked {
345        path: path.as_deref(),
346        branch: arg(arguments, "branch"),
347        query: arg(arguments, "query"),
348        pr,
349    };
350    let matches = match open_prs::pr_matches(&prs, &asked, me, &host) {
351        Ok(m) => m,
352        Err(e) => {
353            body["pr_error"] = json!(e);
354            return;
355        }
356    };
357    if let Some(files) = pr.and_then(|n| prs.iter().find(|p| p.number == n)).map(|p| p.files.clone()) {
358        let mut agents: Vec<Value> = Vec::new();
359        let mut posts: Vec<Value> = body.get("recent_posts").and_then(Value::as_array).cloned().unwrap_or_default();
360        for file in files.iter().take(PR_FILES_CHECKED) {
361            if let Some(answer) = ask_path(file.clone()).await {
362                merge_agents(&mut agents, answer.get("agents").and_then(Value::as_array).cloned().unwrap_or_default());
363                // Asked without branch and query (for a broad agent lookup): apply them to its posts here.
364                let file_posts = answer.get("recent_posts").and_then(Value::as_array).cloned().unwrap_or_default();
365                merge_posts(&mut posts, file_posts.into_iter().filter(|p| post_matches(p, arguments)).collect());
366            }
367        }
368        body["agents"] = Value::Array(agents);
369        // The PR's own posts and its files' posts, newest first, as srv caps them.
370        posts.sort_by_key(|p| std::cmp::Reverse(p.get("at").and_then(Value::as_i64).unwrap_or(0)));
371        posts.truncate(RECENT_POSTS_MAX);
372        body["recent_posts"] = Value::Array(posts);
373        if files.len() > PR_FILES_CHECKED {
374            body["pr_note"] = json!(format!(
375                "the PR changes {} files; agents on this computer were checked against the first {PR_FILES_CHECKED}",
376                files.len()
377            ));
378        }
379    }
380    open_prs::merge_into(body, matches, &host, &repo);
381}
382
383/// `WhoIsWorkingOn`'s `recent_posts` holds at most this many (srv's cap).
384const RECENT_POSTS_MAX: usize = 5;
385
386/// Whether a post fits the question's `branch` and `query`, as srv selects
387/// them (`work_facts::coord::matches`): the branch it is about, or none; every
388/// word of `query` in its topic, path or text, case-insensitively.
389fn post_matches(post: &Value, arguments: &Value) -> bool {
390    let field = |k: &str| post.get(k).and_then(Value::as_str).unwrap_or("");
391    if let (Some(asked), Some(on)) = (arg(arguments, "branch"), post.get("branch").and_then(Value::as_str)) {
392        if !asked.eq_ignore_ascii_case(on) {
393            return false;
394        }
395    }
396    match arg(arguments, "query") {
397        Some(q) => {
398            let hay = format!("{} {} {}", field("topic"), field("path"), field("text")).to_lowercase();
399            q.to_lowercase().split_whitespace().all(|w| hay.contains(w))
400        }
401        None => true,
402    }
403}
404
405/// Add posts not already in `into` (by id).
406fn merge_posts(into: &mut Vec<Value>, from: Vec<Value>) {
407    for post in from {
408        if !into.iter().any(|p| p.get("id") == post.get("id")) {
409            into.push(post);
410        }
411    }
412}
413
414/// Merge srv answers for several files: one entry per agent and channel,
415/// with every distinct match.
416fn merge_agents(into: &mut Vec<Value>, from: Vec<Value>) {
417    for agent in from {
418        let key = |a: &Value| (a.get("agent").cloned(), a.get("channel").cloned());
419        match into.iter_mut().find(|a| key(a) == key(&agent)) {
420            Some(existing) => {
421                let new = agent.get("matches").and_then(Value::as_array).cloned().unwrap_or_default();
422                if let Some(list) = existing.get_mut("matches").and_then(Value::as_array_mut) {
423                    for m in new {
424                        if !list.contains(&m) {
425                            list.push(m);
426                        }
427                    }
428                }
429            }
430            None => into.push(agent),
431        }
432    }
433}
434
435/// The trimmed, non-empty string argument `key`.
436fn arg<'a>(arguments: &'a Value, key: &str) -> Option<&'a str> {
437    arguments.get(key).and_then(|v| v.as_str()).map(str::trim).filter(|v| !v.is_empty())
438}
439
440/// What srv's `/api/v1/work-claims` takes: the claimed target, note and
441/// lifetime, plus who is asking (srv prefers the request's agent token).
442fn claim_body(arguments: &Value, agent: &str, block_id: &str) -> Value {
443    let mut body = serde_json::Map::new();
444    for key in ["path", "repo", "branch", "topic", "note"] {
445        if let Some(v) = arg(arguments, key) {
446            body.insert(key.into(), json!(v));
447        }
448    }
449    if let Some(m) = arguments.get("ttl_minutes").and_then(|v| v.as_u64()) {
450        body.insert("ttl_minutes".into(), json!(m));
451    }
452    body.insert("agent".into(), json!(agent.trim()));
453    body.insert("block".into(), json!(block_id.trim()));
454    Value::Object(body)
455}
456
457/// What srv's `/api/v1/work-claims/release` takes: a claim id, or none for all.
458fn release_body(arguments: &Value, agent: &str, block_id: &str) -> Value {
459    json!({ "id": arg(arguments, "id"), "agent": agent.trim(), "block": block_id.trim() })
460}
461
462#[cfg(test)]
463mod call_tests;
464
465#[cfg(test)]
466mod tests {
467    use super::*;
468
469    #[test]
470    fn a_channel_post_carries_its_pr_and_the_repository_a_pr_url_names() {
471        let body = channel_post_body(
472            &json!({ "message": "regenerate INDEX.md", "path": "docs/specs", "pr": "https://github.com/o/r/pull/12" }),
473            "Loap-3",
474            "blk",
475        )
476        .unwrap();
477        assert_eq!(body["message"], "regenerate INDEX.md");
478        assert_eq!(body["path"], "docs/specs");
479        assert_eq!(body["repo"], "o/r");
480        assert_eq!(body["pr"], 12);
481        assert_eq!((body["agent"].as_str(), body["block"].as_str()), (Some("Loap-3"), Some("blk")));
482        assert!(channel_post_body(&json!({ "message": "x", "repo": "o/other", "pr": "https://github.com/o/r/pull/12" }), "a", "b").is_err());
483        assert!(channel_post_body(&json!({ "message": "x", "pr": "nope" }), "a", "b").is_err());
484    }
485
486    #[test]
487    fn a_files_posts_keep_the_questions_branch_and_query() {
488        let post = json!({ "branch": "main", "topic": "docs index", "path": "docs/specs/INDEX.md", "text": "regenerate it" });
489        assert!(post_matches(&post, &json!({})));
490        assert!(post_matches(&post, &json!({ "branch": "MAIN", "query": "Index regenerate" })));
491        assert!(!post_matches(&post, &json!({ "branch": "dev" })));
492        assert!(!post_matches(&post, &json!({ "query": "shim" })));
493        assert!(post_matches(&json!({ "text": "x" }), &json!({ "branch": "dev" })), "a post on no branch fits any");
494    }
495
496    #[test]
497    fn posts_from_several_files_merge_once_each() {
498        let mut into = vec![json!({ "id": "a", "at": 3 })];
499        merge_posts(&mut into, vec![json!({ "id": "a", "at": 3 }), json!({ "id": "b", "at": 5 })]);
500        assert_eq!(into.iter().map(|p| p["id"].as_str().unwrap()).collect::<Vec<_>>(), vec!["a", "b"]);
501    }
502
503    #[test]
504    fn a_channel_read_passes_its_filters_window_and_limit() {
505        let q = channel_read_query(&json!({ "path": "a.rs", "pr": 7, "since_minutes": 60, "limit": 5, "query": "index" }), "a", "b").unwrap();
506        let get = |k: &str| q.iter().find(|(key, _)| *key == k).map(|(_, v)| v.as_str());
507        assert_eq!(get("path"), Some("a.rs"));
508        assert_eq!(get("query"), Some("index"));
509        assert_eq!(get("pr"), Some("7"));
510        assert_eq!(get("since_minutes"), Some("60"));
511        assert_eq!(get("limit"), Some("5"));
512    }
513
514    #[test]
515    fn a_pr_is_a_number_a_hash_number_or_a_url_naming_its_repository() {
516        assert_eq!(pr_ref(&json!(12)), Some((None, 12)));
517        assert_eq!(pr_ref(&json!("12")), Some((None, 12)));
518        assert_eq!(pr_ref(&json!("#12")), Some((None, 12)));
519        let url = |u: &str| pr_ref(&json!(u));
520        assert_eq!(url("https://github.com/o/r/pull/4683"), Some((Some("o/r".into()), 4683)));
521        assert_eq!(url("https://github.com/o/r/pull/4683/"), Some((Some("o/r".into()), 4683)));
522        assert_eq!(url("https://github.com/o/r/pull/4683/files"), Some((Some("o/r".into()), 4683)));
523        assert_eq!(url("https://github.com/o/r/pull/4683#issuecomment-1"), Some((Some("o/r".into()), 4683)));
524        assert_eq!(url("https://github.com/o/r/pull/4683x"), None);
525        assert_eq!(url("https://github.com/o/r/issues/12"), None);
526        assert_eq!(url("main"), None);
527        assert_eq!(pr_ref(&json!(0)), None);
528    }
529
530    #[test]
531    fn repositories_are_compared_whole_not_by_suffix() {
532        assert_eq!(normalize_repo("Foo/Bar"), "foo/bar");
533        assert_eq!(normalize_repo("https://github.com/foo/bar.git"), "foo/bar");
534        assert_eq!(normalize_repo("git@github.com:foo/bar"), "foo/bar");
535        assert_ne!(normalize_repo("notfoo/bar"), normalize_repo("foo/bar"));
536    }
537
538    #[test]
539    fn answers_for_several_files_merge_by_agent() {
540        let mut agents = Vec::new();
541        merge_agents(&mut agents, vec![json!({ "agent": "A", "channel": "c", "matches": [{ "kind": "dirty", "detail": "x" }] })]);
542        merge_agents(&mut agents, vec![
543            json!({ "agent": "A", "channel": "c", "matches": [{ "kind": "dirty", "detail": "x" }, { "kind": "edited", "detail": "y" }] }),
544            json!({ "agent": "B", "channel": "c", "matches": [] }),
545        ]);
546        assert_eq!(agents.len(), 2);
547        assert_eq!(agents[0]["matches"].as_array().unwrap().len(), 2);
548    }
549
550    #[test]
551    fn only_given_arguments_and_the_callers_identity_are_sent() {
552        let q = who_query(&json!({ "path": " crates/srv ", "query": "", "repo": null, "pr": 12 }), "AgentY", "blk");
553        assert_eq!(
554            q,
555            vec![("path", "crates/srv".to_string()), ("agent", "AgentY".to_string()), ("block", "blk".to_string())]
556        );
557        assert!(who_query(&json!({}), "", "").is_empty());
558    }
559
560    #[test]
561    fn claims_send_only_what_was_given_plus_the_callers_identity() {
562        let body = claim_body(
563            &json!({ "path": " crates/srv ", "topic": "", "note": "presence work", "ttl_minutes": 45, "repo": null }),
564            "AgentY",
565            "blk",
566        );
567        assert_eq!(
568            body,
569            json!({ "path": "crates/srv", "note": "presence work", "ttl_minutes": 45, "agent": "AgentY", "block": "blk" })
570        );
571        assert_eq!(release_body(&json!({}), "AgentY", "blk"), json!({ "id": null, "agent": "AgentY", "block": "blk" }));
572        assert_eq!(release_body(&json!({ "id": "c1" }), "AgentY", "")["id"], "c1");
573    }
574
575    #[tokio::test]
576    async fn without_agentmux_env_it_says_so() {
577        let client = reqwest::Client::new();
578        let loops = LoopRegistry::default();
579        let counter = std::sync::atomic::AtomicU64::new(0);
580        let cx = ToolCtx { local_url: "", auth_key: "", block_id: "", client: &client, loops: &loops, loop_counter: &counter };
581        for tool in ["WhoIsWorkingOn", "ClaimWork", "ReleaseWork"] {
582            let err = call(tool, &json!({ "path": "a" }), &cx).await.unwrap_err();
583            assert!(err.to_string().contains("AGENTMUX_LOCAL_URL"), "{tool}");
584        }
585    }
586}