Skip to main content

agentmux_srv/server/app_api/
kanban_act.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The moves `kanban.act` makes, one method each. A method answers its reply, or the error that
5//! refuses the move; `act_as` records that the board changed after any reply.
6
7use super::*;
8
9/// One `kanban.act` call: who makes it, what it asks and what the board holds.
10#[derive(Clone, Copy)]
11pub(super) struct Act<'a> {
12    pub(super) state: &'a AppState,
13    pub(super) req: &'a ActRequest,
14    pub(super) actor: &'a Actor,
15    /// The agents of this instance.
16    pub(super) regs: &'a [AgentRegistration],
17    /// The words that came with the move, cleaned.
18    pub(super) text: &'a str,
19    pub(super) now: i64,
20}
21
22/// How `release` / `reassign` ended: with the question that asks first, or with the task taken back.
23pub(super) enum TakeBack {
24    Asked(Value),
25    Done(Value),
26}
27
28/// How a task is written (`#12`, or `work#12` off the default board).
29fn task_ref(state: &AppState, id: &str) -> Option<String> {
30    crate::server::work_tasks::ref_of(state, id).map(|(r, _)| r)
31}
32
33impl Act<'_> {
34    /// The task the request names.
35    pub(super) fn task(&self) -> Result<BoardTask, String> {
36        let id = self.req.id.as_deref().ok_or("id is required")?;
37        let id = resolve_id(self.state, id);
38        let task = self.state.work_store.work_board_get(&id).map_err(|e| e.to_string())?.ok_or_else(|| "no such task".to_string())?;
39        // An agent sees only the boards whose agent list has it; the operator sees them all.
40        if !self.actor.is_operator {
41            if let Some((board, _)) = self.state.work_store.work_task_board(&task.item.id).map_err(|e| e.to_string())? {
42                if !board.visible_to(&self.actor.name, &self.actor.uid) {
43                    return Err("no such task".to_string());
44                }
45            }
46        }
47        Ok(task)
48    }
49
50    pub(super) fn create(&self) -> Result<Value, String> {
51        let Act { state, req, regs, now, .. } = *self;
52        let title = req.title.as_deref().map(str::trim).filter(|t| !t.is_empty()).ok_or("a title is required")?;
53        let payload = req.payload.as_deref().map(str::trim).filter(|p| !p.is_empty()).unwrap_or(title);
54        let after = resolve_after(state, req.after.as_deref().unwrap_or_default())?;
55        Ok(match req.first.as_deref().map(str::trim).filter(|f| !f.is_empty()) {
56            // "Spec first" (§5.1): a spec (or research) task, and a build
57            // that starts after it, for the same agent.
58            Some(first) => {
59                if !crate::backend::kanban::is_research_kind(first) {
60                    return Err("first: \"spec\" or \"research\"".into());
61                }
62                let first = first.to_ascii_lowercase();
63                let (spec_id, spec_num) =
64                    create_one(state, regs, req, &kanban::pair_title(&first, title), &kanban::spec_payload(&first, payload), &first, &after, now)?;
65                let (build_id, build_num) = create_one(
66                    state,
67                    regs,
68                    req,
69                    &kanban::pair_title("build", title),
70                    &kanban::build_payload(payload),
71                    "build",
72                    std::slice::from_ref(&spec_id),
73                    now,
74                )?;
75                json!({
76                    "ok": true, "id": spec_id, "num": spec_num, "ref": task_ref(state, &spec_id),
77                    "build_id": build_id, "build_num": build_num, "build_ref": task_ref(state, &build_id),
78                })
79            }
80            None => {
81                let kind = req.kind.clone().unwrap_or_default();
82                let (id, num) = create_one(state, regs, req, title, payload, &kind, &after, now)?;
83                json!({ "ok": true, "id": id, "num": num, "ref": task_ref(state, &id) })
84            }
85        })
86    }
87
88    pub(super) fn edit(&self) -> Result<Value, String> {
89        let Act { state, req, actor, now, .. } = *self;
90        if req.agent.is_some() {
91            return Err("edit doesn't change who a task is for: use move with a target agent. Nothing was changed.".into());
92        }
93        let store = &state.work_store;
94        let t = self.task()?;
95        let id = &t.item.id;
96        // First: a refused list changes nothing.
97        let payload = req.payload.as_deref().map(crate::server::work_tasks::payload_text).transpose()?;
98        let after = req.after.as_ref().map(|given| resolve_after(state, given)).transpose()?;
99        if let Some(after) = &after {
100            if let Some(why) = store.work_deps_set(id, after).map_err(|e| e.to_string())? {
101                return Err(why);
102            }
103        }
104        store
105            .work_task_edit(
106                id,
107                req.title.as_deref().map(clean).as_deref(),
108                payload.as_deref(),
109                req.kind.as_deref(),
110                req.priority,
111                now,
112            )
113            .map_err(|e| e.to_string())?;
114        // Words an agent put in the payload are the agent's: a later start quotes them under its name
115        // instead of delivering them as the operator's.
116        let author = (!actor.is_operator && req.payload.is_some()).then_some(actor.name.as_str());
117        store.work_card_edit(id, None, req.review, req.repo.as_deref(), author, now).map_err(|e| e.to_string())?;
118        let mut body = String::new();
119        if let Some(after) = after {
120            body = after_words(store, &after);
121        }
122        record(state, id, &actor.name, actor.kind(), "edited", &t.item.state, &t.item.state, &body);
123        Ok(json!({ "ok": true }))
124    }
125
126    /// Refuse a task for an agent its board's agent list leaves out: it would be handed a payload
127    /// it can't see on the board.
128    fn receiver_sees_board(&self, work_id: &str, agent: &str, uid: &str) -> Result<(), String> {
129        match self.state.work_store.work_task_board(work_id).map_err(|e| e.to_string())? {
130            Some((b, _)) if !b.visible_to(agent, uid) => Err(format!("{agent} isn't on board {}: its agent list leaves {agent} out", b.slug)),
131            _ => Ok(()),
132        }
133    }
134
135    /// Move the task to another board (`board`): a new task there with the next number, the original
136    /// closed with a pointer. An agent sees only the boards its agent list has it on.
137    fn move_to_board(&self, to: &str) -> Result<Value, String> {
138        let Act { state, req, actor, now, .. } = *self;
139        let t = self.task()?;
140        let who = (!actor.is_operator).then_some((actor.name.as_str(), actor.uid.as_str()));
141        crate::server::work_tasks::pick_board(state, Some(to), who, true)?;
142        if let Some((from, _)) = state.work_store.work_task_board(&t.item.id).map_err(|e| e.to_string())? {
143            if who.is_some_and(|(a, u)| !from.visible_to(a, u)) {
144                return Err("no such task".into());
145            }
146        }
147        let moved = state
148            .work_store
149            .work_task_move(&t.item.id, to, &actor.name, req.drop_deps == Some(true), now)
150            .map_err(|e| e.to_string())?;
151        Ok(json!({
152            "ok": true, "id": moved.id, "ref": moved.to_ref, "from": moved.from_ref, "board": moved.board, "num": moved.num,
153            "dropped_dependencies": moved.dropped_deps, "target_cleared": moved.target_cleared,
154        }))
155    }
156
157    pub(super) fn move_task(&self) -> Result<Value, String> {
158        let Act { state, req, actor, regs, now, .. } = *self;
159        if let Some(to) = req.board.as_deref().map(str::trim).filter(|b| !b.is_empty()) {
160            return self.move_to_board(to);
161        }
162        let store = &state.work_store;
163        let t = self.task()?;
164        let id = &t.item.id;
165        if let Some(agent) = req.agent.as_deref() {
166            let (name, uid) = target_of(state, regs, agent);
167            if !name.is_empty() {
168                self.receiver_sees_board(&t.item.id, &name, &uid)?;
169            }
170            if !store.work_assign(id, &name, &uid, now).map_err(|e| e.to_string())? {
171                return Err("only a waiting task can be moved to another agent".into());
172            }
173            crate::server::task_flow_notes::note(state, id, crate::backend::task_flow::TaskFlowKind::Reassigned, &actor.name, &name);
174            let to = if name.is_empty() { "anyone".to_string() } else { name };
175            record(state, id, &actor.name, actor.kind(), "assigned", &t.item.state, &t.item.state, &format!("for {to}"));
176        }
177        match req.hold {
178            Some(true) => {
179                if let Some(m) = store.work_hold(id, now).map_err(|e| e.to_string())? {
180                    record(state, id, &actor.name, actor.kind(), "held", &m.from, &m.to, "");
181                }
182            }
183            Some(false) => {
184                if let Some(m) = store.work_unhold(id, now).map_err(|e| e.to_string())? {
185                    record(state, id, &actor.name, actor.kind(), "unheld", &m.from, &m.to, "");
186                }
187            }
188            None => {}
189        }
190        if let Some(rank) = req.rank {
191            store.work_card_edit(id, Some(rank), None, None, None, now).map_err(|e| e.to_string())?;
192        }
193        Ok(json!({ "ok": true }))
194    }
195
196    pub(super) async fn start(&self) -> Result<Value, String> {
197        let Act { state, req, actor, regs, now, .. } = *self;
198        let store = &state.work_store;
199        let t = self.task()?;
200        let agent = req.agent.as_deref().ok_or("start: which agent?")?;
201        let reg = agent_named(regs, agent).ok_or_else(|| format!("no agent named {agent} here"))?;
202        if !alive(&reg) {
203            return Err(format!("{} isn't running", reg.agent_id));
204        }
205        let uid = reg.uid.clone().unwrap_or_default();
206        self.receiver_sees_board(&t.item.id, &reg.agent_id, &uid)?;
207        let started = store
208            .work_start_for(&t.item.id, &reg.agent_id, &uid, now, LEASE_MS)
209            .map_err(|e| e.to_string())?
210            .ok_or("only a waiting task can be started")?;
211        let fresh = store.work_board_get(&t.item.id).map_err(|e| e.to_string())?.ok_or("no such task")?;
212        if let Err(e) = tell(state, &reg, actor, start_text(&fresh, started.attempts, actor)).await {
213            // Not delivered: put it back as it was, its attempt not used,
214            // rather than leave it held by an agent that never heard of it.
215            let _ = store.work_unstart(
216                &t.item.id,
217                &reg.agent_id,
218                started.attempts,
219                &t.item.state,
220                &t.item.target_agent,
221                &t.item.target_agent_uid,
222                now,
223            );
224            record(state, &t.item.id, &actor.name, actor.kind(), "start_failed", work_state::CLAIMED, &t.item.state, &format!("couldn't reach {}", reg.agent_id));
225            changed(state);
226            return Err(format!("couldn't reach {}: {e}", reg.agent_id));
227        }
228        record(state, &t.item.id, &actor.name, actor.kind(), "started", &t.item.state, work_state::CLAIMED, &format!("on {}", reg.agent_id));
229        crate::server::task_flow_notes::note(state, &t.item.id, crate::backend::task_flow::TaskFlowKind::Started, &actor.name, &reg.agent_id);
230        Ok(json!({ "ok": true, "attempt": started.attempts }))
231    }
232
233    pub(super) async fn answer(&self) -> Result<Value, String> {
234        let Act { state, actor, regs, text, now, .. } = *self;
235        let store = &state.work_store;
236        let t = self.task()?;
237        if text.is_empty() {
238            return Err("the answer is empty".into());
239        }
240        if t.item.state != work_state::BLOCKED {
241            return Err("this task isn't waiting on a question".into());
242        }
243        let reg = holder_of(regs, &t.item).cloned().filter(alive).ok_or("its agent isn't running")?;
244        let msg = format!(
245            "Answer{} on task {} \"{}\": {text}\n\nCarry on with it (id {}, attempt {}).",
246            if actor.is_operator { String::new() } else { format!(" from {}", quote_in_system_note(&actor.name)) },
247            t.card.name(),
248            quote_in_system_note(&t.item.title),
249            t.card.id_arg(),
250            t.item.attempts
251        );
252        tell(state, &reg, actor, msg).await.map_err(|e| format!("couldn't reach {}: {e}", reg.agent_id))?;
253        store.work_answered(&t.item.id, now, LEASE_MS).map_err(|e| e.to_string())?;
254        store.work_card_set_question(&t.item.id, "", now).map_err(|e| e.to_string())?;
255        record(state, &t.item.id, &actor.name, actor.kind(), "answered", work_state::BLOCKED, work_state::CLAIMED, text);
256        Ok(json!({ "ok": true }))
257    }
258
259    // Take back a leader's acceptance (the spec's D5): Done to Review, for a week. What
260    // the acceptance set off (a started build, a merged PR) stays as it is.
261    pub(super) fn reopen(&self) -> Result<Value, String> {
262        let Act { state, actor, text, now, .. } = *self;
263        let store = &state.work_store;
264        let t = self.task()?;
265        let accepts = store.work_delegate_accepts(now - crate::backend::kanban_delegate::REOPEN_WINDOW_MS).map_err(|e| e.to_string())?;
266        if !accepts.contains_key(&t.item.id) {
267            return Err("only a task an agent accepted, in the last 7 days, can be reopened".into());
268        }
269        let m = store.work_reopen(&t.item.id, now).map_err(|e| e.to_string())?.ok_or("only a done task can be reopened")?;
270        record(state, &t.item.id, &actor.name, actor.kind(), "reopened", &m.from, &m.to, text);
271        Ok(json!({ "ok": true }))
272    }
273
274    pub(super) fn cancel(&self) -> Result<Value, String> {
275        let Act { state, req, actor, text, now, .. } = *self;
276        let store = &state.work_store;
277        let t = self.task()?;
278        // A cancelled spec approves nothing: what waits on it is
279        // cancelled too, or put on hold for the operator (§6). A
280        // cancelled task counts as finished for what starts after it, so
281        // its waiting builds go on hold *before* it is cancelled: until
282        // then the unfinished spec keeps them from being claimed, and no
283        // claim can slip in between.
284        let research = crate::backend::kanban::is_research_kind(&t.item.kind);
285        let why = format!("its {} {} was cancelled", t.item.kind.trim().to_ascii_lowercase(), t.card.name());
286        let mut held: Vec<String> = Vec::new();
287        let mut were_held: Vec<String> = Vec::new();
288        if research {
289            for f in store.work_followers_of(&t.item.id).map_err(|e| e.to_string())? {
290                match f.state.as_str() {
291                    work_state::OPEN => {
292                        if store.work_hold(&f.id, now).map_err(|e| e.to_string())?.is_some() {
293                            held.push(f.id);
294                        }
295                    }
296                    work_state::HELD => were_held.push(f.id),
297                    _ => {}
298                }
299            }
300        }
301        if !store.work_queue_cancel(&t.item.id, text, now).map_err(|e| e.to_string())? {
302            // Nothing to cancel: let the builds go as they were.
303            for id in &held {
304                let _ = store.work_unhold(id, now);
305            }
306            return Err("it is already finished".into());
307        }
308        record(state, &t.item.id, &actor.name, actor.kind(), "cancelled", &t.item.state, work_state::CANCELLED, text);
309        let mut followers = 0;
310        if req.followers.as_deref() == Some("hold") {
311            for id in &held {
312                record(state, id, &actor.name, actor.kind(), "held", work_state::OPEN, work_state::HELD, &why);
313                followers += 1;
314            }
315        } else {
316            for id in held.iter().chain(were_held.iter()) {
317                if store.work_queue_cancel(id, &why, now).map_err(|e| e.to_string())? {
318                    record(state, id, &actor.name, actor.kind(), "cancelled", "", work_state::CANCELLED, &why);
319                    followers += 1;
320                }
321            }
322        }
323        Ok(json!({ "ok": true, "followers": followers }))
324    }
325
326    pub(super) fn retry(&self) -> Result<Value, String> {
327        let Act { state, actor, now, .. } = *self;
328        let store = &state.work_store;
329        let t = self.task()?;
330        let m = store.work_retry(&t.item.id, now).map_err(|e| e.to_string())?.ok_or("only a failed task can be retried")?;
331        record(state, &t.item.id, &actor.name, actor.kind(), "retried", &m.from, &m.to, "");
332        Ok(json!({ "ok": true }))
333    }
334
335    pub(super) async fn track(&self) -> Result<Value, String> {
336        let Act { state, req, regs, now, .. } = *self;
337        let store = &state.work_store;
338        let block = req.block_id.as_deref().ok_or("track: which agent pane?")?;
339        let reg = regs.iter().find(|r| r.block_id == block).cloned().ok_or("that pane has no agent")?;
340        let facts = {
341            let mstore = state.mstore.clone();
342            let r = reg.clone();
343            let channel = crate::backend::work_facts::cross_channel::own_channel();
344            tokio::task::spawn_blocking(move || crate::backend::work_facts::collect_local(&mstore, &[r], &channel))
345                .await
346                .unwrap_or_default()
347                .into_iter()
348                .next()
349        };
350        let title = req
351            .title
352            .as_deref()
353            .map(str::trim)
354            .filter(|t| !t.is_empty())
355            .map(str::to_string)
356            .or_else(|| facts.as_ref().and_then(|f| f.goal.clone()))
357            .unwrap_or_else(|| format!("{}'s current work", reg.agent_id));
358        let title: String = clean(&title).chars().take(200).collect();
359        let uid = reg.uid.clone().unwrap_or_default();
360        let item = WorkItem {
361            id: Uuid::new_v4().to_string(),
362            title: title.clone(),
363            payload: title.clone(),
364            kind: String::new(),
365            target_agent: reg.agent_id.clone(),
366            target_group: String::new(),
367            priority: 0,
368            state: String::new(),
369            claimed_by: String::new(),
370            target_agent_uid: uid.clone(),
371            claimed_by_uid: String::new(),
372            claim_expires: None,
373            attempts: 0,
374            max_attempts: 3,
375            created_by: OPERATOR.into(),
376            created_by_uid: String::new(),
377            created_at: now,
378            updated_at: now,
379            not_before: None,
380            result: String::new(),
381        };
382        store.work_queue_enqueue(&item).map_err(|e| e.to_string())?;
383        let card = NewCard {
384            board: String::new(),
385            repo: facts.as_ref().and_then(|f| f.repo_key()).unwrap_or_default(),
386            branch: facts.as_ref().and_then(|f| f.branch.clone()).unwrap_or_default(),
387            review_required: true,
388            requested_by: OPERATOR.into(),
389            requested_by_kind: requested::OPERATOR.into(),
390            request_text: String::new(),
391            filed_by: String::new(),
392        };
393        let num = store.work_card_create(&item.id, &card, now).map_err(|e| e.to_string())?;
394        let started = store
395            .work_start_for(&item.id, &reg.agent_id, &uid, now, LEASE_MS)
396            .map_err(|e| e.to_string())?
397            .ok_or("couldn't take it for the agent")?;
398        record(state, &item.id, OPERATOR, OPERATOR, "tracked", "", work_state::CLAIMED, &format!("{}'s work", reg.agent_id));
399        let note = format!(
400            "[AgentMux] The operator is following your current work in the Kanban as task #{num} \"{}\". \
401             When it's done, hand it in with Tasks submit (id {num}, attempt {}).",
402            quote_in_system_note(&title),
403            started.attempts
404        );
405        let target = if uid.is_empty() { reg.agent_id.clone() } else { uid };
406        // Informational: a session gone cold gets it with its next turn rather than waking.
407        let extra = state.config_watcher.get_settings().extra;
408        if let Err(e) = crate::backend::cold_hold::note_or_wait_if_cold(&state.mstore, &extra, &reg.block_id, &target, &format!("track:{num}"), &note) {
409            tracing::info!(error = %e, "kanban: track note not delivered");
410        }
411        Ok(json!({ "ok": true, "num": num }))
412    }
413
414    pub(super) async fn take_back(&self) -> Result<TakeBack, String> {
415        let Act { state, req, actor, regs, text, now } = *self;
416        let store = &state.work_store;
417        let t = self.task()?;
418        if !matches!(t.item.state.as_str(), work_state::CLAIMED | work_state::BLOCKED) {
419            return Err("only a task an agent holds can be taken back".into());
420        }
421        let reassign = req.action == "reassign";
422        // `reassign` names who it goes to: an agent (running here or not), or
423        // anyone when empty. `release` leaves who it is for as it was.
424        let retarget = if reassign {
425            let agent = req.agent.as_deref().ok_or("reassign: to which agent? (empty for anyone)")?.trim();
426            Some(target_of(state, regs, agent))
427        } else {
428            None
429        };
430        // Work the holder did lives on its branch or PR; taking the task back
431        // doesn't move it. The operator confirms having read that.
432        let links: Vec<String> = [("a branch", &t.card.branch), ("a PR", &t.card.pr_url)]
433            .iter()
434            .filter(|(_, v)| !v.trim().is_empty())
435            .map(|(what, v)| format!("{what} ({})", v.trim()))
436            .collect();
437        if !links.is_empty() && req.confirm != Some(true) {
438            return Ok(TakeBack::Asked(json!({
439                "ok": false,
440                "confirm": format!(
441                    "It has {}. That work stays where it is, and whoever gets the task has to pick it up from there. Take it back anyway?",
442                    links.join(" and ")
443                ),
444            })));
445        }
446        let holder = if t.item.claimed_by.is_empty() { "its agent".to_string() } else { t.item.claimed_by.clone() };
447        let reason = if text.is_empty() {
448            format!("taken back from {holder}")
449        } else {
450            format!("taken back from {holder}: {text}")
451        };
452        let back = store
453            .work_take_back(&t.item.id, retarget.as_ref().map(|(a, u)| (a.as_str(), u.as_str())), &reason, now)
454            .map_err(|e| e.to_string())?
455            .ok_or("it moved meanwhile")?;
456        let to = match &retarget {
457            Some((name, _)) if !name.is_empty() => format!("; now for {name}"),
458            Some(_) => "; now for anyone".to_string(),
459            None => String::new(),
460        };
461        let kind = if reassign { "reassigned" } else { "taken_back" };
462        record(state, &t.item.id, &actor.name, actor.kind(), kind, &t.item.state, work_state::OPEN, &format!("{reason}{to}"));
463        if let Some((name, _)) = &retarget {
464            crate::server::task_flow_notes::note(state, &t.item.id, crate::backend::task_flow::TaskFlowKind::Reassigned, &actor.name, name);
465        }
466        // Cancel tells nobody, so the old holder is told here: it may still be
467        // working on the task, or be about to hand it in.
468        let note = format!(
469            "[AgentMux] {} took task {} \"{}\" back from you. Stop working on it and don't hand it in: \
470             your claim (attempt {}) is closed.{}",
471            actor.who(),
472            t.card.name(),
473            quote_in_system_note(&t.item.title),
474            t.item.attempts,
475            if text.is_empty() { String::new() } else { format!(" Reason given: {}", quote_in_system_note(text)) }
476        );
477        let target = if t.item.claimed_by_uid.is_empty() { t.item.claimed_by.clone() } else { t.item.claimed_by_uid.clone() };
478        if !target.is_empty() {
479            if let Err(e) = crate::backend::reactive::get_global_handler().deliver_system_note(&target, &note) {
480                tracing::info!(error = %e, "kanban: take-back note not delivered");
481            }
482        }
483        Ok(TakeBack::Done(json!({ "ok": true, "id": back.id })))
484    }
485
486    pub(super) fn media_remove(&self) -> Result<Value, String> {
487        let Act { state, req, actor, text, now, .. } = *self;
488        let store = &state.work_store;
489        let t = self.task()?;
490        let media_id = req.media_id.ok_or("media_remove: media_id is required")?;
491        let gone = store
492            .work_media_remove(&t.item.id, media_id, &actor.name, now)
493            .map_err(|e| e.to_string())?
494            .ok_or("no such file on this task, or it is already removed")?;
495        // The bytes go when no task names them.
496        if !store.work_media_named(&gone.sha256).unwrap_or(true) {
497            if let Some(root) = crate::backend::task_media::default_root() {
498                crate::backend::task_media::remove_content(&root, &gone.sha256, &gone.mime);
499            }
500        }
501        record(state, &t.item.id, &actor.name, actor.kind(), "media_removed", &gone.name, "", text);
502        Ok(json!({ "ok": true }))
503    }
504
505    pub(super) fn ui_change(&self) -> Result<Value, String> {
506        let Act { state, req, actor, text, now, .. } = *self;
507        let store = &state.work_store;
508        let t = self.task()?;
509        let flag = req.ui_change.ok_or("ui_change: true or false is required")?;
510        store.work_ui_set(&t.item.id, Some(flag), None, 0, now).map_err(|e| e.to_string())?;
511        record(state, &t.item.id, &actor.name, actor.kind(), "ui_change", if flag { "yes" } else { "no" }, "", text);
512        Ok(json!({ "ok": true }))
513    }
514
515    /// The pull request a `pr_*` move names: `pr` (an address or `owner/repo#12`), or `repo` and `number`;
516    /// a bare number is taken in the card's own repository.
517    fn pr_named(&self, card_repo: &str) -> Result<(String, u64), String> {
518        let req = self.req;
519        if let (Some(repo), Some(number)) = (req.repo.as_deref(), req.number) {
520            let repo = crate::backend::storage::work_card_prs::github_repo(repo).ok_or("repo is not a GitHub repository")?;
521            if number == 0 {
522                return Err("number is not a pull request".to_string());
523            }
524            return Ok((repo, number));
525        }
526        let pr = req.pr.as_deref().map(str::trim).filter(|p| !p.is_empty()).ok_or("pr (an address or owner/repo#12) is required")?;
527        crate::backend::storage::work_card_prs::parse_pr_ref(pr, card_repo).ok_or_else(|| "pr is not a pull request address".to_string())
528    }
529
530    /// Put a pull request on a task's card: the operator's own link, which a later report never undoes.
531    pub(super) fn pr_link(&self) -> Result<Value, String> {
532        use crate::backend::storage::work_card_prs::{pr_url, PrSource};
533        let Act { state, actor, text, now, .. } = *self;
534        let t = self.task()?;
535        let (repo, number) = self.pr_named(&t.card.repo)?;
536        let store = &state.work_store;
537        let changed = store.work_card_pr_link(&t.item.id, &repo, number, PrSource::Person, now).map_err(|e| e.to_string())?;
538        // It was on the list of pull requests no card had, if it came from there.
539        let _ = store.work_pr_unmatched_remove(&repo, number);
540        record(state, &t.item.id, &actor.name, actor.kind(), "pr_linked", &pr_url(&repo, number), "", text);
541        Ok(json!({ "ok": true, "changed": changed }))
542    }
543
544    /// Take a pull request off a task's card. It stays recorded, so no later report puts it back.
545    pub(super) fn pr_unlink(&self) -> Result<Value, String> {
546        use crate::backend::storage::work_card_prs::pr_url;
547        let Act { state, actor, text, now, .. } = *self;
548        let t = self.task()?;
549        let (repo, number) = self.pr_named(&t.card.repo)?;
550        let changed = state.work_store.work_card_pr_unlink(&t.item.id, &repo, number, now).map_err(|e| e.to_string())?;
551        if changed {
552            record(state, &t.item.id, &actor.name, actor.kind(), "pr_unlinked", &pr_url(&repo, number), "", text);
553        }
554        Ok(json!({ "ok": true, "changed": changed }))
555    }
556
557    /// The pull requests no card has, newest first.
558    pub(super) fn pr_unmatched(&self) -> Result<Value, String> {
559        let unmatched = self.state.work_store.work_pr_unmatched_list().map_err(|e| e.to_string())?;
560        Ok(json!({ "ok": true, "unmatched": unmatched }))
561    }
562
563    /// Take a pull request off the unmatched list without linking it.
564    pub(super) fn pr_dismiss(&self) -> Result<Value, String> {
565        let (repo, number) = self.pr_named("")?;
566        let gone = self.state.work_store.work_pr_unmatched_remove(&repo, number).map_err(|e| e.to_string())?;
567        Ok(json!({ "ok": true, "changed": gone }))
568    }
569}