Skip to main content

magi/
chat_control.rs

1//! Direct task and run control for the standing chat: `magi task control ...`.
2//!
3//! A chat agent can resume a run, hold or release a task, retry a task with a
4//! changed instruction, rerun the failed checks of a pull request and abandon
5//! a dead run by command, with no question or offered choice in between. Every
6//! command goes through the transitions the rest of magi already uses
7//! ([`crate::resume`], [`Task::hold_manual`], [`Task::release_operator`],
8//! [`Task::edit`], [`crate::daemon::rerun_checks_once`],
9//! [`crate::driver::abandon_proven_dead`]); this module only decides *who may
10//! ask* and *about what*.
11//!
12//! - **Authorization.** `MAGI_NODE=chat` and `MAGI_RUN` equal to the exact id
13//!   of an open conversation ([`crate::chat_watch::authorize`]).
14//! - **Scope.** Only tasks that conversation filed itself
15//!   ([`Task::filed_by_chat`]) and the runs recorded in their `runs`. A
16//!   follow-up's inherited `origin_chat` does not count. Task ids and run ids
17//!   are checked against the queue under the task's claim, not trusted.
18//! - **Resume starts nothing here.** It pins the owning task to the run and
19//!   queues it; the loop's ordinary start logic resumes it under the graph's
20//!   execution lease, so a second driver cannot appear.
21//! - **Abandon is individually confirmed.** The owner's latest persisted send
22//!   must be exactly `abandon-run: <full run id>` and `--quote` must equal it;
23//!   liveness is then judged by the shared judge under the owner lock.
24//! - **Merging is not here.** It stays behind the approval gate.
25
26use 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/// Only these operations cross the standing turn's inherited capability.
37/// Paths, commands, merge decisions and conversation identities are not input.
38#[derive(Debug, serde::Serialize, serde::Deserialize)]
39#[serde(tag = "operation", deny_unknown_fields)]
40pub enum Operation {
41    /// 既存 run の再開を queue に登録する。
42    Resume {
43        /// 完全な run ID。
44        run: String,
45    },
46    /// task を手動保留する。
47    Hold {
48        /// task ID または一意な接頭辞。
49        task: String,
50        /// 保留理由。
51        reason: String,
52    },
53    /// task を保留から解放する。
54    Release {
55        /// task ID または一意な接頭辞。
56        task: String,
57    },
58    /// 指示を変更して再試行する。
59    Retry {
60        /// task ID または一意な接頭辞。
61        task: String,
62        /// 新しいタイトル、省略時は指示から生成する。
63        title: Option<String>,
64        /// 新しい指示全文。
65        instruction: String,
66    },
67    /// PR の失敗した workflow を再実行する。
68    RerunChecks {
69        /// 完全な run ID。
70        run: String,
71        /// 冪等性を保証するリクエスト ID。
72        request: String,
73        /// 観測した PR head。
74        head: String,
75        /// 再実行対象の workflow run ID。
76        workflows: Vec<String>,
77    },
78    /// 個別確認後、生存が否定された run を破棄する。
79    Abandon {
80        /// 完全な run ID。
81        run: String,
82        /// 最新の所有者メッセージ全文。
83        quote: Option<String>,
84    },
85}
86
87/// The CLI sends only a typed operation when it inherited a turn capability.
88/// Outside a launched turn the existing, authorized local route remains usable.
89pub 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
153/// The exact owner instruction that confirms abandoning `run`.
154pub fn abandon_instruction(run: &str) -> String {
155    format!("abandon-run: {run}")
156}
157
158/// The conversation this process speaks for, or why it may not act.
159pub 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
167/// Whether `task` was filed by exactly this conversation.
168fn owned(task: &Task, talk: &str) -> bool {
169    task.filed_by_chat() == Some(talk)
170}
171
172/// A task of this conversation, from a full or unambiguous-prefix id.
173pub 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
184/// The task of this conversation that recorded `run` (a full run id).
185pub 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    // The relation is re-checked under the claim, never trusted from a
203    // lookup made before it.
204    ensure!(owned(&task, talk), "task is not filed by this conversation");
205    Ok((claim, task))
206}
207
208/// Hold a task of this conversation for the owner.
209pub 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
218/// Release a task of this conversation (the same transition as `magi task
219/// release`: the attempt count restarts, the history stays).
220pub 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
228/// Change a queued or held task's instruction and queue it again, in one
229/// save under one claim. Only what [`Task::edit`] allows can be retried; the
230/// attempt count follows [`Task::release`] (restarts), while runs, passes and
231/// the resumption history are kept.
232pub 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
252/// Resume a stopped, blocked or parked run of this conversation's task. Only
253/// queues the pinned resume; returns the owning task.
254pub 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
268/// チャットのリクエスト単位で受付記録を残し、共通遷移でチェックを再実行する。
269pub 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
333/// Abandon a run of this conversation's task whose driver is proven gone.
334/// `quote` must be the entire latest persisted owner send, and that send must
335/// be exactly [`abandon_instruction`]. The evidence guard is held through the
336/// abandon, so the owner cannot retract in between.
337pub 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
358/// One line a person or agent can read after a successful command.
359pub 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        // A running task cannot be edited: nothing is changed.
463        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        // No owner message at all.
495        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        // An unrelated run is out of scope before anything else.
508        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}