Skip to main content

agentmux_srv_core/backend/
work_claims.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Whose work claims an agent holds, and giving them back. The agent teardown (`sagas/agent_teardown.rs`) and
5//! the controller watchdog both release an agent's claims, so the rule and the release live here in the core;
6//! `server::agent_resources` and the teardown re-export them under their old paths.
7
8use crate::backend::storage::work_queue::{work_state, WorkItem};
9
10/// Same holder rule as the store's release (`HOLDER_BY_UID`): by UID when
11/// both sides have one, else by name.
12pub fn holds_claim(claimed_by: &str, claimed_by_uid: &str, agent_id: &str, uid: Option<&str>) -> bool {
13    match uid.filter(|u| !u.is_empty()) {
14        Some(u) if !claimed_by_uid.is_empty() => claimed_by_uid == u,
15        _ => !agent_id.is_empty() && claimed_by == agent_id,
16    }
17}
18
19/// The agent's claimed work items (R7).
20pub fn claims_held_by<'a>(items: &'a [WorkItem], agent_id: &str, uid: Option<&str>) -> Vec<&'a WorkItem> {
21    items
22        .iter()
23        .filter(|w| w.state == work_state::CLAIMED && holds_claim(&w.claimed_by, &w.claimed_by_uid, agent_id, uid))
24        .collect()
25}
26
27/// Release the agent's claimed work items with `reason` (each counts as an
28/// attempt), so they go back to the pool now rather than when the 120 s lease
29/// expires. How many went. Blocking.
30pub fn release_claims(work_store: &crate::backend::storage::store::Store, a: &str, u: Option<&str>, reason: &str, now: i64) -> usize {
31    let items = work_store.work_queue_claimed_by(a, u.unwrap_or("")).unwrap_or_default();
32    claims_held_by(&items, a, u)
33        .into_iter()
34        .filter(|w| matches!(work_store.work_queue_release(&w.id, &w.claimed_by, &w.claimed_by_uid, w.attempts, reason, now), Ok(Some(_))))
35        .count()
36}