Skip to main content

agentmux_srv/server/
work_facts_handlers.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! HTTP side of agents' work facts
5//! (docs/specs/SPEC_AGENT_OVERLAP_AWARENESS_2026_10_10.md §3.1, §3.2):
6//!
7//! - `GET /api/v1/work-facts`: this srv's own agents' facts. Other channels
8//!   on this computer call it; it never fans out itself.
9//! - `GET /api/v1/work-facts/who`: the `WhoIsWorkingOn` MCP tool. This srv's
10//!   agents plus every other channel's (through the host-global registry,
11//!   the same reach `ListConversations` has), matched against the question.
12//!   LAN and WAN agents are listed by name only: their facts stay on their
13//!   own computer.
14//!
15//! Both answers include live work claims (`ClaimWork`, §3.4,
16//! `work_claims_handlers`). Also adds the facts to `ListConversations`
17//! entries ([`annotate_conversations`]).
18
19use std::collections::HashMap;
20
21use axum::extract::{Query, State};
22use axum::http::StatusCode;
23use axum::response::{IntoResponse, Json, Response};
24use serde::Deserialize;
25use serde_json::json;
26
27use crate::backend::reactive::types::AgentRegistration;
28use crate::backend::work_facts::cross_channel::{self, own_channel};
29use crate::backend::work_facts::{self, claims, matching, WorkFacts};
30
31use super::caller::Caller;
32use super::AppState;
33
34/// Shown with every answer, so an agent reads it as information.
35const NOTE: &str = "Informational only: nothing is locked or blocked. If someone else is changing the same \
36                    thing, message them (Message send) before you change it.";
37
38/// This srv's own agents' facts. Store reads, so off the async workers.
39pub(crate) async fn local_facts(state: &AppState) -> Vec<WorkFacts> {
40    let regs = state.reactive_handler.list_agents();
41    let store = state.mstore.clone();
42    let channel = own_channel();
43    tokio::task::spawn_blocking(move || work_facts::collect_local(&store, &regs, &channel))
44        .await
45        .unwrap_or_default()
46}
47
48/// Every other channel's agents' facts, plus the channels that didn't answer.
49pub(super) async fn cross_channel_facts(state: &AppState) -> (Vec<WorkFacts>, Vec<String>) {
50    cross_channel::fetch(&state.http_client, &state.local_web_url).await
51}
52
53/// `GET /api/v1/work-facts`: this srv's own agents' work facts.
54pub async fn handle_work_facts(State(state): State<AppState>) -> impl IntoResponse {
55    Json(json!({ "channel": own_channel(), "agents": local_facts(&state).await }))
56}
57
58/// `WhoIsWorkingOn`'s arguments, plus who is asking (`agent`, `block`: the
59/// MCP's own `AGENTMUX_AGENT_ID` and block id; the request's agent token wins
60/// over both).
61#[derive(Debug, Default, Deserialize)]
62pub struct WhoParams {
63    pub path: Option<String>,
64    pub repo: Option<String>,
65    pub branch: Option<String>,
66    pub query: Option<String>,
67    /// A PR: `recent_posts` then holds only posts about it (the MCP side asks
68    /// about each of its files too, and merges those posts in).
69    pub pr: Option<i64>,
70    pub agent: Option<String>,
71    pub block: Option<String>,
72}
73
74/// The caller's own block: by its token's UID, else the block id it sent,
75/// else its name when exactly one registered agent has it. Only used to
76/// leave the caller out and to read its own repository, so a name is enough.
77pub(super) fn caller_block(regs: &[AgentRegistration], uid: Option<&str>, block: Option<&str>, agent: Option<&str>) -> Option<String> {
78    if let Some(uid) = uid {
79        if let Some(r) = regs.iter().find(|r| r.uid.as_deref() == Some(uid)) {
80            return Some(r.block_id.clone());
81        }
82    }
83    let block = block.map(str::trim).filter(|b| !b.is_empty());
84    if let Some(r) = block.and_then(|b| regs.iter().find(|r| r.block_id == b)) {
85        return Some(r.block_id.clone());
86    }
87    let agent = agent.map(str::trim).filter(|a| !a.is_empty())?;
88    let mut named = regs.iter().filter(|r| r.agent_id.eq_ignore_ascii_case(agent));
89    match (named.next(), named.next()) {
90        (Some(r), None) => Some(r.block_id.clone()),
91        _ => None,
92    }
93}
94
95/// Take the caller's own facts out of `facts`.
96pub(super) fn split_caller(facts: Vec<WorkFacts>, caller_block: Option<&str>) -> (Option<WorkFacts>, Vec<WorkFacts>) {
97    let (mine, others): (Vec<_>, Vec<_>) =
98        facts.into_iter().partition(|f| caller_block.is_some_and(|b| f.block_id == b));
99    (mine.into_iter().next(), others)
100}
101
102/// LAN and WAN agents: name and liveness only. A WAN agent that the account's cloud list (`cloud_installs`) has
103/// says its state there (`working`, `idle`, ...) instead of a bare "online"; the Swarm reads the same list.
104fn remote_agents(state: &AppState) -> Vec<serde_json::Value> {
105    let mut out = Vec::new();
106    for lan in state.lan_discovery.get_instances() {
107        for name in &lan.agents {
108            out.push(json!({ "agent": name, "channel": "lan", "status": "online" }));
109        }
110    }
111    if let Some(sub) = crate::muxbus::cloud_subscriber::get_global_subscriber() {
112        // The cache as it is: `who` never waits on the relay, and an old cache starts a read for the next ask.
113        let cloud = crate::muxbus::cloud_installs::cached();
114        let own_wan_id = crate::backend::swarm_cloud::own_wan_id();
115        let now_ms = agentmux_common::time::now_ms_u64();
116        for name in sub.subscribed_agents() {
117            out.push(json!({ "agent": name, "channel": "wan", "status": cloud.as_ref().and_then(|c| crate::backend::swarm_cloud::agent_state(c, &name, own_wan_id.as_deref(), now_ms)).unwrap_or("online") }));
118        }
119    }
120    out
121}
122
123/// `GET /api/v1/work-facts/who`: `WhoIsWorkingOn`.
124pub(crate) async fn handle_who_is_working_on(
125    State(state): State<AppState>,
126    caller: Option<axum::Extension<Caller>>,
127    Query(p): Query<WhoParams>,
128) -> Response {
129    let regs = state.reactive_handler.list_agents();
130    let uid = caller.as_ref().and_then(|c| c.0.uid().map(str::to_string));
131    let me_block = caller_block(&regs, uid.as_deref(), p.block.as_deref(), p.agent.as_deref());
132    let store = state.work_store.clone();
133    let now = agentmux_common::time::now_ms();
134    let live_claims = tokio::task::spawn_blocking(move || store.work_claims_live(now).unwrap_or_default());
135    let (local, (cross, unreachable), live_claims) =
136        tokio::join!(local_facts(&state), cross_channel_facts(&state), live_claims);
137    let (me, mut others) = split_caller(local, me_block.as_deref());
138    others.extend(cross);
139
140    let q = matching::WhoQuery { path: p.path, repo: p.repo, branch: p.branch, query: p.query };
141    let target = match matching::resolve(&q, me.as_ref(), &others) {
142        Ok(t) => t,
143        Err(e) => return (StatusCode::BAD_REQUEST, Json(json!({ "error": e }))).into_response(),
144    };
145    let mut agents = matching::who_is_working_on(&target, &others);
146    // Everyone's claims but the caller's own (by UID, else by name).
147    let me_name = me.as_ref().map(|m| m.agent.clone()).or(p.agent).unwrap_or_default();
148    let theirs: Vec<_> = live_claims
149        .unwrap_or_default()
150        .into_iter()
151        .filter(|c| !claims::is_own(c, &me_name, uid.as_deref().unwrap_or("")))
152        .collect();
153    claims::add_claim_matches(&mut agents, &target, &theirs, &others, now);
154    // What agents posted about it (SPEC_AGENT_COORDINATION_CHANNEL_2026_10_15 §3.4).
155    let store = state.work_store.clone();
156    let asked = target.clone();
157    let pr = p.pr.filter(|n| *n > 0);
158    let recent_posts = tokio::task::spawn_blocking(move || super::coord_channel_handlers::recent_posts(&store, &asked, pr, now))
159        .await
160        .unwrap_or_default();
161    Json(json!({
162        "asked": target,
163        "caller": me.as_ref().map(|m| json!({ "agent": m.agent, "repo": m.repo, "branch": m.branch })),
164        "agents": agents,
165        "recent_posts": recent_posts,
166        "remote_agents": remote_agents(&state),
167        "unreachable_channels": unreachable,
168        "note": NOTE,
169    }))
170    .into_response()
171}
172
173/// Start gathering every agent's facts for `ListConversations`, this srv's
174/// and the other channels' at once, so the handler can run its own preview
175/// fan-out meanwhile rather than paying a second round after it.
176pub(super) fn start_conversation_facts(state: &AppState) -> tokio::task::JoinHandle<Vec<WorkFacts>> {
177    let state = state.clone();
178    tokio::spawn(async move {
179        let (mut local, (cross, _)) = tokio::join!(local_facts(&state), cross_channel_facts(&state));
180        local.extend(cross);
181        local
182    })
183}
184
185/// Add a `work` field (see `work_facts::conversation_summary`) to every
186/// host and cross-channel `ListConversations` entry that names its block,
187/// from the facts [`start_conversation_facts`] gathered. If gathering failed
188/// the entries are left as they were.
189pub(super) async fn annotate_conversations(
190    facts: tokio::task::JoinHandle<Vec<WorkFacts>>,
191    entries: &mut [serde_json::Value],
192) {
193    let facts = facts.await.unwrap_or_default();
194    let by_block: HashMap<&str, &WorkFacts> = facts.iter().map(|f| (f.block_id.as_str(), f)).collect();
195    for e in entries.iter_mut() {
196        let Some(f) = e.get("block_id").and_then(|b| b.as_str()).and_then(|b| by_block.get(b)) else {
197            continue;
198        };
199        let summary = work_facts::conversation_summary(f);
200        if let Some(obj) = e.as_object_mut() {
201            obj.insert("work".to_string(), summary);
202        }
203    }
204}
205
206#[cfg(test)]
207mod tests {
208    use super::*;
209
210    fn reg(agent: &str, block: &str, uid: Option<&str>) -> AgentRegistration {
211        AgentRegistration {
212            agent_id: agent.into(),
213            block_id: block.into(),
214            tab_id: None,
215            uid: uid.map(Into::into),
216            registered_at: 0,
217            last_seen: 0,
218            registration_nonce: 0,
219        }
220    }
221
222    #[test]
223    fn the_caller_is_found_by_token_then_block_then_unique_name() {
224        let regs = vec![reg("AgentY", "b1", Some("u1")), reg("Agent2", "b2", None), reg("Agent2", "b3", None)];
225        assert_eq!(caller_block(&regs, Some("u1"), Some("b2"), None).as_deref(), Some("b1"));
226        assert_eq!(caller_block(&regs, None, Some("b2"), Some("AgentY")).as_deref(), Some("b2"));
227        assert_eq!(caller_block(&regs, None, None, Some("agenty")).as_deref(), Some("b1"));
228        assert_eq!(caller_block(&regs, None, None, Some("Agent2")), None, "an ambiguous name names no one");
229        assert_eq!(caller_block(&regs, None, Some("gone"), None), None);
230    }
231
232    /// The caller is left out of the answer, and its own facts are what
233    /// a relative path resolves against.
234    #[test]
235    fn the_caller_is_excluded_and_its_repository_is_assumed() {
236        let fact = |agent: &str, block: &str, root: &str| WorkFacts {
237            agent: agent.into(),
238            block_id: block.into(),
239            repo: Some("o/r".into()),
240            repo_root: Some(root.into()),
241            dirty_files: vec!["a.rs".into()],
242            ..Default::default()
243        };
244        let (me, others) = split_caller(vec![fact("Me", "b1", "/me"), fact("Other", "b2", "/o")], Some("b1"));
245        assert_eq!(me.as_ref().map(|m| m.agent.as_str()), Some("Me"));
246        let q = matching::WhoQuery { path: Some("a.rs".into()), ..Default::default() };
247        let t = matching::resolve(&q, me.as_ref(), &others).unwrap();
248        let names: Vec<String> = matching::who_is_working_on(&t, &others).into_iter().map(|r| r.agent).collect();
249        assert_eq!(names, vec!["Other".to_string()]);
250
251        let (none, all) = split_caller(vec![fact("A", "b1", "/a")], None);
252        assert!(none.is_none());
253        assert_eq!(all.len(), 1, "an unknown caller excludes no one");
254    }
255
256    #[tokio::test]
257    async fn the_facts_endpoint_lists_this_srvs_agents() {
258        let state = crate::server::tests::test_state();
259        let unique = uuid::Uuid::new_v4();
260        let (agent, block) = (format!("facts-agent-{unique}"), format!("facts-block-{unique}"));
261        state.reactive_handler.register_agent(&agent, &block, None).unwrap();
262        let resp = handle_work_facts(State(state)).await.into_response();
263        assert_eq!(resp.status(), StatusCode::OK);
264        let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX).await.unwrap();
265        let body: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
266        let agents: Vec<WorkFacts> = serde_json::from_value(body["agents"].clone()).unwrap();
267        let mine = agents.iter().find(|f| f.agent == agent).expect("registered agent listed");
268        assert_eq!(mine.block_id, block);
269        assert_eq!(mine.status, "stopped", "no controller in a test");
270    }
271
272    #[tokio::test]
273    async fn who_explains_a_question_it_cannot_answer() {
274        let state = crate::server::tests::test_state();
275        let resp = handle_who_is_working_on(
276            State(state),
277            None,
278            Query(WhoParams { path: Some("relative/x.rs".into()), ..Default::default() }),
279        )
280        .await;
281        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
282    }
283
284    #[tokio::test]
285    async fn conversations_entries_gain_a_work_field_by_block() {
286        let state = crate::server::tests::test_state();
287        let unique = uuid::Uuid::new_v4();
288        let (agent, block) = (format!("conv-agent-{unique}"), format!("conv-block-{unique}"));
289        state.reactive_handler.register_agent(&agent, &block, None).unwrap();
290        let mut entries = vec![
291            json!({ "name": agent, "tier": "host", "block_id": block }),
292            json!({ "name": "remote", "tier": "lan" }),
293        ];
294        annotate_conversations(start_conversation_facts(&state), &mut entries).await;
295        assert!(entries[0]["work"].is_object(), "{}", entries[0]);
296        assert_eq!(entries[0]["work"]["dirty_count"], 0);
297        assert!(entries[1].get("work").is_none(), "LAN entries carry no facts");
298    }
299}