Skip to main content

agentmux_srv/server/
work_tasks.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4//! The agents' side of the Kanban (docs/specs/SPEC_WARDEN_KANBAN_2026_10_20.md
5//! §6.5, §6.8, §6.12), beside the queue's own routes in `work_queue.rs`:
6//!
7//!   POST /agentmux/work/:id/update   — a progress note, a checklist, links
8//!   POST /agentmux/work/:id/ask      — a question for the operator (blocked)
9//!   POST /agentmux/work/:id/submit   — hand it in (review, or done)
10//!   POST /agentmux/work/:id/hold     — put a waiting task on hold, or pause
11//!                                      one's own (any agent)
12//!   POST /agentmux/work/:id/unhold   — take a held task off hold (any agent)
13//!
14//! And what srv adds to every task an agent touches: its card (number,
15//! repository, who asked), its history, the next task waiting for the agent
16//! when it finishes one, and leases that a live holder keeps without calling
17//! `heartbeat`.
18
19use axum::extract::{Path, State};
20use axum::http::StatusCode;
21use axum::response::Json;
22use serde::Deserialize;
23use serde_json::{json, Value};
24
25use agentmux_common::time::now_ms;
26
27use crate::backend::kanban::prs::{link_if_from, pr_in_text};
28use crate::backend::reactive::types::AgentRegistration;
29use crate::backend::storage::work_board::{requested, BoardTask, CardUpdate, ChecklistItem, NewCard, WorkEvent};
30use crate::backend::storage::work_queue::{work_state, ClaimFilter, WorkItem};
31
32use super::caller::Caller;
33use super::AppState;
34
35/// The lease a live holder's claim is kept at (`work_queue::DEFAULT_LEASE_MS`).
36const LEASE_MS: i64 = 120_000;
37/// The longest note, question or result kept on a card.
38const MAX_TEXT: usize = 4_000;
39/// The most checklist steps kept.
40const MAX_CHECKLIST: usize = 50;
41
42/// A task's id from what an agent or the operator typed: its id, or its
43/// number (`12`, `#12`).
44pub(super) fn resolve_id(state: &AppState, id: &str) -> String {
45    let trimmed = id.trim();
46    let looks_numeric = trimmed.trim_start_matches('#').chars().all(|c| c.is_ascii_digit()) && !trimmed.is_empty();
47    // `12`, `#12` (the default board's) or `work#12`.
48    if looks_numeric || crate::backend::storage::work_boards::parse_ref(trimmed).is_some() {
49        if let Ok(Some(t)) = state.work_store.work_board_get(trimmed) {
50            return t.item.id;
51        }
52    }
53    trimmed.to_string()
54}
55
56/// The tasks a task starts after (§6.15), as given: ids or numbers (`12`,
57/// `"#12"`), resolved to ids. The store checks the list when it writes it.
58pub(super) fn resolve_after(state: &AppState, given: &[Value]) -> Result<Vec<String>, String> {
59    let mut ids: Vec<String> = Vec::new();
60    for v in given {
61        let raw = match v {
62            Value::String(s) => s.clone(),
63            Value::Number(n) => n.to_string(),
64            _ => return Err(format!("after: {v} is not a task id or number")),
65        };
66        let id = resolve_id(state, &raw);
67        if !ids.contains(&id) {
68            ids.push(id);
69        }
70    }
71    Ok(ids)
72}
73
74/// Text kept on a card or in the history: sanitized, at most [`MAX_TEXT`]
75/// characters.
76pub(crate) fn clean(text: &str) -> String {
77    let s = crate::backend::reactive::sanitize::sanitize_message(text.trim());
78    match s.char_indices().nth(MAX_TEXT) {
79        Some((cut, _)) => format!("{}…", &s[..cut]),
80        None => s,
81    }
82}
83
84/// The most characters a task's payload (the brief its holder is handed) holds.
85pub(crate) const MAX_PAYLOAD: usize = 100_000;
86
87/// Why a payload is refused when it is longer than [`MAX_PAYLOAD`]: said, never cut, because an agent handed
88/// half a brief works from half.
89pub(crate) fn payload_too_long(text: &str) -> Option<String> {
90    let n = text.trim().chars().count();
91    (n > MAX_PAYLOAD).then(|| format!("the payload is {n} characters and a task holds at most {MAX_PAYLOAD}: put the rest in a file and name its full path in the payload"))
92}
93
94/// Why a payload can't be filed: it is empty, or longer than [`MAX_PAYLOAD`].
95pub(crate) fn payload_problem(text: &str) -> Option<String> {
96    if text.trim().is_empty() {
97        return Some("payload is required".into());
98    }
99    payload_too_long(text)
100}
101
102/// A payload as stored: sanitized and whole, or the reason it is refused.
103pub(crate) fn payload_text(text: &str) -> Result<String, String> {
104    match payload_too_long(text) {
105        Some(why) => Err(why),
106        None => Ok(crate::backend::reactive::sanitize::sanitize_text(text.trim())),
107    }
108}
109
110/// Why agent text is refused when `clean` would cut it: a note, a question or a result longer than [`MAX_TEXT`]
111/// is said so, not kept cut.
112pub(crate) fn text_too_long(what: &str, text: &str) -> Option<String> {
113    let n = crate::backend::reactive::sanitize::sanitize_text(text.trim()).chars().count();
114    (n > MAX_TEXT).then(|| format!("the {what} is {n} characters and a card keeps at most {MAX_TEXT}: shorten it, or put the detail in a file and link it. Nothing was changed."))
115}
116
117/// One line of history; a failure to write it is logged, never the caller's.
118pub(super) fn record(state: &AppState, work_id: &str, actor: &str, actor_kind: &str, kind: &str, from: &str, to: &str, body: &str) {
119    let ev = WorkEvent {
120        id: 0,
121        work_id: work_id.to_string(),
122        at: now_ms(),
123        actor: actor.to_string(),
124        actor_kind: actor_kind.to_string(),
125        kind: kind.to_string(),
126        from_state: from.to_string(),
127        to_state: to.to_string(),
128        body: clean(body),
129    };
130    if let Err(e) = state.work_store.work_event_add(&ev) {
131        tracing::warn!(target: "workqueue", error = %e, work_id, kind, "history line not written");
132    }
133}
134
135/// The calling agent's registration, by its token only: who asked for a task
136/// must not be something the caller can claim (§6.5).
137fn caller_reg(state: &AppState, caller: Option<&Caller>) -> Option<AgentRegistration> {
138    let uid = caller?.uid()?;
139    state.reactive_handler.list_agents().into_iter().find(|r| r.uid.as_deref() == Some(uid))
140}
141
142/// How far a pane's stored prompt may be from the start of the turn and still be what started it. The pane writes the
143/// prompt as the message is sent and srv opens the turn right after, so the two differ by a moment; a prompt from an
144/// earlier turn is minutes or more away.
145const QUOTE_WINDOW_MS: u64 = 15_000;
146
147/// The operator's own words for a card, or nothing when they can't be tied to the task. A task carries a quote only when
148/// all of these hold, so a quote is never a guess:
149/// - the turn's own first trigger is a message the operator typed (not a broadcast, a jekt, a schedule, or a message that
150///   only joined the turn);
151/// - the pane stored that message as its last prompt at the start of this turn (`prompt_at_ms`), not an earlier one, since
152///   a pane keeps its last prompt that has a goal in it across turns and a nudge ("yes") does not replace it;
153/// - no other task was filed by this agent since the turn started (`already_filed`): a second task of a turn is a
154///   follow-up or a sweep, not what the message asked.
155fn quote_for_turn(turn: &Value, prompt: &str, prompt_at_ms: Option<u64>, already_filed: bool) -> String {
156    let own = turn.get("trigger").and_then(|t| t.get("kind")).and_then(Value::as_str) == Some("user");
157    let started = turn.get("started_at_ms").and_then(Value::as_u64);
158    let tied = matches!((started, prompt_at_ms), (Some(s), Some(p)) if s.abs_diff(p) <= QUOTE_WINDOW_MS);
159    if own && tied && !already_filed {
160        clean(prompt)
161    } else {
162        String::new()
163    }
164}
165
166/// Who asked for what the agent is doing now: the operator, when a message of
167/// theirs started or joined the agent's current turn (with their words, when
168/// they are tied to this task: [`quote_for_turn`]); another agent, when its
169/// message started it; else other. `unknown` when the call carried no token.
170fn provenance(state: &AppState, reg: Option<&AgentRegistration>) -> (String, String, String) {
171    let Some(reg) = reg else {
172        return (String::new(), requested::UNKNOWN.into(), String::new());
173    };
174    let scope = format!("block:{}", reg.block_id);
175    let turn = state
176        .broker
177        .read_event_history(crate::backend::mps::EVENT_AGENT_TURN, &scope, 1)
178        .pop()
179        .and_then(|e| e.data);
180    let Some(turn) = turn else {
181        return (String::new(), requested::OTHER.into(), String::new());
182    };
183    let kind_of = |t: &Value| t.get("kind").and_then(Value::as_str).unwrap_or("").to_string();
184    let mut triggers: Vec<&Value> = turn.get("trigger").into_iter().collect();
185    if let Some(abs) = turn.get("absorbed").and_then(Value::as_array) {
186        triggers.extend(abs.iter());
187    }
188    if triggers.iter().any(|t| matches!(kind_of(t).as_str(), "user" | "broadcast")) {
189        let meta = state.mstore.get::<crate::backend::obj::Block>(&reg.block_id).ok().flatten().map(|b| b.meta);
190        let prompt = meta.as_ref().map(|m| crate::backend::obj::meta_get_string(m, "term:last_prompt", "")).unwrap_or_default();
191        let prompt_at = meta.as_ref().and_then(|m| m.get("term:last_prompt_at")).and_then(Value::as_u64);
192        let since = turn.get("started_at_ms").and_then(Value::as_u64).unwrap_or(0) as i64;
193        // A failed look counts as "filed": no quote is better than a wrong one.
194        let already_filed = state.work_store.work_card_filed_since(&reg.agent_id, since).unwrap_or(true);
195        return ("operator".into(), requested::OPERATOR.into(), quote_for_turn(&turn, &prompt, prompt_at, already_filed));
196    }
197    let first = turn.get("trigger");
198    if first.map(kind_of).as_deref() == Some("agent") {
199        let from = first.and_then(|t| t.get("from")).and_then(Value::as_str).unwrap_or("").to_string();
200        return (from, requested::AGENT.into(), String::new());
201    }
202    (String::new(), requested::OTHER.into(), String::new())
203}
204
205/// The repository the agent works in and the branch it is on, from its work
206/// facts.
207async fn repo_of(state: &AppState, reg: Option<&AgentRegistration>) -> (String, String) {
208    let Some(reg) = reg.cloned() else { return Default::default() };
209    let store = state.mstore.clone();
210    let channel = crate::backend::work_facts::cross_channel::own_channel();
211    let facts = tokio::task::spawn_blocking(move || crate::backend::work_facts::collect_local(&store, &[reg], &channel))
212        .await
213        .unwrap_or_default();
214    facts
215        .into_iter()
216        .next()
217        .map(|f| (f.repo_key().unwrap_or_default(), f.branch.unwrap_or_default()))
218        .unwrap_or_default()
219}
220
221/// What an enqueue adds for the board: who asked, the repository.
222pub(super) struct Filing {
223    /// The id of the board it is filed on; empty means the default board.
224    pub board: String,
225    pub repo: Option<String>,
226    pub review: Option<bool>,
227}
228
229/// The card of a task about to be enqueued: who asked, the repository, the
230/// filer. Worked out before the row exists, so nothing awaits between the
231/// row and its card (`file_card`).
232pub(super) async fn prepare_card(state: &AppState, caller: Option<&Caller>, created_by: &str, f: Filing) -> NewCard {
233    let reg = caller_reg(state, caller);
234    let (requested_by, kind, request_text) = provenance(state, reg.as_ref());
235    // Not the branch the filer is on: that is its current work's, not this
236    // task's. The task's branch comes from the PR it opens (kanban::on_new_prs).
237    let repo = match f.repo.filter(|r| !r.trim().is_empty()) {
238        Some(r) => r.trim().to_string(),
239        None => repo_of(state, reg.as_ref()).await.0,
240    };
241    let filer = reg.as_ref().map(|r| r.agent_id.clone()).unwrap_or_else(|| created_by.to_string());
242    NewCard {
243        board: f.board,
244        repo,
245        branch: String::new(),
246        // What the operator asked for needs the operator's eyes; a handoff
247        // between agents doesn't (D2).
248        review_required: f.review.unwrap_or(kind == requested::OPERATOR),
249        requested_by,
250        requested_by_kind: kind,
251        request_text,
252        filed_by: filer,
253    }
254}
255
256/// The card of a task an agent of another machine files: asked by that agent (`slug@machine`), never by
257/// the operator, so it is not held for an Accept unless the request says so.
258pub(super) fn remote_card(actor: &str, f: Filing) -> NewCard {
259    NewCard {
260        board: f.board,
261        repo: f.repo.map(|r| r.trim().to_string()).unwrap_or_default(),
262        branch: String::new(),
263        review_required: f.review.unwrap_or(false),
264        requested_by: actor.to_string(),
265        requested_by_kind: requested::AGENT.to_string(),
266        request_text: String::new(),
267        filed_by: actor.to_string(),
268    }
269}
270
271/// Give a just-enqueued task its card and first history line. Returns its
272/// number. Synchronous: called right after the enqueue, with nothing awaited
273/// between them; a claim or list that got in first made an empty card, which
274/// this fills.
275pub(super) fn file_card(state: &AppState, item: &WorkItem, card: &NewCard) -> Option<i64> {
276    let now = now_ms();
277    let filer = card.filed_by.clone();
278    let num = match state.work_store.work_card_create(&item.id, card, now) {
279        Ok(n) => Some(n),
280        Err(e) => {
281            tracing::warn!(target: "workqueue", error = %e, "card not created");
282            None
283        }
284    };
285    let for_itself = !item.target_agent.is_empty() && item.target_agent == filer;
286    let state_now = if item.state == work_state::HELD { work_state::HELD } else { work_state::OPEN };
287    record(state, &item.id, &filer, "agent", if for_itself { "filed_for_later" } else { "created" }, "", state_now, "");
288    super::task_flow_notes::note(state, &item.id, crate::backend::task_flow::TaskFlowKind::Filed, &filer, &item.target_agent);
289    num
290}
291
292/// The next task waiting for this agent, as the answer to finishing one
293/// carries it (§6.5: it proceeds through its backlog).
294pub(super) fn next_for(state: &AppState, agent_id: &str, uid: &str) -> Value {
295    let waiting = state.work_store.work_board_waiting_for(agent_id, uid, 50, now_ms()).unwrap_or_default();
296    match waiting.first() {
297        Some(t) => json!({
298            "next": task_brief(t),
299            "waiting": waiting.len(),
300        }),
301        None => json!({ "next": null, "waiting": 0 }),
302    }
303}
304
305/// The few fields of a task an agent's answer names.
306pub(super) fn task_brief(t: &BoardTask) -> Value {
307    json!({
308        "id": t.item.id,
309        "num": t.card.num,
310        "ref": t.card.task_ref,
311        "board": t.card.board,
312        "title": t.item.title,
313        "requested_by": t.card.requested_by,
314        "requested_by_kind": t.card.requested_by_kind,
315        "created_at": t.item.created_at,
316    })
317}
318
319/// Whether a live holder's lease on `item` is renewed (R5 of
320/// docs/specs/SPEC_UNRESPONSIVE_AGENTS_2026_10_23.md). Always, except for a
321/// holder that is out of quota or signed out on a task open to anyone or to a
322/// group: after 30 minutes of it, and with its reset more than an hour away
323/// (or not known), the lease lapses so someone else can take the task. A task
324/// aimed at an agent stays with it and shows in Needs you. The rule is
325/// `decide` with `Intent::Lease` (`backend/agent_status.rs`), with the numbers.
326fn renews_lease(item: &WorkItem, unavailable: Option<&crate::backend::agent_state::Unavailable>, now_ms: i64) -> bool {
327    use crate::backend::agent_availability::{of_unavailable, Availability};
328    use crate::backend::agent_status::{decide, AgentStatus, Decision, Intent, Pane, Reach, Wanted};
329    // Only the holder's availability matters to a lease: the rest of the status is what a live holder is.
330    let status = AgentStatus {
331        availability: unavailable.map_or(Availability::Unknown, of_unavailable),
332        pane: Pane::Shown,
333        wanted: Wanted::Running,
334        api: Reach::NotTracked,
335        controller: true,
336    };
337    let aimed_at_agent = !item.target_agent.is_empty() || !item.target_agent_uid.is_empty();
338    let now_ms = u64::try_from(now_ms).unwrap_or(0);
339    decide(&status, Intent::Lease { aimed_at_agent, now_ms }, || false) == Decision::Renew
340}
341
342/// Keep the leases of claims whose holder is alive, so a long tool call or a
343/// model that never calls `heartbeat` doesn't lose its task (§6.8). A holder
344/// is alive while it is registered and its process runs; one that is out of
345/// quota or signed out is alive but may let go of a task nobody in particular
346/// owns (`renews_lease`). Run before the reap.
347pub(super) fn extend_live_leases(state: &AppState, now: i64) {
348    let Ok(claimed) = state.work_store.work_claimed_all() else { return };
349    if claimed.is_empty() {
350        return;
351    }
352    let regs = state.reactive_handler.list_agents();
353    for item in claimed {
354        let holder = regs.iter().find(|r| {
355            (!item.claimed_by_uid.is_empty() && r.uid.as_deref() == Some(item.claimed_by_uid.as_str()))
356                || (item.claimed_by_uid.is_empty() && r.agent_id == item.claimed_by)
357        });
358        let alive = holder.is_some_and(|r| {
359            crate::backend::blockcontroller::get_block_controller_status(&r.block_id)
360                .is_some_and(|s| s.shellprocstatus == crate::backend::blockcontroller::STATUS_RUNNING)
361        });
362        if alive {
363            let unavailable = holder.and_then(|r| {
364                crate::backend::agent_state::unavailable_of_block(&state.mstore, Some(&state.identity_store), &r.block_id, now as u64)
365            });
366            if renews_lease(&item, unavailable.as_ref(), now) {
367                let _ = state.work_store.work_extend_lease(&item.id, item.attempts, now, LEASE_MS);
368            }
369        }
370    }
371}
372
373/// The claims about to be reaped: record them as expired after the reap.
374pub(super) fn expiring(state: &AppState, now: i64) -> Vec<WorkItem> {
375    state
376        .work_store
377        .work_claimed_all()
378        .unwrap_or_default()
379        .into_iter()
380        .filter(|i| i.claim_expires.is_some_and(|e| e <= now))
381        .collect()
382}
383
384#[derive(Debug, Deserialize)]
385pub(super) struct UpdateRequest {
386    pub agent_id: String,
387    /// The attempt from the caller's claim. `update` without it is any agent leaving a note on a task nobody
388    /// holds (`annotate`); `ask` and `submit` are only ever the holder's and need it (`attempt_of`).
389    #[serde(default)]
390    pub attempt: Option<i64>,
391    #[serde(default)]
392    pub note: Option<String>,
393    #[serde(default)]
394    pub checklist: Option<Vec<ChecklistItem>>,
395    #[serde(default)]
396    pub branch: Option<String>,
397    #[serde(default)]
398    pub pr_url: Option<String>,
399    /// A pull request to take off the card (`links.unpr`): the holder's alone.
400    #[serde(default)]
401    pub unpr: Option<String>,
402    /// The path of the document the task wrote (`links.doc`).
403    #[serde(default)]
404    pub doc: Option<String>,
405    /// `ask`: the question; `submit`: the result.
406    #[serde(default)]
407    pub text: String,
408    /// Files already uploaded (`POST /agentmux/work/media`) to attach to the task.
409    #[serde(default)]
410    pub media: Vec<super::work_media::MediaRef>,
411    /// The task changes the UI (it then needs media to be handed in for review).
412    #[serde(default)]
413    pub ui_change: Option<bool>,
414    /// Why it is handed in without media.
415    #[serde(default)]
416    pub no_media_reason: Option<String>,
417}
418
419/// The attempt of a call only a holder can make (`ask`, `submit`).
420fn attempt_of(req: &UpdateRequest) -> Result<i64, (StatusCode, Json<Value>)> {
421    req.attempt.ok_or_else(|| (StatusCode::BAD_REQUEST, Json(json!({ "error": "attempt is required: the one from the claim" }))))
422}
423
424impl UpdateRequest {
425    fn media_call(&self) -> super::work_media::MediaCall {
426        super::work_media::MediaCall {
427            media: self.media.clone(),
428            ui_change: self.ui_change,
429            no_media_reason: self.no_media_reason.clone(),
430        }
431    }
432}
433
434/// Why a handed-in document path can't be kept, if it can't. The card's Open
435/// button gives the path to the Editor as it is, and srv has no way to tell
436/// which clone a relative path meant, so only an absolute (or `~/`) path will do.
437fn doc_problem(req: &UpdateRequest) -> Option<String> {
438    let path = req.doc.as_deref().map(str::trim).filter(|p| !p.is_empty())?;
439    let bytes = path.as_bytes();
440    let absolute = path.starts_with('/')
441        || path.starts_with('\\')
442        || path.starts_with("~/")
443        || path.starts_with("~\\")
444        || (bytes.len() >= 3 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':' && matches!(bytes[2], b'/' | b'\\'));
445    (!absolute).then(|| format!("links.doc \"{path}\" is a relative path: give the document's full path, e.g. C:/Users/you/work/repo/docs/specs/SPEC_X.md"))
446}
447
448fn card_update(req: &UpdateRequest) -> CardUpdate {
449    let one = |s: &Option<String>| s.as_deref().map(str::trim).filter(|s| !s.is_empty()).map(clean);
450    CardUpdate {
451        note: one(&req.note),
452        checklist: req.checklist.as_ref().map(|c| {
453            c.iter()
454                .take(MAX_CHECKLIST)
455                .map(|i| ChecklistItem { text: clean(&i.text), status: i.status.trim().to_string() })
456                .collect()
457        }),
458        branch: one(&req.branch),
459        pr_url: one(&req.pr_url),
460        pr_source: None,
461        doc: one(&req.doc),
462    }
463}
464
465fn holder_uid(caller: Option<&Caller>) -> &str {
466    caller.and_then(Caller::uid).unwrap_or("")
467}
468
469fn conflict() -> (StatusCode, Json<Value>) {
470    (
471        StatusCode::CONFLICT,
472        Json(json!({
473            "ok": false,
474            "error": "not the current holder, or this claim has been superseded — re-claim before continuing"
475        })),
476    )
477}
478
479fn failed(e: impl std::fmt::Display) -> (StatusCode, Json<Value>) {
480    (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({ "error": e.to_string() })))
481}
482
483/// Whether the caller holds this claim now: the same rule as the queue's
484/// holder transitions (UID when both are known, else the name), and the fence.
485fn holds(item: &WorkItem, agent_id: &str, uid: &str, attempt: i64) -> bool {
486    let who = if !item.claimed_by_uid.is_empty() && !uid.is_empty() {
487        item.claimed_by_uid == uid
488    } else {
489        item.claimed_by == agent_id
490    };
491    who && item.attempts == attempt && matches!(item.state.as_str(), work_state::CLAIMED | work_state::BLOCKED)
492}
493
494/// `POST /agentmux/work/:id/update`: a progress note, a checklist, links. Also
495/// a heartbeat.
496pub(super) async fn handle_work_update(
497    State(state): State<AppState>,
498    Path(id): Path<String>,
499    caller: Option<axum::Extension<Caller>>,
500    Json(req): Json<UpdateRequest>,
501) -> (StatusCode, Json<Value>) {
502    let caller = caller.as_deref();
503    if let Some(why) = req.note.as_deref().and_then(|n| text_too_long("note", n)) {
504        return (StatusCode::BAD_REQUEST, Json(json!({ "error": why })));
505    }
506    let id = resolve_id(&state, &id);
507    let Some(attempt) = req.attempt else { return annotate(&state, caller, &id, &req) };
508    let Ok(Some(item)) = state.work_store.work_queue_get(&id) else { return conflict() };
509    if !holds(&item, &req.agent_id, holder_uid(caller), attempt) {
510        return conflict();
511    }
512    if let Some(why) = doc_problem(&req) {
513        return (StatusCode::BAD_REQUEST, Json(json!({ "error": why })));
514    }
515    // The address to take off is checked before anything is written, so a bad one leaves the card as it was.
516    let unpr = match req.unpr.as_deref().map(str::trim).filter(|p| !p.is_empty()) {
517        None => None,
518        Some(addr) => {
519            let repo = state.work_store.work_board_get(&id).ok().flatten().map(|t| t.card.repo).unwrap_or_default();
520            match crate::backend::storage::work_card_prs::parse_pr_ref(addr, &repo) {
521                Some(found) => Some(found),
522                None => return (StatusCode::BAD_REQUEST, Json(json!({ "error": "links.unpr is not a pull request address" }))),
523            }
524        }
525    };
526    let now = now_ms();
527    let _ = state.work_store.work_card_ensure(&id, now);
528    let attached = match super::work_media::apply(&state, &item, &req.agent_id, holder_uid(caller), &req.media_call()) {
529        Ok(rows) => rows,
530        Err(refused) => return refused,
531    };
532    let u = card_update(&req);
533    if let Err(e) = state.work_store.work_card_update(&id, &u, now) {
534        return failed(e);
535    }
536    let _ = state.work_store.work_extend_lease(&id, item.attempts, now, LEASE_MS);
537    let mut body = u.note.clone().unwrap_or_default();
538    if let Some(c) = &u.checklist {
539        let done = c.iter().filter(|i| i.status == "completed").count();
540        body = format!("{body}{}checklist {done}/{}", if body.is_empty() { "" } else { " · " }, c.len());
541    }
542    record(&state, &id, &req.agent_id, "agent", "updated", &item.state, &item.state, &body);
543    if u.pr_url.is_some() || u.branch.is_some() || u.doc.is_some() {
544        let link = [u.pr_url.as_deref(), u.branch.as_deref(), u.doc.as_deref()]
545            .into_iter()
546            .flatten()
547            .collect::<Vec<_>>()
548            .join(" ");
549        record(&state, &id, &req.agent_id, "agent", "linked", &item.state, &item.state, &link);
550    }
551    if let Some((repo, number)) = unpr {
552        if state.work_store.work_card_pr_unlink(&id, &repo, number, now).unwrap_or(false) {
553            record(&state, &id, &req.agent_id, "agent", "pr_unlinked", &item.state, &item.state, &crate::backend::storage::work_card_prs::pr_url(&repo, number));
554        }
555    }
556    let mut answer = json!({ "ok": true });
557    if !attached.is_empty() {
558        let names = attached.iter().map(|m| m.name.as_str()).collect::<Vec<_>>().join(", ");
559        record(&state, &id, &req.agent_id, "agent", "media", &item.state, &item.state, &format!("attached {names}"));
560        answer["attached"] = super::work_media::attached_json(&attached);
561    }
562    if u.pr_url.is_some() {
563        if let Some(reminder) = super::work_media::pr_reminder(&state, &id, item.attempts) {
564            answer["reminder"] = json!(reminder);
565        }
566    }
567    super::work_queue::publish_changed(&state);
568    (StatusCode::OK, Json(answer))
569}
570
571/// `update` without an attempt: any agent leaves a note, and links, on a task nobody holds (waiting, or on
572/// hold), as any agent can already hold, move or edit one. It is not a claim: no attempt is used and no lease
573/// is touched. The note is written as "<agent>: <note>" so the card says who wrote it, and the history line
574/// carries the same agent. A claimed task's note, checklist and files stay its holder's.
575fn annotate(state: &AppState, caller: Option<&Caller>, id: &str, req: &UpdateRequest) -> (StatusCode, Json<Value>) {
576    let who = req.agent_id.trim();
577    if who.is_empty() {
578        return (StatusCode::BAD_REQUEST, Json(json!({ "error": "agent_id is required" })));
579    }
580    let Ok(Some(item)) = state.work_store.work_queue_get(id) else {
581        return (StatusCode::NOT_FOUND, Json(json!({ "error": format!("no task {id}") })));
582    };
583    if !sees_task(state, caller, id) {
584        return (StatusCode::NOT_FOUND, Json(json!({ "error": format!("no task {id}") })));
585    }
586    let name = name_of(state, id);
587    match item.state.as_str() {
588        work_state::OPEN | work_state::HELD => {}
589        work_state::CLAIMED | work_state::BLOCKED => {
590            let holder = if item.claimed_by.is_empty() { "its holder".to_string() } else { item.claimed_by.clone() };
591            return refused(format!(
592                "{name} is being worked on by {holder}: its note, checklist and files are the holder's to write (with the attempt from its claim). To tell them something, message {holder}"
593            ));
594        }
595        other => {
596            return refused(format!("{name} is {other}: a note can be left on a task that is waiting or on hold, not on one that is finished or in review"));
597        }
598    }
599    if req.checklist.is_some() || !req.media.is_empty() || req.ui_change.is_some() || req.no_media_reason.is_some() {
600        return refused(format!(
601            "{name} is not claimed by you: you can leave a note and links on it, but its checklist and files are its holder's"
602        ));
603    }
604    if let Some(why) = doc_problem(req) {
605        return (StatusCode::BAD_REQUEST, Json(json!({ "error": why })));
606    }
607    let mut u = card_update(req);
608    if req.unpr.is_some() {
609        return (StatusCode::BAD_REQUEST, Json(json!({ "error": "links.unpr is the holder's: only the task's holder takes a pull request off its card" })));
610    }
611    if u.note.is_none() && u.branch.is_none() && u.pr_url.is_none() && u.doc.is_none() {
612        return (StatusCode::BAD_REQUEST, Json(json!({ "error": "nothing to write: give a note or links (pr, branch, doc)" })));
613    }
614    u.note = u.note.map(|n| format!("{who}: {n}"));
615    if let Some(why) = u.note.as_deref().and_then(|n| text_too_long("note", n)) {
616        return (StatusCode::BAD_REQUEST, Json(json!({ "error": why })));
617    }
618    let now = now_ms();
619    let _ = state.work_store.work_card_ensure(id, now);
620    if let Err(e) = state.work_store.work_card_update(id, &u, now) {
621        return failed(e);
622    }
623    if let Some(note) = &u.note {
624        record(state, id, who, "agent", "updated", &item.state, &item.state, note);
625    }
626    if u.pr_url.is_some() || u.branch.is_some() || u.doc.is_some() {
627        let link = [u.pr_url.as_deref(), u.branch.as_deref(), u.doc.as_deref()].into_iter().flatten().collect::<Vec<_>>().join(" ");
628        record(state, id, who, "agent", "linked", &item.state, &item.state, &link);
629    }
630    super::work_queue::publish_changed(state);
631    (StatusCode::OK, Json(json!({ "ok": true, "claimed": false })))
632}
633
634/// `POST /agentmux/work/:id/ask`: the holder needs the operator. The task
635/// goes to Needs you; the holder keeps it, its lease paused.
636pub(super) async fn handle_work_ask(
637    State(state): State<AppState>,
638    Path(id): Path<String>,
639    caller: Option<axum::Extension<Caller>>,
640    Json(req): Json<UpdateRequest>,
641) -> (StatusCode, Json<Value>) {
642    let caller = caller.as_deref();
643    if let Some(why) = text_too_long("question", &req.text) {
644        return (StatusCode::BAD_REQUEST, Json(json!({ "error": why })));
645    }
646    let question = clean(&req.text);
647    if question.is_empty() {
648        return (StatusCode::BAD_REQUEST, Json(json!({ "error": "the question is required" })));
649    }
650    let attempt = match attempt_of(&req) {
651        Ok(a) => a,
652        Err(refused) => return refused,
653    };
654    let id = resolve_id(&state, &id);
655    let now = now_ms();
656    match state.work_store.work_ask(&id, &req.agent_id, holder_uid(caller), attempt, now) {
657        Ok(Some(_)) => {
658            let _ = state.work_store.work_card_ensure(&id, now);
659            let _ = state.work_store.work_card_set_question(&id, &question, now);
660            record(&state, &id, &req.agent_id, "agent", "asked", work_state::CLAIMED, work_state::BLOCKED, &question);
661            super::work_queue::publish_changed(&state);
662            (StatusCode::OK, Json(json!({ "ok": true, "state": work_state::BLOCKED })))
663        }
664        Ok(None) => conflict(),
665        Err(e) => failed(e),
666    }
667}
668
669/// `POST /agentmux/work/:id/submit`: the holder hands it in. A task that
670/// needs review waits in Review for the operator; one that doesn't is done.
671/// The answer names the next task waiting for the agent.
672pub(super) async fn handle_work_submit(
673    State(state): State<AppState>,
674    Path(id): Path<String>,
675    caller: Option<axum::Extension<Caller>>,
676    Json(req): Json<UpdateRequest>,
677) -> (StatusCode, Json<Value>) {
678    let caller = caller.as_deref();
679    if let Some(why) = text_too_long("result", &req.text) {
680        return (StatusCode::BAD_REQUEST, Json(json!({ "error": why })));
681    }
682    let result = clean(&req.text);
683    if result.is_empty() {
684        return (StatusCode::BAD_REQUEST, Json(json!({ "error": "result is required: what was done, with links" })));
685    }
686    if let Some(why) = doc_problem(&req) {
687        return (StatusCode::BAD_REQUEST, Json(json!({ "error": why })));
688    }
689    let attempt = match attempt_of(&req) {
690        Ok(a) => a,
691        Err(refused) => return refused,
692    };
693    let id = resolve_id(&state, &id);
694    let Ok(Some(item)) = state.work_store.work_queue_get(&id) else { return conflict() };
695    if !holds(&item, &req.agent_id, holder_uid(caller), attempt) {
696        return conflict();
697    }
698    // The files first, so the check below sees them; a bad file fails the call before anything changes.
699    let attached = match super::work_media::apply(&state, &item, &req.agent_id, holder_uid(caller), &req.media_call()) {
700        Ok(rows) => rows,
701        Err(refused) => return refused,
702    };
703    if !attached.is_empty() {
704        let names = attached.iter().map(|m| m.name.as_str()).collect::<Vec<_>>().join(", ");
705        record(&state, &id, &req.agent_id, "agent", "media", &item.state, &item.state, &format!("attached {names}"));
706    }
707    let (status, Json(mut body)) = finish(&state, caller, &id, &req.agent_id, attempt, &result, Some(card_update(&req))).await;
708    if !attached.is_empty() {
709        body["attached"] = super::work_media::attached_json(&attached);
710    }
711    (status, Json(body))
712}
713
714#[derive(Debug, Deserialize)]
715pub(super) struct HoldRequest {
716    pub agent_id: String,
717    /// `hold` on a task the caller is working on: the attempt from its claim.
718    #[serde(default)]
719    pub attempt: Option<i64>,
720    #[serde(default)]
721    pub reason: String,
722}
723
724/// A task as an agent's answer names it: `#12`, else its id.
725fn name_of(state: &AppState, id: &str) -> String {
726    match state.work_store.work_card_ensure(id, now_ms()) {
727        Ok(n) => ref_of(state, id).map(|(r, _)| r).unwrap_or_else(|| format!("#{n}")),
728        Err(_) => id.to_string(),
729    }
730}
731
732/// How a task is written (`#12` on the default board, else `work#12`) and its board's slug.
733pub(super) fn ref_of(state: &AppState, work_id: &str) -> Option<(String, String)> {
734    let (board, num) = state.work_store.work_task_board(work_id).ok().flatten()?;
735    Some((board.task_ref(num), board.slug))
736}
737
738/// The agent a call comes from, by its token, for which boards it sees: its id and UID. `None`
739/// when the call carries no token, which sees every board.
740pub(super) fn viewer(state: &AppState, caller: Option<&Caller>) -> Option<(String, String)> {
741    let reg = caller_reg(state, caller)?;
742    Some((reg.agent_id.clone(), reg.uid.clone().unwrap_or_default()))
743}
744
745/// The most history lines `GET /agentmux/work/:id` returns.
746const GET_HISTORY: usize = 30;
747
748/// `GET /agentmux/work/:id` (`Tasks` `get`): one task whole, for any agent that sees its board: the instruction
749/// it was filed with, who it is for and who holds it, its card (links, note, question, checklist, what it
750/// starts after) and its last history lines. A task on a board the caller can't see is refused like one that
751/// doesn't exist.
752pub(super) async fn handle_work_get(
753    State(state): State<AppState>,
754    Path(id): Path<String>,
755    caller: Option<axum::Extension<Caller>>,
756) -> (StatusCode, Json<Value>) {
757    let none = || (StatusCode::NOT_FOUND, Json(json!({ "error": "no such task" })));
758    let id = resolve_id(&state, &id);
759    if !sees_task(&state, caller.as_deref(), &id) {
760        return none();
761    }
762    // A card is made only for a task that exists: `work_card_ensure` takes the next number on the board.
763    if !matches!(state.work_store.work_queue_get(&id), Ok(Some(_))) {
764        return none();
765    }
766    let _ = state.work_store.work_card_ensure(&id, now_ms());
767    let Ok(Some(task)) = state.work_store.work_board_get(&id) else { return none() };
768    let mut v = serde_json::to_value(&task).unwrap_or_default();
769    let history = state.work_store.work_events(&task.item.id, GET_HISTORY).unwrap_or_default();
770    v["history"] = serde_json::to_value(history).unwrap_or_default();
771    // The one line of the task's tokens (`Tasks get` shows it; the detail is `Tasks tokens`).
772    if let Ok(Some(detail)) = state.work_store.work_tokens_detail(&task.item.id) {
773        v["token_line"] = json!(detail.line());
774    }
775    (StatusCode::OK, Json(v))
776}
777
778/// `GET /agentmux/work/:id/tokens` (`Tasks` `tokens`): a task's tally and where it went, as counts, for any agent that
779/// sees its board. Never part of the answers an agent gets anyway: it costs nothing unless it asks.
780pub(super) async fn handle_work_tokens(
781    State(state): State<AppState>,
782    Path(id): Path<String>,
783    caller: Option<axum::Extension<Caller>>,
784) -> (StatusCode, Json<Value>) {
785    let none = || (StatusCode::NOT_FOUND, Json(json!({ "error": "no such task" })));
786    let id = resolve_id(&state, &id);
787    if !sees_task(&state, caller.as_deref(), &id) {
788        return none();
789    }
790    match state.work_store.work_tokens_detail(&id) {
791        Ok(Some(detail)) => {
792            let name = state.work_store.work_board_get(&id).ok().flatten().map(|t| format!("task {}", t.card.name())).unwrap_or_else(|| format!("work item {id}"));
793            (StatusCode::OK, Json(json!({ "text": detail.text(&name), "detail": detail })))
794        }
795        Ok(None) => none(),
796        Err(e) => failed(e),
797    }
798}
799
800/// Whether the caller may see the board a task is on (a call with no token sees every board). A task
801/// on a board whose agent list leaves the caller out is refused like one that doesn't exist.
802pub(super) fn sees_task(state: &AppState, caller: Option<&Caller>, work_id: &str) -> bool {
803    let Some((id, uid)) = viewer(state, caller) else { return true };
804    match state.work_store.work_task_board(work_id) {
805        Ok(Some((board, _))) => board.visible_to(&id, &uid),
806        _ => true,
807    }
808}
809
810/// The board a call names (none: the default board), if the caller sees it. A board it can't see is
811/// refused like one that doesn't exist; `filing` also refuses an archived board, which takes no new
812/// tasks.
813pub(super) fn pick_board(
814    state: &AppState,
815    key: Option<&str>,
816    who: Option<(&str, &str)>,
817    filing: bool,
818) -> Result<crate::backend::storage::work_boards::Board, String> {
819    let key = key.map(str::trim).filter(|k| !k.is_empty());
820    let board = state.work_store.work_board_resolve(key, now_ms()).map_err(|e| e.to_string())?;
821    if who.is_some_and(|(id, uid)| !board.visible_to(id, uid)) {
822        return Err(match key {
823            Some(k) => format!("no board named \"{k}\""),
824            None => format!("the default board ({}) isn't open to you; name a board", board.slug),
825        });
826    }
827    if filing && board.archived {
828        return Err(format!("board {} is archived and takes no new tasks; unarchive it first", board.slug));
829    }
830    Ok(board)
831}
832
833/// Where the agent a task is aimed at stands, as words after its name: its state when it runs here, else
834/// that it is not running (stopped, parked or gone), which no claim of its own will end.
835fn target_state_words(state: &AppState, item: &WorkItem) -> String {
836    if item.target_agent.is_empty() && item.target_agent_uid.is_empty() {
837        return String::new();
838    }
839    let regs = state.reactive_handler.list_agents();
840    let reg = regs.iter().find(|r| {
841        if item.target_agent_uid.is_empty() {
842            r.agent_id.eq_ignore_ascii_case(&item.target_agent)
843        } else {
844            r.uid.as_deref() == Some(item.target_agent_uid.as_str())
845        }
846    });
847    match reg {
848        Some(r) => match crate::backend::agent_state::current_state(&state.mstore, &r.block_id) {
849            Some(s) => format!(" ({})", s.as_str()),
850            None => " (running)".to_string(),
851        },
852        None => " (not running: stopped, parked or gone)".to_string(),
853    }
854}
855
856/// Who a waiting task is for, as an answer says it.
857fn waiting_for(item: &WorkItem) -> String {
858    if !item.target_agent.is_empty() {
859        item.target_agent.clone()
860    } else if !item.target_group.is_empty() {
861        format!("group {}", item.target_group)
862    } else {
863        "anyone".into()
864    }
865}
866
867/// A hold's reason shows on the shared Kanban: one that looks like a
868/// credential or a destructive command is refused, before anything moves.
869fn sensitive_reason(reason: &str) -> Option<(StatusCode, Json<Value>)> {
870    crate::backend::reactive::sanitize::is_sensitive_message(reason).then(|| {
871        (
872            StatusCode::BAD_REQUEST,
873            Json(json!({ "ok": false, "error": "the reason looks like it holds a credential or a destructive command; leave that out of it" })),
874        )
875    })
876}
877
878fn refused(text: String) -> (StatusCode, Json<Value>) {
879    (StatusCode::CONFLICT, Json(json!({ "ok": false, "error": text })))
880}
881
882fn moved(state: &AppState, id: &str, to: &str, changed: bool) -> (StatusCode, Json<Value>) {
883    let item = state.work_store.work_queue_get(id).ok().flatten();
884    (
885        StatusCode::OK,
886        Json(json!({
887            "ok": true,
888            "state": to,
889            "changed": changed,
890            "name": name_of(state, id),
891            "for": item.as_ref().map(waiting_for).unwrap_or_default(),
892        })),
893    )
894}
895
896/// `POST /agentmux/work/:id/hold`: any agent puts a waiting task on hold, so
897/// no one takes it until it is taken off hold; the holder of a claimed task
898/// pauses it, with its `attempt`
899/// (SPEC_KANBAN_AGENTS_HOLD_AND_UNHOLD_2026_10_22.md §3.1, §3.2).
900pub(super) async fn handle_work_hold(
901    State(state): State<AppState>,
902    Path(id): Path<String>,
903    caller: Option<axum::Extension<Caller>>,
904    Json(req): Json<HoldRequest>,
905) -> (StatusCode, Json<Value>) {
906    let caller = caller.as_deref();
907    if req.agent_id.trim().is_empty() {
908        return (StatusCode::BAD_REQUEST, Json(json!({ "error": "agent_id is required" })));
909    }
910    let id = resolve_id(&state, &id);
911    let Ok(Some(item)) = state.work_store.work_queue_get(&id) else {
912        return (StatusCode::NOT_FOUND, Json(json!({ "error": format!("no task {id}") })));
913    };
914    if !sees_task(&state, caller, &id) {
915        return (StatusCode::NOT_FOUND, Json(json!({ "error": format!("no task {id}") })));
916    }
917    let reason = clean(&req.reason);
918    if let Some(r) = sensitive_reason(&reason) {
919        return r;
920    }
921    let now = now_ms();
922    let name = name_of(&state, &id);
923    match item.state.as_str() {
924        work_state::HELD => moved(&state, &id, work_state::HELD, false),
925        work_state::OPEN => match state.work_store.work_hold(&id, now) {
926            Ok(Some(m)) => {
927                record(&state, &id, &req.agent_id, "agent", "held", &m.from, &m.to, &reason);
928                super::work_queue::publish_changed(&state);
929                moved(&state, &id, work_state::HELD, true)
930            }
931            Ok(None) => refused(format!("{name} moved meanwhile; look at it again with Tasks list")),
932            Err(e) => failed(e),
933        },
934        work_state::CLAIMED => {
935            let uid = holder_uid(caller);
936            let Some(attempt) = req.attempt.filter(|&a| holds(&item, &req.agent_id, uid, a)) else {
937                let who = if item.claimed_by.is_empty() { "another agent".to_string() } else { item.claimed_by.clone() };
938                return refused(format!(
939                    "{name} is being worked on by {who}: only its holder can put it on hold (with its attempt); message them"
940                ));
941            };
942            match state.work_store.work_hold_own(&id, &req.agent_id, uid, attempt, now) {
943                Ok(Some(_)) => {
944                    record(&state, &id, &req.agent_id, "agent", "held", work_state::CLAIMED, work_state::HELD, &reason);
945                    super::work_queue::publish_changed(&state);
946                    moved(&state, &id, work_state::HELD, true)
947                }
948                Ok(None) => conflict(),
949                Err(e) => failed(e),
950            }
951        }
952        work_state::BLOCKED => refused(format!(
953            "{name} waits on the operator's answer to its question; that is already its pause"
954        )),
955        other => refused(format!(
956            "{name} is {other}: only a waiting task, or one you are working on, can be put on hold"
957        )),
958    }
959}
960
961/// `POST /agentmux/work/:id/unhold`: any agent takes a held task off hold; it
962/// waits again for whoever it is for (§3.1).
963pub(super) async fn handle_work_unhold(
964    State(state): State<AppState>,
965    Path(id): Path<String>,
966    caller: Option<axum::Extension<Caller>>,
967    Json(req): Json<HoldRequest>,
968) -> (StatusCode, Json<Value>) {
969    if req.agent_id.trim().is_empty() {
970        return (StatusCode::BAD_REQUEST, Json(json!({ "error": "agent_id is required" })));
971    }
972    let id = resolve_id(&state, &id);
973    let Ok(Some(item)) = state.work_store.work_queue_get(&id) else {
974        return (StatusCode::NOT_FOUND, Json(json!({ "error": format!("no task {id}") })));
975    };
976    if !sees_task(&state, caller.as_deref(), &id) {
977        return (StatusCode::NOT_FOUND, Json(json!({ "error": format!("no task {id}") })));
978    }
979    let reason = clean(&req.reason);
980    if let Some(r) = sensitive_reason(&reason) {
981        return r;
982    }
983    let name = name_of(&state, &id);
984    match item.state.as_str() {
985        work_state::OPEN => moved(&state, &id, work_state::OPEN, false),
986        work_state::HELD => match state.work_store.work_unhold(&id, now_ms()) {
987            Ok(Some(m)) => {
988                record(&state, &id, &req.agent_id, "agent", "unheld", &m.from, &m.to, &reason);
989                super::work_queue::publish_changed(&state);
990                moved(&state, &id, work_state::OPEN, true)
991            }
992            Ok(None) => refused(format!("{name} moved meanwhile; look at it again with Tasks list")),
993            Err(e) => failed(e),
994        },
995        other => refused(format!("{name} is {other}, not on hold")),
996    }
997}
998
999/// Why a named claim (`claim` with `id`) took nothing: the first rule the task
1000/// fails, in words the agent can act on.
1001pub(super) fn why_not_claimed(state: &AppState, id: &str, filter: &ClaimFilter, now: i64) -> String {
1002    let (agent_id, agent_uid, groups) = (filter.agent_id.as_str(), filter.agent_uid.as_str(), &filter.groups);
1003    let Ok(Some(item)) = state.work_store.work_queue_get(id) else {
1004        return format!("there is no task {id}");
1005    };
1006    let name = name_of(state, id);
1007    if item.state != work_state::OPEN && item.state != work_state::HELD {
1008        let who = if item.claimed_by.is_empty() { String::new() } else { format!(" (by {})", item.claimed_by) };
1009        return format!("{name} is {}{who}, not waiting", item.state);
1010    }
1011    let mine = if !item.target_agent_uid.is_empty() {
1012        item.target_agent_uid == agent_uid
1013    } else {
1014        item.target_agent.is_empty() || item.target_agent == agent_id
1015    };
1016    if !mine {
1017        return format!(
1018            "{name} is for {}{}, not you. A task aimed at someone is theirs to claim; to take it yourself, move it to you first (Tasks move with id and target_agent set to your own id), or ask its filer or a leader. One aimed at an agent that is not working waits until someone moves it.",
1019            waiting_for(&item),
1020            target_state_words(state, &item)
1021        );
1022    }
1023    if !item.target_group.is_empty() && !groups.contains(&item.target_group) {
1024        return format!("{name} is for group {}, which you aren't in", item.target_group);
1025    }
1026    if let Some(kind) = filter.kind.as_deref().filter(|k| !k.is_empty() && *k != item.kind) {
1027        return format!("{name} is not of kind {kind}");
1028    }
1029    if let Some(after) = state.work_store.work_deps_of(id).unwrap_or_default().into_iter().find(|a| !a.finished()) {
1030        return format!("{name} starts after {} \"{}\", which is {}", after.label(), after.title, after.state);
1031    }
1032    if item.attempts >= item.max_attempts {
1033        return format!("{name} has used all {} of its attempts", item.max_attempts);
1034    }
1035    if item.not_before.is_some_and(|t| t > now) {
1036        return format!("{name} can't be taken yet: its start time hasn't come");
1037    }
1038    format!("{name} moved meanwhile; look at it again with Tasks list")
1039}
1040
1041/// Finish a claimed task, for `complete` and `submit`: to Review when it needs
1042/// review (the agent can't accept its own work), else done. Answers with the
1043/// resulting state and the agent's next waiting task.
1044pub(super) async fn finish(
1045    state: &AppState,
1046    caller: Option<&Caller>,
1047    id: &str,
1048    agent_id: &str,
1049    attempt: i64,
1050    result: &str,
1051    update: Option<CardUpdate>,
1052) -> (StatusCode, Json<Value>) {
1053    let out = finish_task(state, caller, id, agent_id, attempt, result, update).await;
1054    // A finished task is a boundary: the caller's next work may start fresh
1055    // (SPEC_AGENT_SELF_COMPACTION_2026_10_23.md §3.5).
1056    if out.0.is_success() {
1057        if let Some(block) = super::actor::own_pane_by_token(&state.mstore, caller, agent_id) {
1058            crate::backend::context_reading::note_task_boundary(&block);
1059        }
1060        // The title the claim put on the agent's status line goes with the task, however it was handed in.
1061        super::agent_status_handlers::task_ended(state, agent_id, holder_uid(caller), id);
1062    }
1063    out
1064}
1065
1066async fn finish_task(
1067    state: &AppState,
1068    caller: Option<&Caller>,
1069    id: &str,
1070    agent_id: &str,
1071    attempt: i64,
1072    result: &str,
1073    update: Option<CardUpdate>,
1074) -> (StatusCode, Json<Value>) {
1075    let now = now_ms();
1076    let uid = holder_uid(caller);
1077    // A UI task that waits for the operator is handed in with media (submit and complete alike); the
1078    // holder's own call only, so a stale or foreign one still gets the usual conflict.
1079    if let Ok(Some(item)) = state.work_store.work_queue_get(id) {
1080        if holds(&item, agent_id, uid, attempt) {
1081            if let Some(why) = super::work_media::submit_refusal(state, id, item.attempts) {
1082                return (StatusCode::BAD_REQUEST, Json(json!({ "ok": false, "error": why })));
1083            }
1084        }
1085    }
1086    let review = state
1087        .work_store
1088        .work_board_get(id)
1089        .ok()
1090        .flatten()
1091        .is_some_and(|t| t.card.review_required);
1092    let before = state.work_store.work_queue_get(id).ok().flatten().map(|i| i.state).unwrap_or_default();
1093    let matched = if review {
1094        state.work_store.work_submit(id, agent_id, uid, attempt, result, now)
1095    } else {
1096        state.work_store.work_queue_complete(id, agent_id, uid, attempt, result, now)
1097    };
1098    match matched {
1099        Ok(Some(_)) => {
1100            if let Some(u) = update {
1101                let _ = state.work_store.work_card_ensure(id, now);
1102                let _ = state.work_store.work_card_update(id, &u, now);
1103            }
1104            // A result naming one PR links it, so the card shows it and its
1105            // merge can close the task, once GitHub says it is from the
1106            // branch the agent is on (kanban::prs).
1107            if let Ok(Some(t)) = state.work_store.work_board_get(id) {
1108                if let Some(pr) = t.card.pr_url.is_empty().then(|| pr_in_text(result, &t.card.repo)).flatten() {
1109                    let (repo, branch) = repo_of(state, caller_reg(state, caller).as_ref()).await;
1110                    link_if_from(id.to_string(), pr, repo, branch);
1111                }
1112            }
1113            let _ = state.work_store.work_card_set_question(id, "", now);
1114            let to = if review { work_state::REVIEW } else { work_state::DONE };
1115            record(state, id, agent_id, "agent", if review { "submitted" } else { "completed" }, &before, to, result);
1116            if to == work_state::DONE {
1117                // A spec done: its build's agent hears it can start.
1118                crate::backend::kanban::notify_unlocked(&state.work_store, &state.mstore, id);
1119            }
1120            super::work_queue::publish_changed(state);
1121            let holder_uid = state.work_store.work_queue_get(id).ok().flatten().map(|i| i.claimed_by_uid).unwrap_or_default();
1122            let next_uid = if uid.is_empty() { holder_uid } else { uid.to_string() };
1123            let mut body = json!({ "ok": true, "state": to });
1124            // An agent the operator switched off going on (`kanban:continue`)
1125            // is told of no next task.
1126            let goes_on = caller_reg(state, caller).is_none_or(|r| crate::backend::kanban::continues(&state.mstore, &r.block_id));
1127            if let (true, Some(obj), Value::Object(next)) = (goes_on, body.as_object_mut(), next_for(state, agent_id, &next_uid)) {
1128                obj.extend(next);
1129            }
1130            (StatusCode::OK, Json(body))
1131        }
1132        Ok(None) => conflict(),
1133        Err(e) => failed(e),
1134    }
1135}
1136
1137#[cfg(test)]
1138#[path = "work_tasks_tests.rs"]
1139mod tests;