Skip to main content

agentmux_srv/server/
work_claims_handlers.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! HTTP side of work claims
5//! (docs/specs/SPEC_AGENT_OVERLAP_AWARENESS_2026_10_10.md §3.4):
6//!
7//! - `POST /api/v1/work-claims`: `ClaimWork`. Records (or renews) the
8//!   caller's claim on a path, branch or topic, and answers with who else is
9//!   already working on it.
10//! - `POST /api/v1/work-claims/release`: `ReleaseWork`. Releases one of the
11//!   caller's claims, or all of them.
12//!
13//! Claims are stored in the identity store (`storage::work_claims`), so
14//! every channel's `WhoIsWorkingOn` and overlap notes see them. Nothing is
15//! ever locked: a claim only informs.
16
17use axum::extract::State;
18use axum::http::StatusCode;
19use axum::response::{IntoResponse, Json, Response};
20use serde::Deserialize;
21use serde_json::json;
22
23use crate::backend::storage::work_claims::WorkClaim;
24use crate::backend::work_facts::cross_channel::own_channel;
25use crate::backend::work_facts::{claims, coord, matching};
26
27use super::caller::Caller;
28use super::work_facts_handlers::{caller_block, cross_channel_facts, local_facts, split_caller};
29use super::AppState;
30
31/// `ClaimWork`'s arguments, plus who is asking (`agent`, `block`: the MCP's
32/// own `AGENTMUX_AGENT_ID` and block id; the request's agent token wins).
33#[derive(Debug, Default, Deserialize)]
34pub struct ClaimParams {
35    pub path: Option<String>,
36    pub repo: Option<String>,
37    pub branch: Option<String>,
38    pub topic: Option<String>,
39    pub note: Option<String>,
40    pub ttl_minutes: Option<u64>,
41    pub agent: Option<String>,
42    pub block: Option<String>,
43}
44
45/// `ReleaseWork`'s arguments: a claim id, or none for all of the caller's.
46#[derive(Debug, Default, Deserialize)]
47pub struct ReleaseParams {
48    pub id: Option<String>,
49    pub agent: Option<String>,
50    pub block: Option<String>,
51}
52
53fn bad_request(msg: impl Into<String>) -> Response {
54    (StatusCode::BAD_REQUEST, Json(json!({ "error": msg.into() }))).into_response()
55}
56
57/// The longest note, topic, path, branch and repository a claim keeps, in
58/// characters. Another agent reads them in its notes and answers.
59const MAX_NOTE: usize = 200;
60const MAX_TOPIC: usize = 120;
61const MAX_PATH: usize = 400;
62const MAX_NAME: usize = 200;
63
64/// A claim's free text as it is kept: one line (control characters and line
65/// breaks become spaces, whitespace runs collapse) of at most `max`
66/// characters. Marker quoting happens where the text is shown inside a
67/// system note (`work_facts::overlap`).
68pub(super) fn one_line(s: &Option<String>, max: usize) -> Option<String> {
69    let flat: String = s.as_deref()?.chars().map(|c| if c.is_control() { ' ' } else { c }).collect();
70    let flat = flat.split_whitespace().collect::<Vec<_>>().join(" ");
71    if flat.is_empty() {
72        return None;
73    }
74    Some(match flat.char_indices().nth(max) {
75        Some((cut, _)) => format!("{}…", &flat[..cut]),
76        None => flat,
77    })
78}
79
80fn nonempty(s: &Option<String>) -> Option<&str> {
81    s.as_deref().map(str::trim).filter(|s| !s.is_empty())
82}
83
84/// Who is asking. A caller with a token is that token's agent and nobody
85/// else: its registration is the one with its UID (never one a `block` or a
86/// name it sent points at), and with none its name is its own slug. Without a
87/// token: the registration found by block, then unique name (as
88/// `WhoIsWorkingOn` does), else the name it sent. `None` when there is no name
89/// at all.
90///
91/// A caller with a token whose registration is missing (the registry is rebuilt after a restart or an
92/// upgrade, and a pane that was resumed can go unregistered for hours: #2271) still has its pane: the
93/// block whose meta names its UID, which is where `Agents list` finds it too.
94pub(super) fn claimer(
95    state: &AppState,
96    caller: Option<&Caller>,
97    agent: Option<&str>,
98    block: Option<&str>,
99) -> Option<(String, String, Option<String>)> {
100    let regs = state.reactive_handler.list_agents();
101    let token_uid = caller.and_then(|c| c.uid().map(str::to_string));
102    let block_id = match token_uid.as_deref() {
103        Some(uid) => regs
104            .iter()
105            .find(|r| r.uid.as_deref() == Some(uid))
106            .map(|r| r.block_id.clone())
107            .or_else(|| super::agent_runtime::pane_blocks_by_agent(&state.mstore).remove(uid)),
108        None => caller_block(&regs, None, block, agent),
109    };
110    let reg = block_id.as_deref().and_then(|b| regs.iter().find(|r| r.block_id == b));
111    let name = match (reg, token_uid.as_deref()) {
112        (Some(r), _) => r.agent_id.clone(),
113        (None, Some(uid)) => state.mstore.agent_names_by_id(uid).ok().flatten().map(|row| row.slug).filter(|s| !s.is_empty())?,
114        (None, None) => agent.map(str::trim).filter(|a| !a.is_empty()).map(str::to_string)?,
115    };
116    let uid = token_uid.or_else(|| reg.and_then(|r| r.uid.clone())).unwrap_or_default();
117    Some((name, uid, block_id))
118}
119
120/// `POST /api/v1/work-claims`: `ClaimWork`.
121pub(crate) async fn handle_claim_work(
122    State(state): State<AppState>,
123    caller: Option<axum::Extension<Caller>>,
124    Json(p): Json<ClaimParams>,
125) -> Response {
126    let p = ClaimParams {
127        path: one_line(&p.path, MAX_PATH),
128        repo: one_line(&p.repo, MAX_NAME),
129        branch: one_line(&p.branch, MAX_NAME),
130        topic: one_line(&p.topic, MAX_TOPIC),
131        note: one_line(&p.note, MAX_NOTE),
132        ..p
133    };
134    if [&p.path, &p.repo, &p.branch, &p.topic].iter().all(|v| nonempty(v).is_none()) {
135        return bad_request("nothing to claim: pass path, branch or topic (and repo for a whole repository)");
136    }
137    let Some((agent, uid, me_block)) =
138        claimer(&state, caller.as_ref().map(|c| &c.0), p.agent.as_deref(), p.block.as_deref())
139    else {
140        return bad_request("who is claiming is unknown: this needs an agent started by AgentMux");
141    };
142    let (local, (cross, _)) = tokio::join!(local_facts(&state), cross_channel_facts(&state));
143    let (me, mut others) = split_caller(local, me_block.as_deref());
144    others.extend(cross);
145
146    let q = matching::WhoQuery {
147        path: p.path.clone(),
148        repo: p.repo.clone(),
149        branch: p.branch.clone(),
150        query: p.topic.clone(),
151    };
152    let mut target = match matching::resolve(&q, me.as_ref(), &others) {
153        Ok(t) => t,
154        Err(e) => return bad_request(e),
155    };
156    // Only a repository named: the whole of it.
157    if [&p.path, &p.branch, &p.topic].iter().all(|v| nonempty(v).is_none()) {
158        target.path = Some(String::new());
159    }
160
161    let now = agentmux_common::time::now_ms();
162    let claim = WorkClaim {
163        id: uuid::Uuid::new_v4().to_string(),
164        agent: agent.clone(),
165        agent_uid: uid.clone(),
166        channel: own_channel(),
167        repo: target.repo.clone(),
168        path: target.path.clone(),
169        absolute_path: target.absolute_path.clone(),
170        branch: target.branch.clone(),
171        topic: target.query.clone(),
172        note: p.note.clone().unwrap_or_default(),
173        created_at: now,
174        expires_at: now + claims::ttl_ms(p.ttl_minutes),
175    };
176    let store = state.work_store.clone();
177    let identified = caller.as_ref().is_some_and(|c| c.0.uid().is_some());
178    let stored = tokio::task::spawn_blocking(move || {
179        let stored = store.work_claim_put(&claim, now)?;
180        // A new claim in its repository's channel (SPEC_AGENT_COORDINATION_CHANNEL_2026_10_15
181        // §3.5); a renewal (it keeps the existing claim's id) posts nothing, or re-claiming to
182        // extend it would fill the channel.
183        if stored.id == claim.id {
184            if let Some(post) = coord::claim_post(&stored, false, identified, now) {
185                let _ = store.coord_post_put(&post, now);
186            }
187        }
188        let live = store.work_claims_live(now)?;
189        Ok::<_, crate::backend::storage::StoreError>((stored, live))
190    })
191    .await;
192    let (stored, live) = match stored {
193        Ok(Ok(v)) => v,
194        Ok(Err(e)) => {
195            return (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({ "error": format!("claim not saved: {e}") })))
196                .into_response()
197        }
198        Err(e) => {
199            return (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({ "error": format!("claim not saved: {e}") })))
200                .into_response()
201        }
202    };
203
204    // Who else is already on it, their claims included.
205    let theirs: Vec<WorkClaim> = live.into_iter().filter(|c| !claims::is_own(c, &agent, &uid)).collect();
206    let others: Vec<_> = others.into_iter().filter(|f| !f.agent.eq_ignore_ascii_case(&agent)).collect();
207    let mut overlapping = matching::who_is_working_on(&target, &others);
208    claims::add_claim_matches(&mut overlapping, &target, &theirs, &others, now);
209    Json(json!({
210        "claim": stored,
211        "claimed": claims::describe(&stored),
212        "others_working_on_it": overlapping,
213        "note": "Claimed. Other agents see this in Presence who and are told when they edit a file in it. It \
214                 blocks no one, and lapses at expires_at unless you claim it again. Release it with Presence release \
215                 when you are done. If others_working_on_it names anyone, message them (Message send).",
216    }))
217    .into_response()
218}
219
220/// `POST /api/v1/work-claims/release`: `ReleaseWork`.
221pub(crate) async fn handle_release_work(
222    State(state): State<AppState>,
223    caller: Option<axum::Extension<Caller>>,
224    Json(p): Json<ReleaseParams>,
225) -> Response {
226    let Some((agent, uid, _)) = claimer(&state, caller.as_ref().map(|c| &c.0), p.agent.as_deref(), p.block.as_deref())
227    else {
228        return bad_request("who is releasing is unknown: this needs an agent started by AgentMux");
229    };
230    let id = nonempty(&p.id).map(str::to_string);
231    let store = state.work_store.clone();
232    let now = agentmux_common::time::now_ms();
233    let identified = caller.as_ref().is_some_and(|c| c.0.uid().is_some());
234    let released = tokio::task::spawn_blocking(move || {
235        let released = store.work_claim_release(&agent, &uid, id.as_deref(), now)?;
236        for c in &released {
237            if let Some(post) = coord::claim_post(c, true, identified, now) {
238                let _ = store.coord_post_put(&post, now);
239            }
240        }
241        Ok::<_, crate::backend::storage::StoreError>(released)
242    })
243    .await;
244    match released {
245        Ok(Ok(released)) => {
246            let note = if released.is_empty() {
247                "Nothing released: you hold no live claim with that id."
248            } else {
249                "Released."
250            };
251            Json(json!({ "released": released, "note": note })).into_response()
252        }
253        Ok(Err(e)) => (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({ "error": format!("release failed: {e}") })))
254            .into_response(),
255        Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({ "error": format!("release failed: {e}") })))
256            .into_response(),
257    }
258}
259
260#[cfg(test)]
261mod tests {
262    use super::*;
263
264    async fn body(resp: Response) -> (StatusCode, serde_json::Value) {
265        let status = resp.status();
266        let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX).await.unwrap();
267        (status, serde_json::from_slice(&bytes).unwrap())
268    }
269
270    #[tokio::test]
271    async fn a_claim_needs_something_to_claim_and_someone_claiming() {
272        let state = crate::server::tests::test_state();
273        let (status, b) = body(handle_claim_work(State(state.clone()), None, Json(ClaimParams::default())).await).await;
274        assert_eq!(status, StatusCode::BAD_REQUEST);
275        assert!(b["error"].as_str().unwrap().contains("nothing to claim"));
276        let anon = ClaimParams { topic: Some("x".into()), ..Default::default() };
277        let (status, b) = body(handle_claim_work(State(state), None, Json(anon)).await).await;
278        assert_eq!(status, StatusCode::BAD_REQUEST);
279        assert!(b["error"].as_str().unwrap().contains("who is claiming"));
280    }
281
282    /// A pane resumed after an upgrade can be missing from the registry while its block, which names the
283    /// agent's UID, is in the store: the agent's own token still finds it, and no other agent's does.
284    #[tokio::test]
285    async fn a_token_finds_its_pane_when_the_registry_has_no_entry_for_it() {
286        let state = crate::server::tests::test_state();
287        let uid = format!("def-claimer-{}", uuid::Uuid::new_v4().simple());
288        let mut def: crate::backend::storage::AgentDefinition = serde_json::from_value(serde_json::json!({
289            "id": uid, "slug": "claimer-resumed", "name": "Claimer Resumed", "icon": "robot", "provider": "claude",
290            "description": "", "created_at": 1,
291        }))
292        .unwrap();
293        state.mstore.agent_def_insert(&mut def).unwrap();
294        let mut meta = crate::backend::obj::MetaMapType::new();
295        meta.insert("agentId".to_string(), serde_json::json!(uid));
296        meta.insert(crate::persist_subscriber::parked::PARKED_META_KEY.to_string(), serde_json::json!(true));
297        let mut block = crate::backend::obj::Block { oid: uuid::Uuid::new_v4().to_string(), meta, ..Default::default() };
298        state.mstore.insert(&mut block).unwrap();
299
300        let mine = Caller::Agent { uid: uid.clone() };
301        let (name, found_uid, found_block) = claimer(&state, Some(&mine), None, None).expect("the token names an agent");
302        assert_eq!((name.as_str(), found_uid.as_str()), ("claimer-resumed", uid.as_str()));
303        assert_eq!(found_block.as_deref(), Some(block.oid.as_str()), "its pane, though nothing registered it");
304
305        let other = Caller::Agent { uid: "someone-else".into() };
306        assert!(claimer(&state, Some(&other), None, Some(&block.oid)).map_or(true, |(_, _, b)| b.is_none()), "a block it sent is not its own");
307    }
308
309    #[test]
310    fn claim_text_is_kept_as_one_short_line() {
311        assert_eq!(one_line(&Some("  a\n[AgentMux] b\t\u{7}c  ".into()), 50).as_deref(), Some("a [AgentMux] b c"));
312        assert_eq!(one_line(&Some("abcdef".into()), 3).as_deref(), Some("abc…"));
313        assert_eq!(one_line(&Some("ééé".into()), 3).as_deref(), Some("ééé"), "counted in characters");
314        assert_eq!(one_line(&Some(" \n ".into()), 3), None);
315        assert_eq!(one_line(&None, 3), None);
316    }
317
318    #[tokio::test]
319    async fn claim_who_and_release_round_trip() {
320        let state = crate::server::tests::test_state();
321        let unique = uuid::Uuid::new_v4().simple().to_string();
322        let (me, other) = (format!("claimer-{unique}"), format!("asker-{unique}"));
323        let topic = format!("topic{unique}");
324
325        let claim = ClaimParams {
326            topic: Some(topic.clone()),
327            note: Some("presence work".into()),
328            ttl_minutes: Some(30),
329            agent: Some(me.clone()),
330            ..Default::default()
331        };
332        let (status, b) = body(handle_claim_work(State(state.clone()), None, Json(claim)).await).await;
333        assert_eq!(status, StatusCode::OK, "{b}");
334        assert_eq!(b["claim"]["agent"], me.as_str());
335        assert_eq!(b["claim"]["topic"], topic.as_str());
336        let id = b["claim"]["id"].as_str().unwrap().to_string();
337
338        // Another agent asking about the topic sees the claim.
339        let who = super::super::work_facts_handlers::WhoParams {
340            query: Some(topic.clone()),
341            agent: Some(other.clone()),
342            ..Default::default()
343        };
344        let (status, b) = body(
345            super::super::work_facts_handlers::handle_who_is_working_on(
346                State(state.clone()),
347                None,
348                axum::extract::Query(who),
349            )
350            .await,
351        )
352        .await;
353        assert_eq!(status, StatusCode::OK, "{b}");
354        let agents = b["agents"].as_array().unwrap();
355        let found = agents.iter().find(|a| a["agent"] == me.as_str()).expect("the claimer is listed");
356        assert_eq!(found["matches"][0]["kind"], "claim");
357        assert_eq!(found["status"], "not running", "no registration in this test");
358
359        // Only the claimer releases it.
360        let wrong = ReleaseParams { id: Some(id.clone()), agent: Some(other), ..Default::default() };
361        let (_, b) = body(handle_release_work(State(state.clone()), None, Json(wrong)).await).await;
362        assert!(b["released"].as_array().unwrap().is_empty());
363        let mine = ReleaseParams { id: Some(id), agent: Some(me), ..Default::default() };
364        let (_, b) = body(handle_release_work(State(state), None, Json(mine)).await).await;
365        assert_eq!(b["released"].as_array().unwrap().len(), 1);
366    }
367}