Skip to main content

magi/
chat_control.rs

1//! Direct task and run control for the standing chat: `magi task control ...`,
2//! and a chat seat's `magi answer --reply` / `--reply-other`.
3//!
4//! A chat agent carries out the owner's requests by command, with no question
5//! or offered choice in between: resume a run, hold or release a task, retry a
6//! task with a changed instruction, rerun the failed checks of a pull request,
7//! abandon a dead run, and record the owner's choice for a decision the
8//! machinery waits on (a merge included). The owner's request in the chat is
9//! the authority: no quote, fixed phrase or "only tasks this chat filed" scope
10//! applies, including to direct PR merges. Every command goes
11//! through the transitions the rest of magi already uses ([`crate::resume`],
12//! [`Task::hold_manual`], [`Task::release_operator`], [`Task::edit`],
13//! [`crate::daemon::rerun_checks_once`], [`crate::driver::abandon_proven_dead`],
14//! [`crate::ask::Question::answer`]); this module only checks *who is asking*
15//! and that the target is consistent. A chat seat's answers go through the
16//! same bridge ([`Operation::Answer`], [`Operation::ReplyOther`]) because a
17//! read-only turn's sandbox may refuse magi's stores; the launcher records
18//! them with exactly the terminal's functions.
19//!
20//! - **Authorization.** `MAGI_NODE=chat` and `MAGI_RUN` equal to the exact id
21//!   of an open conversation ([`crate::chat_watch::authorize`]).
22//! - **Targets.** Any task (full or unambiguous-prefix id) and any recorded
23//!   run (full run id). Ids are checked against the queue, and a task is
24//!   re-read under its claim, never trusted from a lookup made before it.
25//! - **Resume starts nothing here.** It pins the owning task to the run and
26//!   queues it; the loop's ordinary start logic resumes it under the graph's
27//!   execution lease, so a second driver cannot appear.
28//! - **Abandon needs a proven-dead driver.** Liveness is judged by the shared
29//!   judge under the owner lock; an unknown or live driver is refused.
30//! - **A merge waits for the owner.** It is recorded only when the owner asks
31//!   for it; the land driver then merges the saved head with
32//!   `--match-head-commit`.
33//! - **Direct PR merging is head-bound, not phrase-bound.** The chat reads the
34//!   head from the forge and merges on the owner's plain request. Pending land
35//!   approvals retain their existing decision path.
36
37use std::path::Path;
38
39use anyhow::{Context, Result, bail, ensure};
40
41use crate::queue::{Queue, Task, TaskStatus};
42use crate::talk::{Talk, Talks};
43
44#[cfg(any(unix, windows))]
45pub(crate) mod bridge;
46
47/// Only these operations cross the standing turn's inherited capability.
48/// No shell commands or calling conversation identities are input.
49#[derive(Debug, serde::Serialize, serde::Deserialize)]
50#[serde(tag = "operation", deny_unknown_fields)]
51pub enum Operation {
52    /// Reassign an idle task to a different repository without migrating runs.
53    Reassign {
54        /// Task id or unambiguous prefix.
55        task: String,
56        /// Repository path, owner/repo, or unique short name.
57        repo: std::path::PathBuf,
58    },
59    /// Authorize bounded repair through the same transaction as the terminal.
60    GrantRepair {
61        /// Head-bound operator request.
62        request: crate::repair_budget::Request,
63    },
64    /// File a new task through the launcher, including from read-only chats.
65    Add {
66        /// Validated filing inputs, without task state or a caller-selected id.
67        filing: Box<Filing>,
68    },
69    /// Mark a task complete using the terminal's transition.
70    Done {
71        /// Task id or unambiguous prefix.
72        task: String,
73    },
74    /// Change a task's queue priority.
75    Priority {
76        /// Task id or unambiguous prefix.
77        task: String,
78        /// New priority.
79        priority: i32,
80    },
81    /// Merge a PR the owner asked for, once per request.
82    MergePr {
83        /// Exact owner/repository name.
84        repo: String,
85        /// Pull request number.
86        number: u64,
87        /// Full head SHA the chat just read from the forge.
88        head: String,
89        /// Idempotency key minted by the chat agent.
90        request: String,
91    },
92    /// 既存 run の再開を queue に登録する。
93    Resume {
94        /// 完全な run ID。
95        run: String,
96    },
97    /// task を手動保留する。
98    Hold {
99        /// task ID または一意な接頭辞。
100        task: String,
101        /// 保留理由。
102        reason: String,
103    },
104    /// task を保留から解放する。
105    Release {
106        /// task ID または一意な接頭辞。
107        task: String,
108    },
109    /// 指示を変更して再試行する。
110    Retry {
111        /// task ID または一意な接頭辞。
112        task: String,
113        /// 新しいタイトル、省略時は指示から生成する。
114        title: Option<String>,
115        /// 新しい指示全文。
116        instruction: String,
117    },
118    /// PR の失敗した workflow を再実行する。
119    RerunChecks {
120        /// 完全な run ID。
121        run: String,
122        /// 冪等性を保証するリクエスト ID。
123        request: String,
124        /// 観測した PR head。
125        head: String,
126        /// 再実行対象の workflow run ID。
127        workflows: Vec<String>,
128    },
129    /// タスクチャットで所有者の判断を記録する(マージを含む)。
130    Decide {
131        /// 質問 ID(完全または一意な接頭辞)。
132        question: String,
133        /// 記録された選択肢のラベル。
134        choice: String,
135        /// 「use my text」で公開する置換タイトルそのもの。
136        #[serde(default)]
137        title: Option<String>,
138    },
139    /// `magi answer --reply`: the owner's answer to a question, as an ordinary
140    /// answer ([`crate::ask::record_answer`]).
141    Answer {
142        /// Full question id, resolved by the CLI.
143        question: String,
144        /// An offered choice (label or alias), or the free-text answer.
145        reply: String,
146        /// The literal replacement title for the posting gate's `use my text`.
147        #[serde(default)]
148        title: Option<String>,
149    },
150    /// `magi answer --reply-other`: the owner's decision outside the offered
151    /// choices, saved as a note that ends the consultation
152    /// ([`crate::consult::reply_other`]).
153    ReplyOther {
154        /// Full question id, resolved by the CLI.
155        question: String,
156        /// The owner's outcome.
157        text: String,
158    },
159    /// 保存された計画を作成、または適用する。
160    ReconcileRetention {
161        /// 対象タスク ID。
162        task: String,
163        /// 保護する実装の完全な run ID。
164        authority: String,
165        /// 適用する保存済み計画 ID(省略時は計画のみ)。
166        apply: Option<String>,
167    },
168    /// 生存が否定された run を破棄する。
169    Abandon {
170        /// 完全な run ID。
171        run: String,
172    },
173}
174
175/// Inputs prepared by `magi task add` before saving a fresh queue record.
176#[derive(Debug, serde::Serialize, serde::Deserialize)]
177#[serde(deny_unknown_fields)]
178pub struct Filing {
179    /// Task title.
180    pub title: String,
181    /// Complete task instruction.
182    pub instruction: String,
183    /// Validated absolute repository path.
184    pub repo: std::path::PathBuf,
185    /// Filing provenance prepared by the CLI.
186    pub source: crate::queue::Source,
187    /// Resolved implementation imports.
188    pub sources: crate::refs::Sources,
189    /// Optional initial hold reason.
190    pub hold: Option<String>,
191    /// Queue priority.
192    pub priority: i32,
193    /// Use one implementer.
194    pub solo: bool,
195    /// Prioritize execution.
196    pub urgent: bool,
197    /// Optional implementer count.
198    pub implementers: Option<usize>,
199    /// Absolute attachment paths to copy into the queue.
200    pub attach: Vec<std::path::PathBuf>,
201}
202
203/// Whether this process inherited a launcher control channel.
204/// Provenance-only CLI calls without a channel retain their ordinary local route.
205pub fn has_channel() -> bool {
206    #[cfg(any(unix, windows))]
207    {
208        std::env::var_os(bridge::CHANNEL_ENV).is_some()
209    }
210    #[cfg(not(any(unix, windows)))]
211    {
212        false
213    }
214}
215
216/// The CLI sends only a typed operation when it inherited a turn capability.
217/// Outside a launched turn the existing, authorized local route remains usable.
218pub async fn dispatch(
219    queue: &Queue,
220    home: &Path,
221    talks: &Talks,
222    talk: &str,
223    operation: Operation,
224) -> Result<String> {
225    if matches!(&operation, Operation::Reassign { .. }) {
226        #[cfg(unix)]
227        {
228            return bridge::request(&operation).context("repository reassignment requires the authenticated chat control channel; restart this chat turn through the launcher");
229        }
230        #[cfg(windows)]
231        {
232            return bridge::request(&operation).await.context("repository reassignment requires the authenticated chat control channel; restart this chat turn through the launcher");
233        }
234        #[cfg(not(any(unix, windows)))]
235        {
236            bail!("authenticated chat control channel is unavailable on this platform");
237        }
238    }
239    #[cfg(unix)]
240    if std::env::var_os(bridge::CHANNEL_ENV).is_some() {
241        // The launcher sets this flag for writable seats, including effective
242        // unsandboxed chat turns. execute() still enforces talk authorization.
243        match bridge::request(&operation) {
244            Err(error)
245                if error.is::<bridge::Unavailable>()
246                    && std::env::var("MAGI_ALLOW_WRITE").as_deref() == Ok("1") => {}
247            result => return result,
248        }
249    }
250    #[cfg(windows)]
251    if std::env::var_os(bridge::CHANNEL_ENV).is_some() {
252        return bridge::request(&operation).await;
253    }
254    execute(queue, home, talks, talk, operation).await
255}
256
257async fn execute(
258    queue: &Queue,
259    home: &Path,
260    talks: &Talks,
261    talk: &str,
262    operation: Operation,
263) -> Result<String> {
264    authorize(talks, talk, crate::queue::CHAT_NODE)?;
265    Ok(match operation {
266        Operation::Reassign { task, repo } => {
267            let cwd = &talks.get(talk)?.repo;
268            let task = crate::task_reassign::reassign(
269                queue,
270                home,
271                cwd,
272                &task,
273                &repo,
274                &format!("chat:{talk}"),
275            )
276            .await?;
277            let mut message = describe(&task, "reassigned");
278            for note in crate::task_reassign::advisory_notes(&task, home) {
279                message.push_str(&format!("\n  {note}"));
280            }
281            message
282        }
283        Operation::Add { filing } => {
284            let mut task = Task::new(filing.title, filing.instruction, filing.repo, filing.source);
285            task.sources = filing.sources;
286            if let Some(reason) = filing.hold {
287                task.hold_manual(Some(reason));
288            }
289            task.priority = filing.priority;
290            task.solo = filing.solo;
291            task.urgent = filing.urgent;
292            if filing.implementers.is_some() {
293                task.overrides = Some(crate::queue::RunOverrides {
294                    candidates: filing.implementers,
295                    ..Default::default()
296                });
297            }
298            if filing.attach.is_empty() {
299                queue.put(&mut task)?;
300            } else {
301                queue.attach_and_put(&mut task, &filing.attach)?;
302            }
303            serde_json::to_string(&task)?
304        }
305        Operation::Done { task } => {
306            let t = done(queue, home, &task)?;
307            format!("done {} {}", t.short(), t.title)
308        }
309        Operation::Priority { task, priority } => {
310            let t = set_priority(queue, &task, priority)?;
311            format!("{} priority now {} - {}", t.short(), t.priority, t.title)
312        }
313        Operation::MergePr {
314            repo,
315            number,
316            head,
317            request,
318        } => {
319            crate::chat_merge::merge(
320                home,
321                talks,
322                talk,
323                crate::chat_merge::Request {
324                    repo,
325                    number,
326                    head,
327                    request,
328                },
329            )
330            .await?
331        }
332        Operation::GrantRepair { request } => {
333            // Keep run-state admission out of the shared control dispatcher
334            // future, which is also embedded in ordinary CLI task operations.
335            serde_json::to_string(
336                &Box::pin(crate::repair_budget::grant(queue, home, request)).await?,
337            )?
338        }
339        Operation::Resume { run } => {
340            let t = resume(queue, home, &run)?;
341            format!(
342                "{}; the loop (`magi serve`) resumes the run under its execution lease",
343                describe(&t, "resume queued for")
344            )
345        }
346        Operation::Hold { task, reason } => describe(&hold(queue, &task, &reason)?, "held"),
347        Operation::Release { task } => describe(&release(queue, &task)?, "released"),
348        Operation::Retry {
349            task,
350            title,
351            instruction,
352        } => describe(
353            &retry(queue, &task, title, &instruction)?,
354            "retry queued for",
355        ),
356        Operation::RerunChecks {
357            run,
358            request,
359            head,
360            workflows,
361        } => {
362            let ids = rerun_checks(queue, home, talk, &run, &request, &head, &workflows).await?;
363            format!("requested a rerun of workflow run(s) {}", ids.join(", "))
364        }
365        Operation::Decide {
366            question,
367            choice,
368            title,
369        } => {
370            let q = record_decision(home, &question, &choice, title.as_deref())?;
371            format!("recorded `{choice}` for decision {}", q.short())
372        }
373        Operation::Answer {
374            question,
375            reply,
376            title,
377        } => crate::ask::record_answer(
378            &crate::ask::Questions::at(home.join("questions")),
379            &question,
380            &reply,
381            title.as_deref(),
382        )?,
383        Operation::ReplyOther { question, text } => crate::consult::reply_other(
384            &crate::ask::Questions::at(home.join("questions")),
385            &question,
386            &text,
387        )?,
388        Operation::ReconcileRetention {
389            task,
390            authority,
391            apply,
392        } => {
393            let path = Box::pin(crate::retention::reconcile::run_chat(
394                home,
395                &task,
396                &authority,
397                apply.as_deref(),
398                crate::retention::reconcile::ChatRequest {
399                    talks,
400                    conversation: talk,
401                },
402            ))
403            .await?;
404            if apply.is_none() {
405                // Return the complete saved evidence through the capability bridge.
406                crate::retention::reconcile::chat_summary(&path)?
407            } else {
408                format!(
409                    "Applied saved plan {}",
410                    apply.as_deref().unwrap_or_default()
411                )
412            }
413        }
414        Operation::Abandon { run } => {
415            abandon(queue, home, &run)?;
416            format!("abandoned run {run}")
417        }
418    })
419}
420
421/// Record the owner's choice for a decision from an open standing chat. The
422/// chat agent interprets the owner's request directly, a merge included; no
423/// quote, consent phrase or task ownership is required. See [`record_decision`].
424pub fn decide(
425    talks: &Talks,
426    home: &Path,
427    talk: &str,
428    question: &str,
429    choice: &str,
430) -> Result<crate::ask::Question> {
431    authorize(talks, talk, crate::queue::CHAT_NODE)?;
432    record_decision(home, question, choice, None)
433}
434
435/// Answer an open decision whose answer the machinery consumes
436/// ([`crate::task_chat::awaits_decision`]: a merge or release approval, the
437/// posting gate, triage, a divergence reconcile, a structured choice action).
438/// The question must still be open and `choice` one of its offered choices;
439/// the consumer behind it keeps its own state and transition checks.
440fn record_decision(
441    home: &Path,
442    question: &str,
443    choice: &str,
444    title: Option<&str>,
445) -> Result<crate::ask::Question> {
446    use crate::ask::{Answer, Questions};
447    let questions = Questions::at(home.join("questions"));
448    let id = questions.resolve_id(question)?;
449    let q = questions.get(&id)?;
450    let queue = Queue::at(home.join("queue"));
451    for task in queue.list() {
452        if q.run == task.id
453            || task.runs.contains(&q.run)
454            || q.routed_task.as_deref() == Some(&task.id)
455        {
456            ensure!(
457                !task.stale_question(&q),
458                "question predates task repository reassignment; inspect the current task and release it for fresh execution"
459            );
460        }
461    }
462    ensure!(
463        crate::task_chat::awaits_decision(&q),
464        "question {} is not a decision the machinery waits on; answer it with `magi answer`",
465        q.short()
466    );
467    let (q, ()) = questions.update(&q.id, |r| {
468        ensure!(
469            r.status.open(),
470            "question {} is already {}",
471            r.short(),
472            r.status.as_str()
473        );
474        let reply = r.resolve_reply(choice)?.to_owned();
475        let replacement =
476            r.node == crate::github_text::ASK_NODE && reply == crate::github_text::USE_MY_TEXT;
477        ensure!(
478            replacement || title.is_none(),
479            "--title is only valid for a publication decision's `use my text` choice"
480        );
481        let title = if replacement {
482            let title =
483                title.context("use my text needs --title with the literal replacement title")?;
484            ensure!(
485                !title.trim().is_empty(),
486                "replacement title must not be empty"
487            );
488            Some(title.to_owned())
489        } else {
490            None
491        };
492        let answer = if r.free_text() {
493            Answer::Text(reply)
494        } else {
495            Answer::Choice(reply)
496        };
497        r.publication_title = title;
498        r.answer(answer)
499    })?;
500    Ok(q)
501}
502
503/// The conversation this process speaks for, or why it may not act.
504pub fn authorize(talks: &Talks, run: &str, node: &str) -> Result<Talk> {
505    if node != crate::queue::CHAT_NODE || run.trim().is_empty() {
506        bail!("task control requires MAGI_NODE=chat and MAGI_RUN from a standing chat");
507    }
508    let id = crate::chat_watch::authorize(talks, run, node)?;
509    talks.get(&id)
510}
511
512/// The task that recorded `run` (a full run id).
513fn run_task(queue: &Queue, run: &str) -> Result<Task> {
514    ensure!(
515        crate::run::is_run_id(run),
516        "an execution command needs the full run id"
517    );
518    queue
519        .list()
520        .into_iter()
521        .find(|t| t.runs.iter().any(|r| r == run))
522        .with_context(|| format!("run {run} belongs to no task"))
523}
524
525/// Claim a task from a full or unambiguous-prefix id and read it under the
526/// claim, never from a lookup made before it.
527fn claimed(queue: &Queue, reference: &str) -> Result<(crate::queue::Claim, Task)> {
528    let id = queue.resolve_id(reference)?;
529    let claim = queue
530        .claim(&id)
531        .with_context(|| format!("task {id} is claimed by a running daemon"))?;
532    let task = queue.get(&id)?;
533    Ok((claim, task))
534}
535
536fn check_hold_release(task: &Task, operation: &str) -> Result<()> {
537    match task.status {
538        TaskStatus::Queued
539        | TaskStatus::Held
540        | TaskStatus::Failed
541        | TaskStatus::Blocked
542        | TaskStatus::Parked => Ok(()),
543        TaskStatus::Done => bail!(
544            "cannot {operation} task {} (done): completed work must not be restarted; create a new task instead",
545            task.id
546        ),
547        TaskStatus::Running => bail!(
548            "cannot {operation} task {} (running): its run may still be active; use resume or abandon for the existing run instead",
549            task.id
550        ),
551    }
552}
553
554/// Mark a task complete under its queue claim, as `magi task done` does.
555pub fn done(queue: &Queue, home: &Path, reference: &str) -> Result<Task> {
556    let (_claim, mut task) = claimed(queue, reference)?;
557    task.succeed();
558    // Manual completion also retires earlier attempts when the latest one landed.
559    crate::daemon::supersede_prior_runs(&task, home);
560    queue.put(&mut task)?;
561    Ok(task)
562}
563
564/// Change priority under the same claim and state check as the terminal route.
565pub fn set_priority(queue: &Queue, reference: &str, priority: i32) -> Result<Task> {
566    let (_claim, mut task) = claimed(queue, reference)?;
567    task.set_priority(priority)?;
568    queue.put(&mut task)?;
569    Ok(task)
570}
571
572/// Hold a task for the owner.
573pub fn hold(queue: &Queue, reference: &str, reason: &str) -> Result<Task> {
574    let (_claim, mut task) = claimed(queue, reference)?;
575    check_hold_release(&task, "hold")?;
576    let reason = reason.trim();
577    task.hold_manual((!reason.is_empty()).then(|| reason.to_owned()));
578    queue.put(&mut task)?;
579    Ok(task)
580}
581
582/// Release a task (the same transition as `magi task release`: the attempt
583/// count restarts, the history stays). An operator hold is released too: the
584/// owner asked for it.
585pub fn release(queue: &Queue, reference: &str) -> Result<Task> {
586    let (_claim, mut task) = claimed(queue, reference)?;
587    check_hold_release(&task, "release")?;
588    crate::base_sync_recovery::ensure_generic_release(queue, &task)?;
589    let run = task.execution_runs().last().cloned();
590    let preserved = match run {
591        Some(run) => crate::repair_budget::queue_resumption(queue, &mut task, &run)?,
592        None => false,
593    };
594    if !preserved {
595        task.release_operator("chat", None);
596    }
597    queue.put(&mut task)?;
598    Ok(task)
599}
600
601/// Change a queued or held task's instruction and queue it again, in one
602/// save under one claim. Only what [`Task::edit`] allows can be retried; the
603/// attempt count follows [`Task::release`] (restarts), while runs, passes and
604/// the resumption history are kept.
605pub fn retry(
606    queue: &Queue,
607    reference: &str,
608    title: Option<String>,
609    instruction: &str,
610) -> Result<Task> {
611    ensure!(
612        !instruction.trim().is_empty(),
613        "the new instruction is empty"
614    );
615    let (_claim, mut task) = claimed(queue, reference)?;
616    if let Some(state) = crate::base_sync_recovery::held_run(queue, &task)
617        && state
618            .base_sync_recovery
619            .stop
620            .as_ref()
621            .is_some_and(|stop| stop.kind == crate::base_sync_recovery::StopKind::Conflict)
622    {
623        anyhow::bail!(
624            "retry cannot authorize editing a retained base-sync stop. {} Keep the retained review criteria and use a dedicated repair grant for the narrow resolution.",
625            state.base_sync_next_action()
626        );
627    }
628    crate::base_sync_recovery::ensure_generic_release(queue, &task)?;
629    let title = title.unwrap_or_else(|| crate::queue::title_from(instruction, 72));
630    task.edit(title, instruction.to_owned())?;
631    task.release_operator("chat", None);
632    queue.put(&mut task)?;
633    Ok(task)
634}
635
636/// Resume a stopped, blocked or parked run (its task's latest). Only queues
637/// the pinned resume; returns the owning task.
638pub fn resume(queue: &Queue, home: &Path, run: &str) -> Result<Task> {
639    let task = run_task(queue, run)?;
640    ensure!(
641        task.execution_runs().last().map(String::as_str) == Some(run),
642        "only the task's latest run can be resumed"
643    );
644    crate::resume::validate(home, run)?;
645    ensure!(
646        crate::resume::pin_queued(queue, run, None, None)?,
647        "no queued task owns run {run}"
648    );
649    queue.get(&task.id)
650}
651
652/// チャットのリクエスト単位で受付記録を残し、共通遷移でチェックを再実行する。
653pub async fn rerun_checks(
654    queue: &Queue,
655    home: &Path,
656    talk: &str,
657    run: &str,
658    request: &str,
659    head: &str,
660    workflows: &[String],
661) -> Result<Vec<String>> {
662    run_task(queue, run)?;
663    let state = crate::run::RunState::load_under(run, home)?;
664    let pr = &state
665        .pr
666        .as_ref()
667        .context("the run recorded no pull request")?
668        .url;
669    ensure!(
670        crate::ask::valid_asset_name(request),
671        "request must be a safe filename of at most 64 bytes"
672    );
673    let dir = home.join("chat-controls").join(talk);
674    std::fs::create_dir_all(&dir)?;
675    let lock = std::fs::OpenOptions::new()
676        .create(true)
677        .truncate(false)
678        .write(true)
679        .open(dir.join(format!("{request}.lock")))?;
680    crate::pr_head::try_lock_file(&lock)?;
681    let path = dir.join(format!("{request}.json"));
682    let action = serde_json::json!({
683        "run": run, "repo": state.repo, "pr": pr, "head": head, "runs": workflows
684    });
685    if path.exists() {
686        let prior: serde_json::Value = serde_json::from_slice(&std::fs::read(&path)?)?;
687        ensure!(
688            prior["action"] == action,
689            "request ID already binds a different operation"
690        );
691        ensure!(
692            prior["status"] == "applied",
693            "previous request has an uncertain result; inspect its receipt before a new request"
694        );
695        return Ok(workflows.to_vec());
696    }
697    let record = |status: &str| -> Result<()> {
698        let tmp = path.with_extension("tmp");
699        std::fs::write(
700            &tmp,
701            serde_json::to_vec(&serde_json::json!({
702                "action": action, "status": status
703            }))?,
704        )?;
705        std::fs::rename(tmp, &path)?;
706        Ok(())
707    };
708    let operation = format!("chat:{talk}:{request}");
709    crate::daemon::rerun_checks_once(home, &operation, &state.repo, pr, head, workflows, || {
710        record("started")
711    })
712    .await?;
713    record("applied")?;
714    Ok(workflows.to_vec())
715}
716
717/// Abandon a recorded run whose driver is proven gone. No confirmation phrase
718/// is needed; an unknown or live driver is refused by
719/// [`crate::driver::abandon_proven_dead`], so a working driver is never broken.
720pub fn abandon(queue: &Queue, home: &Path, run: &str) -> Result<()> {
721    run_task(queue, run)?;
722    crate::driver::abandon_proven_dead(home, run)
723}
724
725/// One line a person or agent can read after a successful command.
726pub fn describe(task: &Task, what: &str) -> String {
727    let status = match task.status {
728        TaskStatus::Queued => "queued",
729        _ => task.status.as_str(),
730    };
731    format!("{what} {} {} ({status})", task.short(), task.title)
732}
733
734#[cfg(test)]
735mod tests {
736    use super::*;
737    use crate::queue::Source;
738    use jiff::Timestamp;
739
740    fn talk(talks: &Talks, id: &str) -> Talk {
741        let mut t: Talk = serde_json::from_value(serde_json::json!({
742            "schema":1,"id":id,"repo":".","agent":"worker","status":"open","turns":[],
743            "created_at":Timestamp::now(),"updated_at":Timestamp::now(),
744            "seat":crate::agent::SeatState::new("talk","worker",1)
745        }))
746        .unwrap();
747        talks.put(&mut t).unwrap();
748        t
749    }
750
751    fn filed(queue: &Queue, talk: &str, text: &str) -> Task {
752        let mut t = Task::new(
753            text.into(),
754            text.into(),
755            ".".into(),
756            Source::Agent {
757                run: talk.into(),
758                node: crate::queue::CHAT_NODE.into(),
759            },
760        );
761        queue.put(&mut t).unwrap();
762        t
763    }
764
765    #[test]
766    fn only_the_chat_seat_of_an_open_talk_is_authorized() {
767        let tmp = tempfile::tempdir().unwrap();
768        let talks = Talks::at(tmp.path().join("talks"));
769        let t = talk(&talks, "talk-a");
770        assert!(authorize(&talks, &t.id, "chat").is_ok());
771        assert!(authorize(&talks, &t.id, "deputy").is_err());
772        assert!(authorize(&talks, &t.id, "").is_err());
773        assert!(authorize(&talks, "", "chat").is_err());
774        assert!(
775            authorize(&talks, "talk-", "chat").is_err(),
776            "prefix is not an id"
777        );
778    }
779
780    #[test]
781    fn tasks_of_any_origin_are_controlled_on_request() {
782        let tmp = tempfile::tempdir().unwrap();
783        let queue = Queue::at(tmp.path().join("queue"));
784        let theirs = filed(&queue, "talk-b", "theirs");
785        let mut hand = Task::new("h".into(), "h".into(), ".".into(), Source::Human);
786        hand.hold_manual(Some("operator".into()));
787        queue.put(&mut hand).unwrap();
788        // Another chat's task and an operator-held human task are the owner's
789        // work too: the request goes through without any ownership scope.
790        assert_eq!(
791            hold(&queue, &theirs.id, "wait").unwrap().status,
792            TaskStatus::Held
793        );
794        assert_eq!(
795            release(&queue, &hand.id).unwrap().status,
796            TaskStatus::Queued
797        );
798        let again = retry(&queue, &theirs.id, None, "new").unwrap();
799        assert_eq!(again.instruction, "new");
800        assert_eq!(again.status, TaskStatus::Queued);
801    }
802
803    #[test]
804    fn hold_then_release_keeps_history_and_restarts_attempts() {
805        let tmp = tempfile::tempdir().unwrap();
806        let queue = Queue::at(tmp.path().join("queue"));
807        let mut t = filed(&queue, "talk-a", "work");
808        t.attempts = 3;
809        t.runs.push("20260101-000000-aaaa".into());
810        queue.put(&mut t).unwrap();
811        let held = hold(&queue, &t.id, "owner asked").unwrap();
812        assert_eq!(held.status, TaskStatus::Held);
813        assert_eq!(held.hold_reason.as_deref(), Some("owner asked"));
814        let back = release(&queue, &t.id).unwrap();
815        assert_eq!(back.status, TaskStatus::Queued);
816        assert_eq!(back.attempts, 0);
817        assert_eq!(back.runs, t.runs);
818        assert!(back.resumption.is_some());
819    }
820
821    #[test]
822    fn hold_and_release_refuse_done_and_running_without_saving() {
823        let tmp = tempfile::tempdir().unwrap();
824        let queue = Queue::at(tmp.path().join("queue"));
825        for status in [TaskStatus::Done, TaskStatus::Running] {
826            let mut t = filed(&queue, "talk-a", "work");
827            t.start("20260101-000000-aaaa".into());
828            if status == TaskStatus::Done {
829                t.succeed();
830            }
831            queue.put(&mut t).unwrap();
832            let before = std::fs::read(queue.path_of(&t.id)).unwrap();
833            for operation in ["hold", "release"] {
834                let error = if operation == "hold" {
835                    hold(&queue, &t.id, "owner asked")
836                } else {
837                    release(&queue, &t.id)
838                }
839                .unwrap_err()
840                .to_string();
841                assert!(error.contains(operation), "{error}");
842                assert!(error.contains(&t.id), "{error}");
843                assert!(error.contains(status.as_str()), "{error}");
844                let guidance = if status == TaskStatus::Done {
845                    "create a new task"
846                } else {
847                    "use resume or abandon"
848                };
849                assert!(error.contains(guidance), "{error}");
850                assert_eq!(std::fs::read(queue.path_of(&t.id)).unwrap(), before);
851            }
852        }
853    }
854
855    #[test]
856    fn hold_and_release_allow_unfinished_inactive_tasks() {
857        let tmp = tempfile::tempdir().unwrap();
858        let queue = Queue::at(tmp.path().join("queue"));
859        for status in [
860            TaskStatus::Queued,
861            TaskStatus::Held,
862            TaskStatus::Failed,
863            TaskStatus::Blocked,
864            TaskStatus::Parked,
865        ] {
866            for operation in ["hold", "release"] {
867                let mut t = filed(&queue, "talk-a", "work");
868                t.status = status;
869                t.hold_reason = Some("old reason".into());
870                t.attempts = 3;
871                t.runs.push("20260101-000000-aaaa".into());
872                queue.put(&mut t).unwrap();
873                let changed = if operation == "hold" {
874                    let held = hold(&queue, &t.id, " new reason ").unwrap();
875                    assert_eq!(held.status, TaskStatus::Held);
876                    assert_eq!(held.hold_reason.as_deref(), Some("new reason"));
877                    assert_eq!(held.attempts, t.attempts);
878                    held
879                } else {
880                    let released = release(&queue, &t.id).unwrap();
881                    assert_eq!(released.status, TaskStatus::Queued);
882                    assert_eq!(released.attempts, 0);
883                    assert_eq!(released.resumption.as_ref().unwrap().source, "chat");
884                    released
885                };
886                assert_eq!(changed.runs, t.runs);
887                assert_eq!(queue.get(&t.id).unwrap().status, changed.status);
888            }
889        }
890    }
891
892    #[test]
893    fn retry_edits_and_requeues_in_one_save() {
894        let tmp = tempfile::tempdir().unwrap();
895        let queue = Queue::at(tmp.path().join("queue"));
896        let mut t = filed(&queue, "talk-a", "old text");
897        t.runs.push("20260101-000000-aaaa".into());
898        t.attempts = 2;
899        t.hold_manual(Some("stopped".into()));
900        queue.put(&mut t).unwrap();
901        let again = retry(&queue, &t.id, None, "new text").unwrap();
902        assert_eq!(again.instruction, "new text");
903        assert_eq!(again.status, TaskStatus::Queued);
904        assert_eq!(again.attempts, 0);
905        assert_eq!(again.runs, t.runs, "run history is kept");
906        assert_eq!(again.resumption.as_ref().unwrap().source, "chat");
907        assert_eq!(again.resumption.as_ref().unwrap().instruction, "new text");
908        // A running task cannot be edited: nothing is changed.
909        let mut running = filed(&queue, "talk-a", "busy");
910        running.start("20260101-000000-bbbb".into());
911        queue.put(&mut running).unwrap();
912        assert!(retry(&queue, &running.id, None, "x").is_err());
913        assert_eq!(queue.get(&running.id).unwrap().instruction, "busy");
914        assert!(retry(&queue, &t.id, None, "  ").is_err());
915    }
916
917    #[test]
918    fn execution_commands_need_the_full_id_of_a_recorded_run() {
919        let tmp = tempfile::tempdir().unwrap();
920        let queue = Queue::at(tmp.path().join("queue"));
921        let mut t = filed(&queue, "talk-b", "work");
922        t.runs.push("20260101-000000-aaaa".into());
923        queue.put(&mut t).unwrap();
924        assert_eq!(
925            run_task(&queue, "20260101-000000-aaaa").unwrap().id,
926            t.id,
927            "any chat may address another chat's run"
928        );
929        assert!(run_task(&queue, "aaaa").is_err());
930        assert!(run_task(&queue, "20260101-000000-bbbb").is_err());
931        assert!(resume(&queue, tmp.path(), "aaaa").is_err());
932    }
933
934    #[test]
935    fn abandon_needs_no_phrase_but_refuses_unrecorded_and_unknown_runs() {
936        let tmp = tempfile::tempdir().unwrap();
937        let queue = Queue::at(tmp.path().join("queue"));
938        let mut t = filed(&queue, "talk-b", "work");
939        t.runs.push("20260101-000000-aaaa".into());
940        queue.put(&mut t).unwrap();
941        // A run no task recorded is refused before liveness is judged.
942        assert!(abandon(&queue, tmp.path(), "20260101-000000-bbbb").is_err());
943        // A recorded run whose driver is not proven dead (here: no state to
944        // judge at all) is never abandoned.
945        assert!(abandon(&queue, tmp.path(), "20260101-000000-aaaa").is_err());
946    }
947}