1use std::path::Path;
27
28use anyhow::{Context, Result, bail, ensure};
29
30use crate::queue::{Queue, Task, TaskStatus};
31use crate::talk::{Talk, Talks};
32
33#[cfg(any(unix, windows))]
34pub(crate) mod bridge;
35
36#[derive(Debug, serde::Serialize, serde::Deserialize)]
39#[serde(tag = "operation", deny_unknown_fields)]
40pub enum Operation {
41 Resume {
43 run: String,
45 },
46 Hold {
48 task: String,
50 reason: String,
52 },
53 Release {
55 task: String,
57 },
58 Retry {
60 task: String,
62 title: Option<String>,
64 instruction: String,
66 },
67 RerunChecks {
69 run: String,
71 request: String,
73 head: String,
75 workflows: Vec<String>,
77 },
78 Abandon {
80 run: String,
82 quote: Option<String>,
84 },
85}
86
87pub async fn dispatch(
90 queue: &Queue,
91 home: &Path,
92 talks: &Talks,
93 talk: &str,
94 operation: Operation,
95) -> Result<String> {
96 #[cfg(unix)]
97 if std::env::var_os(bridge::CHANNEL_ENV).is_some() {
98 return bridge::request(&operation);
99 }
100 #[cfg(windows)]
101 if std::env::var_os(bridge::CHANNEL_ENV).is_some() {
102 return bridge::request(&operation).await;
103 }
104 execute(queue, home, talks, talk, operation).await
105}
106
107async fn execute(
108 queue: &Queue,
109 home: &Path,
110 talks: &Talks,
111 talk: &str,
112 operation: Operation,
113) -> Result<String> {
114 authorize(talks, talk, crate::queue::CHAT_NODE)?;
115 ensure!(
116 !crate::consult::pending_consults(&crate::ask::Questions::at(home.join("questions")), talk),
117 "task control is excluded during consultation"
118 );
119 Ok(match operation {
120 Operation::Resume { run } => {
121 let t = resume(queue, home, talk, &run)?;
122 format!(
123 "{}; the loop (`magi serve`) resumes the run under its execution lease",
124 describe(&t, "resume queued for")
125 )
126 }
127 Operation::Hold { task, reason } => describe(&hold(queue, talk, &task, &reason)?, "held"),
128 Operation::Release { task } => describe(&release(queue, talk, &task)?, "released"),
129 Operation::Retry {
130 task,
131 title,
132 instruction,
133 } => describe(
134 &retry(queue, talk, &task, title, &instruction)?,
135 "retry queued for",
136 ),
137 Operation::RerunChecks {
138 run,
139 request,
140 head,
141 workflows,
142 } => {
143 let ids = rerun_checks(queue, home, talk, &run, &request, &head, &workflows).await?;
144 format!("requested a rerun of workflow run(s) {}", ids.join(", "))
145 }
146 Operation::Abandon { run, quote } => {
147 abandon(queue, talks, home, talk, &run, quote.as_deref())?;
148 format!("abandoned run {run}")
149 }
150 })
151}
152
153pub fn abandon_instruction(run: &str) -> String {
155 format!("abandon-run: {run}")
156}
157
158pub fn authorize(talks: &Talks, run: &str, node: &str) -> Result<Talk> {
160 if node != crate::queue::CHAT_NODE || run.trim().is_empty() {
161 bail!("task control requires MAGI_NODE=chat and MAGI_RUN from a standing chat");
162 }
163 let id = crate::chat_watch::authorize(talks, run, node)?;
164 talks.get(&id)
165}
166
167fn owned(task: &Task, talk: &str) -> bool {
169 task.filed_by_chat() == Some(talk)
170}
171
172pub fn owned_task(queue: &Queue, talk: &str, reference: &str) -> Result<Task> {
174 let id = queue.resolve_id(reference)?;
175 let task = queue.get(&id)?;
176 ensure!(
177 owned(&task, talk),
178 "task {} was not filed by this conversation",
179 task.short()
180 );
181 Ok(task)
182}
183
184pub fn owned_run_task(queue: &Queue, talk: &str, run: &str) -> Result<Task> {
186 ensure!(
187 crate::run::is_run_id(run),
188 "an execution command needs the full run id"
189 );
190 queue
191 .list()
192 .into_iter()
193 .find(|t| owned(t, talk) && t.runs.iter().any(|r| r == run))
194 .with_context(|| format!("run {run} belongs to no task filed by this conversation"))
195}
196
197fn claimed(queue: &Queue, id: &str, talk: &str) -> Result<(crate::queue::Claim, Task)> {
198 let claim = queue
199 .claim(id)
200 .with_context(|| format!("task {id} is claimed by a running daemon"))?;
201 let task = queue.get(id)?;
202 ensure!(owned(&task, talk), "task is not filed by this conversation");
205 Ok((claim, task))
206}
207
208pub fn hold(queue: &Queue, talk: &str, reference: &str, reason: &str) -> Result<Task> {
210 let id = owned_task(queue, talk, reference)?.id;
211 let (_claim, mut task) = claimed(queue, &id, talk)?;
212 let reason = reason.trim();
213 task.hold_manual((!reason.is_empty()).then(|| reason.to_owned()));
214 queue.put(&mut task)?;
215 Ok(task)
216}
217
218pub fn release(queue: &Queue, talk: &str, reference: &str) -> Result<Task> {
221 let id = owned_task(queue, talk, reference)?.id;
222 let (_claim, mut task) = claimed(queue, &id, talk)?;
223 task.release_operator("chat", None);
224 queue.put(&mut task)?;
225 Ok(task)
226}
227
228pub fn retry(
233 queue: &Queue,
234 talk: &str,
235 reference: &str,
236 title: Option<String>,
237 instruction: &str,
238) -> Result<Task> {
239 ensure!(
240 !instruction.trim().is_empty(),
241 "the new instruction is empty"
242 );
243 let id = owned_task(queue, talk, reference)?.id;
244 let (_claim, mut task) = claimed(queue, &id, talk)?;
245 let title = title.unwrap_or_else(|| crate::queue::title_from(instruction, 72));
246 task.edit(title, instruction.to_owned())?;
247 task.release_operator("chat", None);
248 queue.put(&mut task)?;
249 Ok(task)
250}
251
252pub fn resume(queue: &Queue, home: &Path, talk: &str, run: &str) -> Result<Task> {
255 let task = owned_run_task(queue, talk, run)?;
256 ensure!(
257 task.runs.last().map(String::as_str) == Some(run),
258 "only the task's latest run can be resumed"
259 );
260 crate::resume::validate(home, run)?;
261 ensure!(
262 crate::resume::pin_queued(queue, run, None, None)?,
263 "no queued task owns run {run}"
264 );
265 queue.get(&task.id)
266}
267
268pub async fn rerun_checks(
270 queue: &Queue,
271 home: &Path,
272 talk: &str,
273 run: &str,
274 request: &str,
275 head: &str,
276 workflows: &[String],
277) -> Result<Vec<String>> {
278 owned_run_task(queue, talk, run)?;
279 let state = crate::run::RunState::load_under(run, home)?;
280 let pr = &state
281 .pr
282 .as_ref()
283 .context("the run recorded no pull request")?
284 .url;
285 ensure!(
286 crate::ask::valid_asset_name(request),
287 "request must be a safe filename of at most 64 bytes"
288 );
289 let dir = home.join("chat-controls").join(talk);
290 std::fs::create_dir_all(&dir)?;
291 let lock = std::fs::OpenOptions::new()
292 .create(true)
293 .truncate(false)
294 .write(true)
295 .open(dir.join(format!("{request}.lock")))?;
296 crate::pr_head::try_lock_file(&lock)?;
297 let path = dir.join(format!("{request}.json"));
298 let action = serde_json::json!({
299 "run": run, "repo": state.repo, "pr": pr, "head": head, "runs": workflows
300 });
301 if path.exists() {
302 let prior: serde_json::Value = serde_json::from_slice(&std::fs::read(&path)?)?;
303 ensure!(
304 prior["action"] == action,
305 "request ID already binds a different operation"
306 );
307 ensure!(
308 prior["status"] == "applied",
309 "previous request has an uncertain result; inspect its receipt before a new request"
310 );
311 return Ok(workflows.to_vec());
312 }
313 let record = |status: &str| -> Result<()> {
314 let tmp = path.with_extension("tmp");
315 std::fs::write(
316 &tmp,
317 serde_json::to_vec(&serde_json::json!({
318 "action": action, "status": status
319 }))?,
320 )?;
321 std::fs::rename(tmp, &path)?;
322 Ok(())
323 };
324 let operation = format!("chat:{talk}:{request}");
325 crate::daemon::rerun_checks_once(home, &operation, &state.repo, pr, head, workflows, || {
326 record("started")
327 })
328 .await?;
329 record("applied")?;
330 Ok(workflows.to_vec())
331}
332
333pub fn abandon(
338 queue: &Queue,
339 talks: &Talks,
340 home: &Path,
341 talk_id: &str,
342 run: &str,
343 quote: Option<&str>,
344) -> Result<()> {
345 owned_run_task(queue, talk_id, run)?;
346 let _evidence = talks.answer_guard()?;
347 let talk = talks.get(talk_id)?;
348 let expected = abandon_instruction(run);
349 let latest = crate::consult::latest_owner_instruction(&talk);
350 ensure!(
351 latest == Some(expected.as_str()) && quote == Some(expected.as_str()),
352 "abandoning a run needs individual owner confirmation: the owner's latest persisted \
353 message must be exactly `{expected}` and --quote must repeat it"
354 );
355 crate::driver::abandon_proven_dead(home, run)
356}
357
358pub fn describe(task: &Task, what: &str) -> String {
360 let status = match task.status {
361 TaskStatus::Queued => "queued",
362 _ => task.status.as_str(),
363 };
364 format!("{what} {} {} ({status})", task.short(), task.title)
365}
366
367#[cfg(test)]
368mod tests {
369 use super::*;
370 use crate::queue::Source;
371 use jiff::Timestamp;
372
373 fn talk(talks: &Talks, id: &str) -> Talk {
374 let mut t: Talk = serde_json::from_value(serde_json::json!({
375 "schema":1,"id":id,"repo":".","agent":"worker","status":"open","turns":[],
376 "created_at":Timestamp::now(),"updated_at":Timestamp::now(),
377 "seat":crate::agent::SeatState::new("talk","worker",1)
378 }))
379 .unwrap();
380 talks.put(&mut t).unwrap();
381 t
382 }
383
384 fn filed(queue: &Queue, talk: &str, text: &str) -> Task {
385 let mut t = Task::new(
386 text.into(),
387 text.into(),
388 ".".into(),
389 Source::Agent {
390 run: talk.into(),
391 node: crate::queue::CHAT_NODE.into(),
392 },
393 );
394 queue.put(&mut t).unwrap();
395 t
396 }
397
398 #[test]
399 fn only_the_chat_seat_of_an_open_talk_is_authorized() {
400 let tmp = tempfile::tempdir().unwrap();
401 let talks = Talks::at(tmp.path().join("talks"));
402 let t = talk(&talks, "talk-a");
403 assert!(authorize(&talks, &t.id, "chat").is_ok());
404 assert!(authorize(&talks, &t.id, "deputy").is_err());
405 assert!(authorize(&talks, &t.id, "").is_err());
406 assert!(authorize(&talks, "", "chat").is_err());
407 assert!(
408 authorize(&talks, "talk-", "chat").is_err(),
409 "prefix is not an id"
410 );
411 }
412
413 #[test]
414 fn tasks_of_other_origins_are_out_of_scope() {
415 let tmp = tempfile::tempdir().unwrap();
416 let queue = Queue::at(tmp.path().join("queue"));
417 let mine = filed(&queue, "talk-a", "mine");
418 let theirs = filed(&queue, "talk-b", "theirs");
419 let mut hand = Task::new("h".into(), "h".into(), ".".into(), Source::Human);
420 queue.put(&mut hand).unwrap();
421 assert!(hold(&queue, "talk-a", &mine.id, "wait").is_ok());
422 assert!(hold(&queue, "talk-a", &theirs.id, "x").is_err());
423 assert!(release(&queue, "talk-a", &hand.id).is_err());
424 assert!(retry(&queue, "talk-a", &theirs.id, None, "new").is_err());
425 assert_eq!(queue.get(&theirs.id).unwrap().status, TaskStatus::Queued);
426 }
427
428 #[test]
429 fn hold_then_release_keeps_history_and_restarts_attempts() {
430 let tmp = tempfile::tempdir().unwrap();
431 let queue = Queue::at(tmp.path().join("queue"));
432 let mut t = filed(&queue, "talk-a", "work");
433 t.attempts = 3;
434 t.runs.push("20260101-000000-aaaa".into());
435 queue.put(&mut t).unwrap();
436 let held = hold(&queue, "talk-a", &t.id, "owner asked").unwrap();
437 assert_eq!(held.status, TaskStatus::Held);
438 assert_eq!(held.hold_reason.as_deref(), Some("owner asked"));
439 let back = release(&queue, "talk-a", &t.id).unwrap();
440 assert_eq!(back.status, TaskStatus::Queued);
441 assert_eq!(back.attempts, 0);
442 assert_eq!(back.runs, t.runs);
443 assert!(back.resumption.is_some());
444 }
445
446 #[test]
447 fn retry_edits_and_requeues_in_one_save() {
448 let tmp = tempfile::tempdir().unwrap();
449 let queue = Queue::at(tmp.path().join("queue"));
450 let mut t = filed(&queue, "talk-a", "old text");
451 t.runs.push("20260101-000000-aaaa".into());
452 t.attempts = 2;
453 t.hold_manual(Some("stopped".into()));
454 queue.put(&mut t).unwrap();
455 let again = retry(&queue, "talk-a", &t.id, None, "new text").unwrap();
456 assert_eq!(again.instruction, "new text");
457 assert_eq!(again.status, TaskStatus::Queued);
458 assert_eq!(again.attempts, 0);
459 assert_eq!(again.runs, t.runs, "run history is kept");
460 assert_eq!(again.resumption.as_ref().unwrap().source, "chat");
461 assert_eq!(again.resumption.as_ref().unwrap().instruction, "new text");
462 let mut running = filed(&queue, "talk-a", "busy");
464 running.start("20260101-000000-bbbb".into());
465 queue.put(&mut running).unwrap();
466 assert!(retry(&queue, "talk-a", &running.id, None, "x").is_err());
467 assert_eq!(queue.get(&running.id).unwrap().instruction, "busy");
468 assert!(retry(&queue, "talk-a", &t.id, None, " ").is_err());
469 }
470
471 #[test]
472 fn execution_commands_need_a_full_run_id_of_an_owned_task() {
473 let tmp = tempfile::tempdir().unwrap();
474 let queue = Queue::at(tmp.path().join("queue"));
475 let mut t = filed(&queue, "talk-a", "work");
476 t.runs.push("20260101-000000-aaaa".into());
477 queue.put(&mut t).unwrap();
478 assert!(owned_run_task(&queue, "talk-a", "20260101-000000-aaaa").is_ok());
479 assert!(owned_run_task(&queue, "talk-b", "20260101-000000-aaaa").is_err());
480 assert!(owned_run_task(&queue, "talk-a", "aaaa").is_err());
481 assert!(resume(&queue, tmp.path(), "talk-b", "20260101-000000-aaaa").is_err());
482 }
483
484 #[test]
485 fn abandon_needs_the_exact_owner_message_and_a_matching_quote() {
486 let tmp = tempfile::tempdir().unwrap();
487 let queue = Queue::at(tmp.path().join("queue"));
488 let talks = Talks::at(tmp.path().join("talks"));
489 talk(&talks, "talk-a");
490 let mut t = filed(&queue, "talk-a", "work");
491 t.runs.push("20260101-000000-aaaa".into());
492 queue.put(&mut t).unwrap();
493 let run = "20260101-000000-aaaa";
494 assert!(
496 abandon(
497 &queue,
498 &talks,
499 tmp.path(),
500 "talk-a",
501 run,
502 Some("abandon-run: x")
503 )
504 .is_err()
505 );
506 assert!(abandon(&queue, &talks, tmp.path(), "talk-a", run, None).is_err());
507 assert!(
509 abandon(
510 &queue,
511 &talks,
512 tmp.path(),
513 "talk-a",
514 "20260101-000000-bbbb",
515 None
516 )
517 .is_err()
518 );
519 }
520}