Skip to main content

agentmux_srv/server/
work_queue.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4//! Muxqueue HTTP surface — slice 2 of
5//! `docs/reports/REPORT_UNIVERSAL_AGENT_WORK_QUEUE_2026_09_01.md`.
6//!
7//!   POST   /agentmux/work                 — enqueue
8//!   POST   /agentmux/work/claim           — claim the next eligible item
9//!   POST   /agentmux/work/:id/heartbeat   — extend a lease
10//!   POST   /agentmux/work/:id/complete    — finish
11//!   POST   /agentmux/work/:id/release     — give back
12//!   GET    /agentmux/work                 — list
13//!
14//! The Kanban's additions (cards, history, update/ask/submit, the next task)
15//! are in `work_tasks.rs` (SPEC_WARDEN_KANBAN_2026_10_20.md). An `:id` may be
16//! a task's number (`12`) as well as its id.
17//!
18//! Auth-gated by the same middleware as the cron and reactive routes.
19//!
20//! **Store choice:** every handler uses `state.work_store`. In an installed or
21//! `task package` build that is the always-global identity store, not
22//! `state.shared_store` (cron's place until it moves, `SPEC_IDENTITY_STORE_SPLIT_2026_08_17.md`
23//! step 1b), and deliberately so: a per-channel queue would only ever mean
24//! "any agent in this channel can pick it up". A `task dev` build is the one
25//! exception, with a `work-store.db` of its own (`crate::registry::work_store`),
26//! so a test there never reads or changes the operator's real queue.
27
28use axum::extract::{Path, Query, State};
29use axum::http::StatusCode;
30use axum::response::Json;
31use serde::Deserialize;
32use serde_json::{json, Value};
33use uuid::Uuid;
34
35use crate::backend::storage::work_queue::{ClaimFilter, HolderMatch, WorkItem};
36
37use super::AppState;
38
39/// Default lease granted by a claim, and the window a heartbeat extends by.
40/// Deliberately short relative to a long agent turn: a claimant is expected to
41/// heartbeat, and a crashed one should return to the pool in about a minute
42/// rather than blocking the item for an hour.
43const DEFAULT_LEASE_MS: i64 = 120_000;
44
45use agentmux_common::time::now_ms;
46
47pub(crate) fn publish_changed(state: &AppState) {
48    state.broker.publish_event::<crate::backend::mps_events::WorkQueueChanged>(&(), vec![], 0);
49}
50
51fn err(code: StatusCode, msg: impl Into<String>) -> (StatusCode, Json<Value>) {
52    (code, Json(json!({ "error": msg.into() })))
53}
54
55#[derive(Debug, Deserialize)]
56pub(super) struct EnqueueRequest {
57    pub title: String,
58    pub payload: String,
59    #[serde(default)]
60    pub kind: String,
61    #[serde(default)]
62    pub target_agent: String,
63    /// Identity M3: the target's UID, resolved at the MCP boundary (spec
64    /// §5) and CARRIED here. When present it is stored as-is; when absent
65    /// the server resolves `target_agent` itself as a counted fallback.
66    #[serde(default)]
67    pub target_agent_uid: String,
68    #[serde(default)]
69    pub target_group: String,
70    #[serde(default)]
71    pub priority: i64,
72    #[serde(default)]
73    pub created_by: String,
74    #[serde(default)]
75    pub max_attempts: Option<i64>,
76    /// ms epoch. Not claimable before this.
77    #[serde(default)]
78    pub not_before: Option<i64>,
79    /// Kanban: the repository it belongs to; default the enqueuer's own.
80    #[serde(default)]
81    pub repo: Option<String>,
82    /// Kanban: on hold until the operator releases it.
83    #[serde(default)]
84    pub hold: bool,
85    /// Kanban: whether a person must accept it; default from who asked.
86    #[serde(default)]
87    pub review: Option<bool>,
88    /// Kanban: the tasks it starts after (ids or numbers).
89    #[serde(default)]
90    pub after: Vec<Value>,
91    /// Kanban: `"spec"` or `"research"` files that task and a build that
92    /// starts after it, for the same agent
93    /// (SPEC_KANBAN_STAGES_COLOURS_AND_NARROW_VIEW_2026_10_23.md §5.1).
94    #[serde(default)]
95    pub first: Option<String>,
96    /// Kanban: the task changes the UI, so it needs media to be handed in for review
97    /// (SPEC_KANBAN_TASK_MEDIA_2026_10_25.md §5).
98    #[serde(default)]
99    pub ui_change: Option<bool>,
100    /// Which board to file it on, by name or slug; the default board when absent.
101    #[serde(default)]
102    pub board: Option<String>,
103}
104
105/// Who files a task: a caller on this machine (its token says who it is and what it was asked), or an
106/// agent of another machine, named `slug@machine`, whose request the transport has verified.
107pub(super) enum Filer<'a> {
108    Local(Option<&'a super::caller::Caller>),
109    Remote(&'a str),
110}
111
112pub(super) async fn handle_work_enqueue(
113    State(state): State<AppState>,
114    caller: Option<axum::Extension<super::caller::Caller>>,
115    Json(req): Json<EnqueueRequest>,
116) -> (StatusCode, Json<Value>) {
117    super::actor::check_actor(
118        &state,
119        caller.as_deref(),
120        super::actor::ActorSite::WorkEnqueue,
121        Some(&req.created_by),
122    );
123    enqueue_core(&state, req, Filer::Local(caller.as_deref())).await
124}
125
126/// File a task (or a spec and its build). The one path for a local call and a remote operation, so a
127/// task filed from another machine is numbered, carded and noted exactly like a local one.
128pub(super) async fn enqueue_core(state: &AppState, req: EnqueueRequest, filer: Filer<'_>) -> (StatusCode, Json<Value>) {
129    let state = state.clone();
130    let (caller, remote) = match filer {
131        Filer::Local(c) => (c, None),
132        Filer::Remote(actor) => (None, Some(actor.to_string())),
133    };
134    if req.title.trim().is_empty() {
135        return err(StatusCode::BAD_REQUEST, "title is required");
136    }
137    if let Some(why) = crate::server::work_tasks::payload_problem(&req.payload) {
138        return err(StatusCode::BAD_REQUEST, why);
139    }
140    // An item targeted at both a specific agent AND a group is ambiguous —
141    // reject rather than silently letting one win, which would look like the
142    // queue quietly ignored half the caller's intent.
143    if !req.target_agent.is_empty() && !req.target_group.is_empty() {
144        return err(
145            StatusCode::BAD_REQUEST,
146            "specify target_agent or target_group, not both",
147        );
148    }
149
150    // Identity M3: the target's UID is stored only if the caller CARRIED
151    // one — resolved at the boundary where the name was typed (the MCP, via
152    // `POST /agentmux/agents/resolve`, spec §5). This handler never turns a
153    // name into an identity itself (§2 rule 1): since M3 the UID decides who
154    // may claim the item, and a server-side guess — the host-wide slug
155    // registry, a template id — would bind it to whichever agent the guess
156    // found, in any channel (review on #3563). A named target with no
157    // carried UID keeps the name path until M5, counted (§9.2).
158    let target_agent_uid = req.target_agent_uid.trim().to_string();
159    if target_agent_uid.is_empty() && !req.target_agent.trim().is_empty() {
160        crate::backend::agent_resolve::record_uid_fallback("work_enqueue.uid_not_carried");
161    }
162
163    let board = match filing_board(&state, &req, &target_agent_uid, (&remote, caller)) {
164        Ok(b) => b,
165        Err(why) => return err(StatusCode::BAD_REQUEST, why),
166    };
167
168    let now = now_ms();
169    let ui_change = req.ui_change;
170    // Who to tell the filer about if the target can't work now: looked up by the UID it was carried with,
171    // else by its name, and named in the note as the filer typed it.
172    let target = (if target_agent_uid.is_empty() { req.target_agent.clone() } else { target_agent_uid.clone() }, req.target_agent.clone());
173    let item = WorkItem {
174        id: Uuid::new_v4().to_string(),
175        title: req.title,
176        payload: req.payload,
177        kind: req.kind,
178        target_agent: req.target_agent,
179        target_group: req.target_group,
180        priority: req.priority,
181        // Set by the store: `open`, or `held` when filed on hold (never
182        // claimable, not even between the enqueue and a later hold).
183        state: if req.hold { crate::backend::storage::work_queue::work_state::HELD.into() } else { String::new() },
184        claimed_by: String::new(),
185        target_agent_uid,
186        claimed_by_uid: String::new(),
187        claim_expires: None,
188        attempts: 0,
189        max_attempts: req.max_attempts.unwrap_or(3),
190        created_by: req.created_by,
191        // Identity M4c-1 (§6.5.9): the enqueuer's UID is the request's
192        // `Caller` — its token — never a body field; `""` when Unattributed
193        // (and for an agent of another machine, which has no UID here).
194        created_by_uid: super::caller::attributed_uid(caller),
195        created_at: now,
196        updated_at: now,
197        not_before: req.not_before,
198        result: String::new(),
199    };
200
201    let after = match super::work_tasks::resolve_after(&state, &req.after) {
202        Ok(a) => a,
203        Err(why) => return err(StatusCode::BAD_REQUEST, why),
204    };
205    if let Err(why) = after_on_board(&state, &after, &board) {
206        return err(StatusCode::BAD_REQUEST, why);
207    }
208    let first = match req.first.as_deref().map(str::trim).filter(|f| !f.is_empty()) {
209        Some(f) if crate::backend::kanban::is_research_kind(f) => Some(f.to_ascii_lowercase()),
210        Some(_) => return err(StatusCode::BAD_REQUEST, "first: \"spec\" or \"research\""),
211        None => None,
212    };
213    let filing = super::work_tasks::Filing { board: board.id.clone(), repo: req.repo, review: review_for(req.review, first.is_some()) };
214    let card = match &remote {
215        Some(actor) => super::work_tasks::remote_card(actor, filing),
216        None => super::work_tasks::prepare_card(&state, caller, &item.created_by, filing).await,
217    };
218    let Some(first) = first else {
219        return match enqueue_one(&state, &item, &after, &card) {
220            Ok(num) => {
221                let _ = state.work_store.work_ui_set(&item.id, ui_change, None, 0, now);
222                publish_changed(&state);
223                let note = super::availability_view::enqueue_note(&state, &target.0, &target.1).await;
224                let body = json!({ "id": item.id, "num": num, "ref": num.map(|n| board.task_ref(n)), "board": board.slug });
225                (StatusCode::OK, Json(super::availability_view::with_note(body, note)))
226            }
227            Err(e) => e,
228        };
229    };
230    file_pair(&state, item, first, &after, &card, (&board, ui_change, now), &target).await
231}
232
233/// Which board a filing goes to, if its filer sees it and the target agent is on its list. An agent
234/// of another machine (`slug@machine`) is matched against the board's agent list by that name.
235fn filing_board(
236    state: &AppState,
237    req: &EnqueueRequest,
238    target_agent_uid: &str,
239    (remote, caller): (&Option<String>, Option<&super::caller::Caller>),
240) -> Result<crate::backend::storage::work_boards::Board, String> {
241    let who: Option<(String, String)> = match (remote, caller) {
242        (Some(actor), _) => Some((actor.clone(), String::new())),
243        (None, c) => super::work_tasks::viewer(state, c),
244    };
245    let who_ref = who.as_ref().map(|(a, u)| (a.as_str(), u.as_str()));
246    let board = super::work_tasks::pick_board(state, req.board.as_deref(), who_ref, true)?;
247    if (!req.target_agent.trim().is_empty() || !target_agent_uid.is_empty()) && !board.visible_to(req.target_agent.trim(), target_agent_uid) {
248        return Err(format!("{} isn't on the agent list of board {}; add it there, or file on another board", req.target_agent.trim(), board.slug));
249    }
250    Ok(board)
251}
252
253/// Dependencies stay inside one board.
254fn after_on_board(state: &AppState, after: &[String], board: &crate::backend::storage::work_boards::Board) -> Result<(), String> {
255    for a in after {
256        if let Ok(Some((other, n))) = state.work_store.work_task_board(a) {
257            if other.id != board.id {
258                return Err(format!(
259                    "after: {} is on board {}; a task can only start after tasks on its own board ({})",
260                    other.task_ref(n),
261                    other.slug,
262                    board.slug
263                ));
264            }
265        }
266    }
267    Ok(())
268}
269
270/// A feature as two tasks: its spec (or research), and a build that starts after it, for the same
271/// agent, filed and numbered together.
272async fn file_pair(
273    state: &AppState,
274    item: WorkItem,
275    first: String,
276    after: &[String],
277    card: &crate::backend::storage::work_board::NewCard,
278    (board, ui_change, now): (&crate::backend::storage::work_boards::Board, Option<bool>, i64),
279    target: &(String, String),
280) -> (StatusCode, Json<Value>) {
281    use crate::backend::kanban::{build_payload, pair_title, spec_payload};
282    let spec = WorkItem {
283        title: pair_title(&first, &item.title),
284        payload: spec_payload(&first, &item.payload),
285        kind: first.clone(),
286        ..item.clone()
287    };
288    let build = WorkItem {
289        id: Uuid::new_v4().to_string(),
290        title: pair_title("build", &item.title),
291        payload: build_payload(&item.payload),
292        kind: "build".into(),
293        ..item
294    };
295    let spec_num = match enqueue_one(state, &spec, after, card) {
296        Ok(n) => n,
297        Err(e) => return e,
298    };
299    let build_num = match enqueue_one(state, &build, std::slice::from_ref(&spec.id), card) {
300        Ok(n) => {
301            // The flag is the build's: the spec is a document.
302            let _ = state.work_store.work_ui_set(&build.id, ui_change, None, 0, now);
303            n
304        }
305        Err(e) => {
306            publish_changed(state);
307            return e;
308        }
309    };
310    publish_changed(state);
311    let note = super::availability_view::enqueue_note(state, &target.0, &target.1).await;
312    let body = json!({
313        "id": spec.id, "num": spec_num, "ref": spec_num.map(|n| board.task_ref(n)),
314        "build_id": build.id, "build_num": build_num, "build_ref": build_num.map(|n| board.task_ref(n)),
315        "board": board.slug,
316    });
317    (StatusCode::OK, Json(super::availability_view::with_note(body, note)))
318}
319
320/// The answer to a claim: the attempt (the fence), the card's number and the
321/// item, and `after`, the tasks it starts after with their documents. A build
322/// claimed by an agent no unlock note reached (it was filed for anyone) finds
323/// its spec's path here.
324fn claimed_body(state: &AppState, item: &WorkItem, num: Option<i64>) -> Value {
325    let after = state.work_store.work_deps_of(&item.id).unwrap_or_default();
326    let (task_ref, board) = super::work_tasks::ref_of(state, &item.id).unzip();
327    let mut body = json!({
328        "claimed": true, "attempt": item.attempts, "num": num, "ref": task_ref, "board": board, "item": item, "after": after,
329        "status": "Your status line now shows this task's title. Say what you are doing in your own words with \
330                   Presence status (line), and again when your plan changes, when you are blocked or waiting, \
331                   and when you are done.",
332    });
333    if item.target_agent.is_empty() && item.target_agent_uid.is_empty() && item.target_group.is_empty() {
334        body["unaimed"] = json!(
335            "This task was not aimed at you. If it is outside your area, hand it back with Tasks release (id, attempt, \
336             handback: true, reason): it returns to the pool without using an attempt, and an unnamed claim will not \
337             offer it to you again."
338        );
339    }
340    body
341}
342
343/// The answer to a claim that took: the body above, after the claim's title is written to the agent's
344/// status line.
345fn claimed_reply(state: &AppState, item: &WorkItem, num: Option<i64>, block_id: &str, holder: (&str, &str)) -> (StatusCode, Json<Value>) {
346    super::agent_status_handlers::task_claimed(state, block_id, holder, &item.id, num, &item.title);
347    (StatusCode::OK, Json(claimed_body(state, item, num)))
348}
349
350/// Whether a filing is held for the operator's Accept: what the filer said, else
351/// (a spec-and-build pair) no, as in the operator's "Spec first". Left to the
352/// provenance default, a spec an operator asked for would wait for an Accept
353/// that never comes, and its build could not start.
354fn review_for(asked: Option<bool>, pair: bool) -> Option<bool> {
355    asked.or(pair.then_some(false))
356}
357
358/// Enqueue one task with what it starts after (the row and the list in one
359/// transaction, so no claim takes it in between) and file its card.
360fn enqueue_one(
361    state: &AppState,
362    item: &WorkItem,
363    after: &[String],
364    card: &crate::backend::storage::work_board::NewCard,
365) -> Result<Option<i64>, (StatusCode, Json<Value>)> {
366    let enqueued = if after.is_empty() {
367        state.work_store.work_queue_enqueue(item).map(|()| None)
368    } else {
369        state.work_store.work_queue_enqueue_after(item, after)
370    };
371    match enqueued {
372        Ok(Some(why)) => Err(err(StatusCode::BAD_REQUEST, format!("after: {why}"))),
373        Ok(None) => Ok(super::work_tasks::file_card(state, item, card)),
374        Err(e) => Err(err(StatusCode::INTERNAL_SERVER_ERROR, format!("enqueue failed: {e}"))),
375    }
376}
377
378#[derive(Debug, Deserialize)]
379pub(super) struct ClaimRequest {
380    /// The claiming agent's id.
381    pub agent_id: String,
382    /// The claiming agent's UID, carried from its own `AGENTMUX_AGENT_UID`
383    /// (identity M1a). Optional: a pre-M1a spawn, a continuation resume, an
384    /// App Server agent or a quick-launch pane has none. Since M3 it decides
385    /// eligibility for UID-addressed items, and is written to
386    /// `claimed_by_uid` — since M4c-1 only when the claim is Unattributed;
387    /// an attributed claim uses its token's UID instead. It is an assertion
388    /// like `agent_id` is — recorded, not trusted.
389    #[serde(default)]
390    pub agent_uid: String,
391    /// The claimer's block, carried from its `AGENTMUX_BLOCKID`. When no UID
392    /// was carried, the UID is taken from the row shown on this block — the
393    /// identity the block already has, never one derived from `agent_id`.
394    #[serde(default)]
395    pub block_id: String,
396    #[serde(default)]
397    pub kind: Option<String>,
398    /// Group ids this agent belongs to. Resolved by the CALLER — group
399    /// membership lives in the per-channel store, which the queue module
400    /// deliberately does not reach into.
401    #[serde(default)]
402    pub groups: Vec<String>,
403    #[serde(default)]
404    pub lease_ms: Option<i64>,
405    /// Claim this task (its number or id) and no other: open, or held, which
406    /// lifts the hold (SPEC_KANBAN_AGENTS_HOLD_AND_UNHOLD_2026_10_22.md §3.3).
407    #[serde(default)]
408    pub id: Option<String>,
409    /// Claim only on this board (name or slug); without it, on any board the claimer sees, the
410    /// default board first on a tie. `"all"` is the same as leaving it out.
411    #[serde(default)]
412    pub board: Option<String>,
413}
414
415/// An Unattributed claimer's UID: carried, else its block's row, else `""`
416/// (name path only). An attributed claim uses its `Caller`'s UID instead —
417/// see `handle_work_claim`.
418async fn claimer_uid(state: &AppState, req: &ClaimRequest) -> String {
419    let carried = req.agent_uid.trim();
420    if !carried.is_empty() {
421        return carried.to_string();
422    }
423    crate::backend::agent_resolve::record_uid_fallback("work_claim.uid_not_carried");
424    let block_id = req.block_id.trim().to_string();
425    if block_id.is_empty() {
426        return String::new();
427    }
428    // A synchronous store read, so off the async worker (incident #1782).
429    let mstore = state.mstore.clone();
430    tokio::task::spawn_blocking(move || {
431        crate::backend::agent_resolve::uid_for_block(&mstore, &block_id)
432    })
433    .await
434    .ok()
435    .flatten()
436    .unwrap_or_default()
437}
438
439pub(super) async fn handle_work_claim(
440    State(state): State<AppState>,
441    caller: Option<axum::Extension<super::caller::Caller>>,
442    Json(req): Json<ClaimRequest>,
443) -> (StatusCode, Json<Value>) {
444    super::actor::check_actor(
445        &state,
446        caller.as_deref(),
447        super::actor::ActorSite::WorkClaim,
448        Some(&req.agent_id),
449    );
450    super::actor::check_carried_uid(caller.as_deref(), &req.agent_uid);
451    if req.agent_id.trim().is_empty() {
452        return err(StatusCode::BAD_REQUEST, "agent_id is required");
453    }
454    let now = now_ms();
455
456    // Reap BEFORE claiming, so an expired lease is recovered by the very next
457    // agent that asks for work. This is why there is no background reaper
458    // task: the only moment a stale claim actually matters is when someone
459    // wants the item, and reaping here makes that self-healing. The predicate
460    // is indexed (idx_ids_work_queue_claim_expires) and no-ops when nothing
461    // has expired.
462    // A holder srv knows is alive keeps its lease whether or not it calls
463    // heartbeat (Kanban §6.8); what still expires is recorded as such.
464    super::work_tasks::extend_live_leases(&state, now);
465    let expiring = super::work_tasks::expiring(&state, now);
466    if let Err(e) = state.work_store.work_queue_reap(now) {
467        // Not fatal — a claim against a not-yet-reaped queue is still correct,
468        // just possibly emptier than it could be. Log and continue rather than
469        // failing the caller's request.
470        tracing::warn!(target: "workqueue", error = %e, "reap before claim failed");
471    }
472    for gone in expiring {
473        let to = state.work_store.work_queue_get(&gone.id).ok().flatten().map(|i| i.state).unwrap_or_default();
474        if to != crate::backend::storage::work_queue::work_state::CLAIMED {
475            super::work_tasks::record(&state, &gone.id, &gone.claimed_by, "system", "expired", "claimed", &to, "lease expired");
476        }
477    }
478
479    // Identity M4c-1 (§6.5.9): an attributed claim's UID is the request's
480    // `Caller` — its token. Only an Unattributed claim falls back to M3's
481    // path: the UID it CARRIED, else the UID of the row on its own block
482    // (the presence path's resolution, §0.1) — never one derived from its
483    // name (§2 rule 1). Deriving it from the name reached the host-wide slug
484    // registry, so a claimer with no UID in its env could be locked out of
485    // its own UID-addressed work, or handed another channel's (review on
486    // #3563). Each fallback is counted (§9.2): a non-zero count names a
487    // launch path that does not carry its UID. This one UID is both the
488    // `claimed_by_uid` written and the M3 eligibility match
489    // (`target_agent_uid = ?5`) — the one reader change M4c-1 makes; the
490    // carried UID and the token are set together from one row, and a
491    // disagreement is counted just above (`check_carried_uid`).
492    let agent_uid = match caller.as_deref().and_then(super::caller::Caller::uid) {
493        Some(uid) => uid.to_string(),
494        None => claimer_uid(&state, &req).await,
495    };
496
497    let filter = ClaimFilter {
498        kind: req.kind.filter(|k| !k.is_empty()),
499        agent_id: req.agent_id.clone(),
500        agent_uid,
501        groups: req.groups.clone(),
502    };
503    let lease = req.lease_ms.filter(|&n| n > 0).unwrap_or(DEFAULT_LEASE_MS);
504
505    let on_board = match req.board.as_deref().map(str::trim).filter(|b| !b.is_empty() && !b.eq_ignore_ascii_case("all")) {
506        Some(key) => match super::work_tasks::pick_board(&state, Some(key), Some((req.agent_id.as_str(), filter.agent_uid.as_str())), false) {
507            Ok(b) => Some(b),
508            Err(why) => return err(StatusCode::BAD_REQUEST, why),
509        },
510        None => None,
511    };
512
513    if let Some(named) = req.id.as_deref().map(str::trim).filter(|s| !s.is_empty()) {
514        // With a board named, a bare number is that board's.
515        let named = match &on_board {
516            Some(b) if named.trim_start_matches('#').chars().all(|c| c.is_ascii_digit()) => format!("{}#{}", b.slug, named.trim_start_matches('#')),
517            _ => named.to_string(),
518        };
519        let id = super::work_tasks::resolve_id(&state, &named);
520        if let Some(why) = unclaimable_board(&state, &id, &named, &filter) {
521            return (StatusCode::OK, Json(json!({ "claimed": false, "why": why })));
522        }
523        return match state.work_store.work_claim_one(&id, &filter, now, lease) {
524            Ok(Some((item, from))) => {
525                let num = state.work_store.work_card_ensure(&item.id, now).ok();
526                if from == crate::backend::storage::work_queue::work_state::HELD {
527                    super::work_tasks::record(&state, &item.id, &item.claimed_by, "agent", "unheld", "held", "open", "claimed by name");
528                }
529                super::work_tasks::record(&state, &item.id, &item.claimed_by, "agent", "claimed", "open", "claimed", "");
530                publish_changed(&state);
531                claimed_reply(&state, &item, num, &req.block_id, (&req.agent_id, holder_uid(caller.as_deref())))
532            }
533            Ok(None) => {
534                let why = super::work_tasks::why_not_claimed(&state, &id, &filter, now);
535                (StatusCode::OK, Json(json!({ "claimed": false, "why": why })))
536            }
537            Err(e) => err(StatusCode::INTERNAL_SERVER_ERROR, format!("claim failed: {e}")),
538        };
539    }
540
541    let floor = crate::backend::quota_mode::claim_floor(&state.config_watcher.get_full_config().settings.extra);
542    match state.work_store.work_queue_claim_in(&filter, on_board.as_ref().map(|b| b.id.as_str()), now, lease, floor) {
543        Ok(Some(item)) => {
544            let num = state.work_store.work_card_ensure(&item.id, now).ok();
545            super::work_tasks::record(&state, &item.id, &item.claimed_by, "agent", "claimed", "open", "claimed", "");
546            publish_changed(&state);
547            // `attempt` is echoed at the top level as well as inside `item`
548            // because every subsequent call (heartbeat/complete/release) MUST
549            // pass it back as a fence — see work_queue.rs's ABA note. Making
550            // it prominent here is the difference between a caller that
551            // fences correctly and one that discovers the requirement from a
552            // 404-shaped "not the holder" response.
553            claimed_reply(&state, &item, num, &req.block_id, (&req.agent_id, holder_uid(caller.as_deref())))
554        }
555        Ok(None) => nothing_to_claim(&state, &filter, now, floor),
556        Err(e) => err(StatusCode::INTERNAL_SERVER_ERROR, format!("claim failed: {e}")),
557    }
558}
559
560/// Why a named task can't be claimed because of its board: one the claimer doesn't see is as good
561/// as unknown, and an archived board's tasks are read-only.
562fn unclaimable_board(state: &AppState, id: &str, named: &str, filter: &ClaimFilter) -> Option<String> {
563    let Ok(Some((b, _))) = state.work_store.work_task_board(id) else { return None };
564    if !b.visible_to(&filter.agent_id, &filter.agent_uid) {
565        return Some(format!("there is no task {named}"));
566    }
567    b.archived.then(|| format!("board {} is archived: its tasks can't be claimed", b.slug))
568}
569
570/// The answer when an unnamed claim finds nothing. Only when the quota floor is what stood in the
571/// way does it say so.
572fn nothing_to_claim(state: &AppState, filter: &ClaimFilter, now: i64, floor: Option<i64>) -> (StatusCode, Json<Value>) {
573    let held = floor.and_then(|n| state.work_store.work_queue_held_by_floor(filter, now, n).ok().filter(|&h| h > 0).map(|h| (n, h)));
574    match held {
575        Some((n, held)) => (
576            StatusCode::OK,
577            Json(json!({
578                "claimed": false,
579                "held_back_by_quota_mode": held,
580                "reason": format!(
581                    "quota mode: {held} open task(s) held back; an unnamed claim takes only tasks aimed at you and ones with priority {n} or more. Claim a named one with its id if you were told to"
582                ),
583            })),
584        ),
585        None => (StatusCode::OK, Json(json!({ "claimed": false }))),
586    }
587}
588
589#[derive(Debug, Deserialize)]
590pub(super) struct HolderRequest {
591    pub agent_id: String,
592    /// Fence token — the `attempt` returned by the claim this call belongs to.
593    pub attempt: i64,
594    #[serde(default)]
595    pub result: String,
596    #[serde(default)]
597    pub lease_ms: Option<i64>,
598    /// release: the task is outside the holder's area. It goes back to the pool with its attempt
599    /// given back (never parked as failed) and is not offered to this agent by an unnamed claim again.
600    #[serde(default)]
601    pub handback: bool,
602}
603
604/// The caller's UID for a holder check (identity M4c-2, spec §6.5.9): the
605/// token's, or `""` when Unattributed — the store then matches by name.
606fn holder_uid(caller: Option<&super::caller::Caller>) -> &str {
607    caller.and_then(super::caller::Caller::uid).unwrap_or("")
608}
609
610/// Count a holder check that matched by name — the row or the caller had no
611/// UID. Each is a holder that M5, which drops the name path, would refuse.
612fn count_holder_match(matched: Option<HolderMatch>) {
613    if matched == Some(HolderMatch::Name) {
614        crate::backend::agent_resolve::record_uid_fallback("m4c.holder_by_name");
615    }
616}
617
618/// Shared shape for the three holder-only transitions. No match from the
619/// store means the caller is not the current holder OR its fence is stale — both are
620/// CONFLICT, not NOT_FOUND: the row usually still exists, it just moved on
621/// without this caller.
622fn holder_result(ok: bool, state: &AppState) -> (StatusCode, Json<Value>) {
623    if ok {
624        publish_changed(state);
625        (StatusCode::OK, Json(json!({ "ok": true })))
626    } else {
627        (
628            StatusCode::CONFLICT,
629            Json(json!({
630                "ok": false,
631                "error": "not the current holder, or this claim has been superseded \
632                          (expired and reclaimed) — re-claim before continuing"
633            })),
634        )
635    }
636}
637
638pub(super) async fn handle_work_heartbeat(
639    State(state): State<AppState>,
640    Path(id): Path<String>,
641    caller: Option<axum::Extension<super::caller::Caller>>,
642    Json(req): Json<HolderRequest>,
643) -> (StatusCode, Json<Value>) {
644    super::actor::check_actor(
645        &state,
646        caller.as_deref(),
647        super::actor::ActorSite::WorkHeartbeat,
648        Some(&req.agent_id),
649    );
650    let id = super::work_tasks::resolve_id(&state, &id);
651    let lease = req.lease_ms.filter(|&n| n > 0).unwrap_or(DEFAULT_LEASE_MS);
652    match state
653        .work_store
654        .work_queue_heartbeat(&id, &req.agent_id, holder_uid(caller.as_deref()), req.attempt, now_ms(), lease)
655    {
656        Ok(matched) => {
657            count_holder_match(matched);
658            holder_result(matched.is_some(), &state)
659        }
660        Err(e) => err(StatusCode::INTERNAL_SERVER_ERROR, format!("heartbeat failed: {e}")),
661    }
662}
663
664pub(super) async fn handle_work_complete(
665    State(state): State<AppState>,
666    Path(id): Path<String>,
667    caller: Option<axum::Extension<super::caller::Caller>>,
668    Json(req): Json<HolderRequest>,
669) -> (StatusCode, Json<Value>) {
670    super::actor::check_actor(
671        &state,
672        caller.as_deref(),
673        super::actor::ActorSite::WorkComplete,
674        Some(&req.agent_id),
675    );
676    let id = super::work_tasks::resolve_id(&state, &id);
677    // A task that needs review goes to Review instead of done (the agent
678    // can't accept its own work); either way the answer names the agent's
679    // next waiting task (Kanban §6.5).
680    let done = super::work_tasks::finish(&state, caller.as_deref(), &id, &req.agent_id, req.attempt, &req.result, None).await;
681    if done.0.is_success() {
682        // The agent's build caches are cleared in the background (SPEC_BUILD_CACHE_CLEANUP_2026_10_26.md).
683        crate::backend::build_cache_service::agent_task_done(state.mstore.clone(), state.config_watcher.clone(), req.agent_id.clone());
684    }
685    done
686}
687
688/// Returns the item's RESULTING state alongside `ok` (Codex P2 on PR #2902).
689/// A release on the item's final allowed attempt parks it as `failed` rather
690/// than reopening it, so a bare `{ok:true}` would let the caller report "handed
691/// back to the queue" for an item nobody can ever claim again.
692pub(super) async fn handle_work_release(
693    State(state): State<AppState>,
694    Path(id): Path<String>,
695    caller: Option<axum::Extension<super::caller::Caller>>,
696    Json(req): Json<HolderRequest>,
697) -> (StatusCode, Json<Value>) {
698    super::actor::check_actor(
699        &state,
700        caller.as_deref(),
701        super::actor::ActorSite::WorkRelease,
702        Some(&req.agent_id),
703    );
704    let id = super::work_tasks::resolve_id(&state, &id);
705    let released = if req.handback {
706        state.work_store.work_queue_hand_back(&id, &req.agent_id, holder_uid(caller.as_deref()), req.attempt, &req.result, now_ms())
707    } else {
708        state.work_store.work_queue_release(&id, &req.agent_id, holder_uid(caller.as_deref()), req.attempt, &req.result, now_ms())
709    };
710    match released {
711        Ok(Some(matched)) => {
712            count_holder_match(Some(matched));
713            publish_changed(&state);
714            super::task_flow_notes::note(&state, &id, crate::backend::task_flow::TaskFlowKind::HandedBack, &req.agent_id, "");
715            // Read back rather than infer: the store owns the
716            // attempts-vs-max_attempts decision, and duplicating that rule
717            // here is exactly how the two drift.
718            let resulting = state
719                .work_store
720                .work_queue_get(&id)
721                .ok()
722                .flatten()
723                .map(|i| i.state)
724                .unwrap_or_default();
725            // A hand-back's history line was written with the hand-back itself.
726            if !req.handback {
727                super::work_tasks::record(&state, &id, &req.agent_id, "agent", "released", "claimed", &resulting, &req.result);
728            }
729            super::agent_status_handlers::task_ended(&state, &req.agent_id, holder_uid(caller.as_deref()), &id);
730            (StatusCode::OK, Json(json!({ "ok": true, "state": resulting })))
731        }
732        Ok(None) => holder_result(false, &state),
733        Err(e) => err(StatusCode::INTERNAL_SERVER_ERROR, format!("release failed: {e}")),
734    }
735}
736
737#[derive(Debug, Deserialize)]
738pub(super) struct ListQuery {
739    #[serde(default)]
740    pub state: String,
741    #[serde(default)]
742    pub limit: Option<usize>,
743    /// A board by name or slug; `all` for every board the caller sees; the default board when absent.
744    #[serde(default)]
745    pub board: Option<String>,
746}
747
748pub(super) async fn handle_work_list(
749    State(state): State<AppState>,
750    caller: Option<axum::Extension<super::caller::Caller>>,
751    Query(q): Query<ListQuery>,
752) -> (StatusCode, Json<Value>) {
753    let who = super::work_tasks::viewer(&state, caller.as_deref());
754    let who = who.as_ref().map(|(a, u)| (a.as_str(), u.as_str()));
755    match list_view(&state, &q.state, q.limit, q.board.as_deref(), who) {
756        Ok(view) => (StatusCode::OK, Json(view)),
757        Err(e) => err(StatusCode::BAD_REQUEST, e),
758    }
759}
760
761/// The board's tasks in `state` (all when empty), newest first as the store gives them, each with its
762/// number and ref, which agents and the operator use. Without `board`, the default board's; `all` lists
763/// every board the caller sees. `who` is the caller's id and UID, whose agent lists decide the boards it
764/// sees (none: all of them). The answer carries a line when more waits for the caller on other boards.
765pub(super) fn list_view(
766    state: &AppState,
767    filter: &str,
768    limit: Option<usize>,
769    board: Option<&str>,
770    who: Option<(&str, &str)>,
771) -> Result<Value, String> {
772    let limit = limit.unwrap_or(50).clamp(1, 500);
773    let now = now_ms();
774    let key = board.map(str::trim).filter(|b| !b.is_empty());
775    let all = key.is_some_and(|k| k.eq_ignore_ascii_case("all"));
776    let (ids, scope, scope_id) = if all {
777        let boards = state.work_store.work_boards_list(true, now).map_err(|e| format!("list failed: {e}"))?;
778        let ids: Vec<String> = boards.into_iter().filter(|b| who.map_or(true, |(a, u)| b.visible_to(a, u))).map(|b| b.id).collect();
779        (ids, "all".to_string(), String::new())
780    } else {
781        let b = super::work_tasks::pick_board(state, key, who, false)?;
782        (vec![b.id.clone()], b.slug.clone(), b.id)
783    };
784    let items = state.work_store.work_queue_list_on(filter, limit, &ids, now).map_err(|e| format!("list failed: {e}"))?;
785    let items: Vec<Value> = items
786        .into_iter()
787        .map(|i| {
788            let num = state.work_store.work_card_ensure(&i.id, now).ok();
789            let (task_ref, board) = super::work_tasks::ref_of(state, &i.id).unzip();
790            let mut v = serde_json::to_value(&i).unwrap_or_default();
791            if let Some(o) = v.as_object_mut() {
792                o.insert("num".into(), json!(num));
793                o.insert("ref".into(), json!(task_ref));
794                o.insert("board".into(), json!(board));
795            }
796            v
797        })
798        .collect();
799    let mut view = json!({ "items": items, "board": scope });
800    if let (false, Some((agent, uid))) = (all, who) {
801        let elsewhere = state.work_store.work_waiting_elsewhere(&scope_id, agent, uid).unwrap_or_default();
802        let total: i64 = elsewhere.iter().map(|(_, n)| n).sum();
803        if total > 0 {
804            let names: Vec<&str> = elsewhere.iter().map(|(name, _)| name.as_str()).collect();
805            view["note"] = json!(format!("{total} more for you on {} (list with board: \"all\", or name one)", names.join(" and ")));
806        }
807    }
808    Ok(view)
809}
810
811/// [`list_view`]'s tasks alone, for the remote `tasks.list`.
812pub(super) fn list_items(
813    state: &AppState,
814    filter: &str,
815    limit: Option<usize>,
816    board: Option<&str>,
817    who: Option<(&str, &str)>,
818) -> Result<Vec<Value>, String> {
819    let view = list_view(state, filter, limit, board, who)?;
820    Ok(view["items"].as_array().cloned().unwrap_or_default())
821}
822
823#[cfg(test)]
824mod review_for_tests {
825    use super::review_for;
826
827    #[test]
828    fn a_pair_defaults_to_no_accept_unless_asked() {
829        assert_eq!(review_for(None, true), Some(false));
830        assert_eq!(review_for(Some(true), true), Some(true), "asked for stands");
831        assert_eq!(review_for(None, false), None, "a single task keeps the provenance default");
832        assert_eq!(review_for(Some(false), false), Some(false));
833    }
834}