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
41/// Immutable synchronization stop evidence offered by a recovery decision.
42pub use crate::base_sync_recovery::Stop as BaseRecoveryStop;
43use crate::queue::{Queue, Task, TaskStatus};
44use crate::talk::{Talk, Talks};
45
46#[cfg(any(unix, windows))]
47pub(crate) mod bridge;
48
49/// Only these operations cross the standing turn's inherited capability.
50/// No shell commands or calling conversation identities are input.
51#[derive(Debug, serde::Serialize, serde::Deserialize)]
52#[serde(tag = "operation", deny_unknown_fields)]
53pub enum Operation {
54    /// Reassign an idle task to a different repository without migrating runs.
55    Reassign {
56        /// Task id or unambiguous prefix.
57        task: String,
58        /// Repository path, owner/repo, or unique short name.
59        repo: std::path::PathBuf,
60    },
61    /// Authorize bounded repair through the same transaction as the terminal.
62    GrantRepair {
63        /// Head-bound operator request.
64        request: crate::repair_budget::Request,
65    },
66    /// Reconcile an existing unimported repair receipt; never adds budget.
67    ReconcileRepairGrant {
68        /// Exact owner-authorized recovery identity.
69        request: crate::repair_budget::reconcile::Request,
70    },
71    /// Reconcile a task-local uncertain effect against its durable end condition.
72    ReconcileDecision {
73        /// Stable inquiry id.
74        inquiry: String,
75    },
76    /// Bind a command to its durable inquiry; acceptance is not resolution.
77    ForDecision {
78        /// Stable inquiry id.
79        inquiry: String,
80        /// Existing typed task/run command.
81        command: Box<Operation>,
82    },
83    /// Explicitly confirm no effect remains, including accepted legacy choices.
84    SettleDecision {
85        /// Stable inquiry id.
86        inquiry: String,
87        /// Owner's reason for settlement.
88        reason: String,
89        /// Replacement active inquiry in the same task/chat.
90        replacement: Option<String>,
91    },
92    /// File a new task through the launcher, including from read-only chats.
93    Add {
94        /// Validated filing inputs, without task state or a caller-selected id.
95        filing: Box<Filing>,
96    },
97    /// Mark a task complete using the terminal's transition.
98    Done {
99        /// Task id or unambiguous prefix.
100        task: String,
101    },
102    /// Change a task's queue priority.
103    Priority {
104        /// Task id or unambiguous prefix.
105        task: String,
106        /// New priority.
107        priority: i32,
108    },
109    /// Merge a PR the owner asked for, once per request.
110    MergePr {
111        /// Exact owner/repository name.
112        repo: String,
113        /// Pull request number.
114        number: u64,
115        /// Full head SHA the chat just read from the forge.
116        head: String,
117        /// Idempotency key minted by the chat agent.
118        request: String,
119    },
120    /// Authorize one bounded base-recovery interval and queue the existing run.
121    RecoverBase {
122        /// Exact retained run ID.
123        run: String,
124        /// Retained HEAD inspected for the owner's request (full SHA or 7+ hex digits).
125        head: String,
126        /// Durable idempotency key; reuse only for identical arguments.
127        request: String,
128    },
129    /// 既存 run の再開を queue に登録する。
130    Resume {
131        /// 完全な run ID。
132        run: String,
133    },
134    /// task を手動保留する。
135    Hold {
136        /// task ID または一意な接頭辞。
137        task: String,
138        /// 保留理由。
139        reason: String,
140    },
141    /// task を保留から解放する。
142    Release {
143        /// task ID または一意な接頭辞。
144        task: String,
145    },
146    /// 指示を変更して再試行する。
147    Retry {
148        /// task ID または一意な接頭辞。
149        task: String,
150        /// 新しいタイトル、省略時は指示から生成する。
151        title: Option<String>,
152        /// 新しい指示全文。
153        instruction: String,
154    },
155    /// PR の失敗した workflow を再実行する。
156    RerunChecks {
157        /// 完全な run ID。
158        run: String,
159        /// 冪等性を保証するリクエスト ID。
160        request: String,
161        /// 観測した PR head。
162        head: String,
163        /// 再実行対象の workflow run ID。
164        workflows: Vec<String>,
165    },
166    /// タスクチャットで所有者の判断を記録する(マージを含む)。
167    Decide {
168        /// 質問 ID(完全または一意な接頭辞)。
169        question: String,
170        /// 記録された選択肢のラベル。
171        choice: String,
172        /// 「use my text」で公開する置換タイトルそのもの。
173        #[serde(default)]
174        title: Option<String>,
175    },
176    /// `magi answer --reply`: the owner's answer to a question, as an ordinary
177    /// answer ([`crate::ask::record_answer`]).
178    Answer {
179        /// Full question id, resolved by the CLI.
180        question: String,
181        /// An offered choice (label or alias), or the free-text answer.
182        reply: String,
183        /// The literal replacement title for the posting gate's `use my text`.
184        #[serde(default)]
185        title: Option<String>,
186    },
187    /// `magi answer --reply-other`: the owner's decision outside the offered
188    /// choices, saved as a note that ends the consultation
189    /// ([`crate::consult::reply_other`]).
190    ReplyOther {
191        /// Full question id, resolved by the CLI.
192        question: String,
193        /// The owner's outcome.
194        text: String,
195    },
196    /// 保存された計画を作成、または適用する。
197    ReconcileRetention {
198        /// 対象タスク ID。
199        task: String,
200        /// 保護する実装の完全な run ID。
201        authority: String,
202        /// 適用する保存済み計画 ID(省略時は計画のみ)。
203        apply: Option<String>,
204    },
205    /// 生存が否定された run を破棄する。
206    Abandon {
207        /// 完全な run ID。
208        run: String,
209    },
210}
211
212/// Inputs prepared by `magi task add` before saving a fresh queue record.
213#[derive(Debug, serde::Serialize, serde::Deserialize)]
214#[serde(deny_unknown_fields)]
215pub struct Filing {
216    /// Task title.
217    pub title: String,
218    /// Complete task instruction.
219    pub instruction: String,
220    /// Validated absolute repository path.
221    pub repo: std::path::PathBuf,
222    /// Filing provenance prepared by the CLI.
223    pub source: crate::queue::Source,
224    /// Resolved implementation imports.
225    pub sources: crate::refs::Sources,
226    /// Optional initial hold reason.
227    pub hold: Option<String>,
228    /// Queue priority.
229    pub priority: i32,
230    /// Use one implementer.
231    pub solo: bool,
232    /// Prioritize execution.
233    pub urgent: bool,
234    /// Optional implementer count.
235    pub implementers: Option<usize>,
236    /// Absolute attachment paths to copy into the queue.
237    pub attach: Vec<std::path::PathBuf>,
238}
239
240/// Whether this process inherited a launcher control channel.
241/// Provenance-only CLI calls without a channel retain their ordinary local route.
242pub fn has_channel() -> bool {
243    #[cfg(any(unix, windows))]
244    {
245        #[cfg(unix)]
246        let socket = std::env::var_os("MAGI_CHAT_CONTROL_SOCKET").is_some();
247        #[cfg(windows)]
248        let socket = false;
249        std::env::var_os(bridge::CHANNEL_ENV).is_some() || socket
250    }
251    #[cfg(not(any(unix, windows)))]
252    {
253        false
254    }
255}
256
257/// The CLI sends only a typed operation when it inherited a turn capability.
258/// Outside a launched turn the existing, authorized local route remains usable.
259pub async fn dispatch(
260    queue: &Queue,
261    home: &Path,
262    talks: &Talks,
263    talk: &str,
264    operation: Operation,
265) -> Result<String> {
266    if matches!(
267        &operation,
268        Operation::Reassign { .. } | Operation::RecoverBase { .. }
269    ) {
270        #[cfg(unix)]
271        {
272            return bridge::request(&operation).context("this operation requires the authenticated chat control channel; repair the launcher/backend transport; reopening the conversation does not repair descriptor propagation");
273        }
274        #[cfg(windows)]
275        {
276            return bridge::request(&operation).await.context("this operation requires the authenticated chat control channel; repair the launcher/backend transport; reopening the conversation does not repair descriptor propagation");
277        }
278        #[cfg(not(any(unix, windows)))]
279        {
280            bail!("authenticated chat control channel is unavailable on this platform");
281        }
282    }
283    #[cfg(unix)]
284    if std::env::var_os(bridge::CHANNEL_ENV).is_some()
285        || std::env::var_os("MAGI_CHAT_CONTROL_SOCKET").is_some()
286    {
287        // The launcher sets this flag for writable seats, including effective
288        // unsandboxed chat turns. execute() still enforces talk authorization.
289        match bridge::request(&operation) {
290            Err(error)
291                if error.is::<bridge::Unavailable>()
292                    && std::env::var("MAGI_ALLOW_WRITE").as_deref() == Ok("1") => {}
293            result => return result,
294        }
295    }
296    #[cfg(windows)]
297    if std::env::var_os(bridge::CHANNEL_ENV).is_some() {
298        return bridge::request(&operation).await;
299    }
300    execute(queue, home, talks, talk, operation).await
301}
302
303async fn execute(
304    queue: &Queue,
305    home: &Path,
306    talks: &Talks,
307    talk: &str,
308    operation: Operation,
309) -> Result<String> {
310    authorize(talks, talk, crate::queue::CHAT_NODE)?;
311    Ok(match operation {
312        Operation::Reassign { task, repo } => {
313            let cwd = &talks.get(talk)?.repo;
314            let task = crate::task_reassign::reassign(
315                queue,
316                home,
317                cwd,
318                &task,
319                &repo,
320                &format!("chat:{talk}"),
321            )
322            .await?;
323            let mut message = describe(&task, "reassigned");
324            for note in crate::task_reassign::advisory_notes(&task, home) {
325                message.push_str(&format!("\n  {note}"));
326            }
327            message
328        }
329        Operation::ReconcileDecision { inquiry } => {
330            reconcile_task_decision(queue, home, talk, &inquiry)?;
331            format!("decision {inquiry} reconciled from the task's durable state")
332        }
333        Operation::ForDecision { inquiry, command } => {
334            execute_decision(queue, home, talks, talk, &inquiry, *command).await?
335        }
336        Operation::SettleDecision {
337            inquiry,
338            reason,
339            replacement,
340        } => {
341            let outbox = crate::task_inquiry::Outbox::at(home);
342            let record = outbox.get(&inquiry)?;
343            let questions = crate::ask::Questions::at(home.join("questions"));
344            let source = questions.read_history(&inquiry).ok();
345            // A quarantined saved reply is not a live unanswered decision.
346            // The owner can explicitly confirm that its unknown effect needs
347            // no further work without accepting or replaying the old reply.
348            let unaccepted_history = record
349                .decision
350                .as_ref()
351                .is_some_and(|d| d.request.is_none())
352                && source.as_ref().is_some_and(|source| {
353                    source.status == crate::ask::QuestionStatus::Answered
354                        && crate::task_chat::saved_reply_requires_confirmation(home, source)
355                });
356            // Task-backed legacy consumers run under the task claim. Hold it
357            // through settlement; ownerless release consumers use the inquiry
358            // execution fence inside Outbox::settle instead.
359            let _task_claim = if !record.task.is_empty()
360                && (unaccepted_history
361                    || record
362                        .decision
363                        .as_ref()
364                        .is_some_and(|d| d.request.is_some()))
365            {
366                Some(
367                    queue
368                        .claim(&record.task)
369                        .context("decision task is executing")?,
370                )
371            } else {
372                None
373            };
374            if record
375                .decision
376                .as_ref()
377                .is_some_and(|d| d.request.is_none())
378                && let Some(source) = source
379                && !(record.task.is_empty() && record.delivered_to.is_none())
380            {
381                ensure!(
382                    unaccepted_history || !crate::task_chat::awaits_decision(&source),
383                    "a legacy effect still awaits consumer reconciliation; settlement executes no action"
384                );
385            }
386            outbox.settle(&inquiry, talk, &reason, replacement.as_deref())?;
387            format!("settled decision {inquiry}: {reason}")
388        }
389        Operation::Add { filing } => {
390            let mut task = Task::new(filing.title, filing.instruction, filing.repo, filing.source);
391            task.sources = filing.sources;
392            if let Some(reason) = filing.hold {
393                task.hold_manual(Some(reason));
394            }
395            task.priority = filing.priority;
396            task.solo = filing.solo;
397            task.urgent = filing.urgent;
398            if filing.implementers.is_some() {
399                task.overrides = Some(crate::queue::RunOverrides {
400                    candidates: filing.implementers,
401                    ..Default::default()
402                });
403            }
404            if filing.attach.is_empty() {
405                queue.put(&mut task)?;
406            } else {
407                queue.attach_and_put(&mut task, &filing.attach)?;
408            }
409            serde_json::to_string(&task)?
410        }
411        Operation::Done { task } => {
412            let t = done(queue, home, &task)?;
413            format!("done {} {}", t.short(), t.title)
414        }
415        Operation::Priority { task, priority } => {
416            let t = set_priority(queue, &task, priority)?;
417            format!("{} priority now {} - {}", t.short(), t.priority, t.title)
418        }
419        Operation::MergePr {
420            repo,
421            number,
422            head,
423            request,
424        } => crate::chat_merge::merge(
425            home,
426            talks,
427            talk,
428            crate::chat_merge::Request {
429                repo,
430                number,
431                head,
432                request,
433            },
434        )
435        .await
436        .map_err(|error| {
437            if error.is::<crate::chat_merge::BeforeMergeWrite>() {
438                anyhow::Error::new(BeforeEffect(error))
439            } else {
440                error
441            }
442        })?,
443        Operation::ReconcileRepairGrant { request } => serde_json::to_string(
444            &Box::pin(crate::repair_budget::reconcile::apply(queue, home, request)).await?,
445        )?,
446        Operation::GrantRepair { request } => {
447            // Keep run-state admission out of the shared control dispatcher
448            // future, which is also embedded in ordinary CLI task operations.
449            serde_json::to_string(
450                &Box::pin(crate::repair_budget::grant(queue, home, request)).await?,
451            )?
452        }
453        Operation::RecoverBase { run, head, request } => {
454            let result = Box::pin(crate::base_recovery_control::recover(
455                queue,
456                home,
457                crate::base_recovery_control::Request {
458                    run,
459                    head,
460                    request,
461                    actor: talk.to_owned(),
462                    decision: None,
463                    expected_stop: None,
464                },
465            ))
466            .await?;
467            if result.repeated {
468                format!(
469                    "This base-recovery request was already applied to task {}; inspect its current status before continuing",
470                    result.task.id
471                )
472            } else {
473                format!(
474                    "{}; bounded base recovery authorized; the daemon resumes the exact run under its execution lease",
475                    describe(&result.task, "recovery queued for")
476                )
477            }
478        }
479        Operation::Resume { run } => {
480            let t = resume(queue, home, &run)?;
481            format!(
482                "{}; the loop (`magi serve`) resumes the run under its execution lease",
483                describe(&t, "resume queued for")
484            )
485        }
486        Operation::Hold { task, reason } => describe(&hold(queue, &task, &reason)?, "held"),
487        Operation::Release { task } => describe(&release(queue, &task)?, "released"),
488        Operation::Retry {
489            task,
490            title,
491            instruction,
492        } => describe(
493            &retry(queue, &task, title, &instruction)?,
494            "retry queued for",
495        ),
496        Operation::RerunChecks {
497            run,
498            request,
499            head,
500            workflows,
501        } => {
502            let ids = rerun_checks(queue, home, talk, &run, &request, &head, &workflows).await?;
503            format!("requested a rerun of workflow run(s) {}", ids.join(", "))
504        }
505        Operation::Decide {
506            question,
507            choice,
508            title,
509        } => {
510            let q = record_decision(home, &question, &choice, title.as_deref())?;
511            format!(
512                "recorded `{choice}` for decision {}; effect pending until its durable application receipt is confirmed",
513                q.short()
514            )
515        }
516        Operation::Answer {
517            question,
518            reply,
519            title,
520        } => crate::ask::record_answer(
521            &crate::ask::Questions::at(home.join("questions")),
522            &question,
523            &reply,
524            title.as_deref(),
525        )?,
526        Operation::ReplyOther { question, text } => crate::consult::reply_other(
527            &crate::ask::Questions::at(home.join("questions")),
528            &question,
529            &text,
530        )?,
531        Operation::ReconcileRetention {
532            task,
533            authority,
534            apply,
535        } => {
536            let path = Box::pin(crate::retention::reconcile::run_chat(
537                home,
538                &task,
539                &authority,
540                apply.as_deref(),
541                crate::retention::reconcile::ChatRequest {
542                    talks,
543                    conversation: talk,
544                },
545            ))
546            .await?;
547            if apply.is_none() {
548                // Return the complete saved evidence through the capability bridge.
549                crate::retention::reconcile::chat_summary(&path)?
550            } else {
551                format!(
552                    "Applied saved plan {}",
553                    apply.as_deref().unwrap_or_default()
554                )
555            }
556        }
557        Operation::Abandon { run } => {
558            abandon(queue, home, &run)?;
559            format!("abandoned run {run}")
560        }
561    })
562}
563
564/// Run one typed operation on behalf of the owner, retaining failures and
565/// uncertainty. A repeated command never blindly replays a possibly applied
566/// external effect. The underlying operation retains its existing claims and
567/// receipts; this journal is its user-visible lifecycle, not a second worker.
568async fn execute_decision(
569    queue: &Queue,
570    home: &Path,
571    talks: &Talks,
572    chat: &str,
573    id: &str,
574    command: Operation,
575) -> Result<String> {
576    use crate::task_decision::Status;
577    let outbox = crate::task_inquiry::Outbox::at(home);
578    let _execution = outbox.execution_claim(id)?;
579    let inquiry = outbox.get(id)?;
580    ensure!(
581        inquiry.delivered_to.as_deref() == Some(chat),
582        "decision belongs to another chat"
583    );
584    let task = queue.get(&inquiry.task)?;
585    ensure!(task.repo == inquiry.repo, "decision repository changed");
586    let deferred = matches!(
587        command,
588        Operation::Resume { .. } | Operation::MergePr { .. }
589    );
590    let merge = match &command {
591        Operation::MergePr {
592            repo,
593            number,
594            head,
595            request,
596        } => Some(crate::chat_merge::Request {
597            repo: repo.clone(),
598            number: *number,
599            head: head.clone(),
600            request: request.clone(),
601        }),
602        _ => None,
603    };
604    match &command {
605        Operation::Done { task: target }
606        | Operation::Hold { task: target, .. }
607        | Operation::Release { task: target }
608        | Operation::Retry { task: target, .. } => {
609            ensure!(
610                queue.resolve_id(target)? == task.id,
611                "command targets another task"
612            );
613        }
614        Operation::Resume { run }
615        | Operation::Abandon { run }
616        | Operation::RerunChecks { run, .. } => {
617            ensure!(
618                task.runs.contains(run) && inquiry.run.as_ref().is_none_or(|own| own == run),
619                "command targets another execution"
620            );
621            ensure!(
622                queue
623                    .list()
624                    .iter()
625                    .filter(|owner| owner.runs.contains(run))
626                    .count()
627                    == 1,
628                "execution ownership is ambiguous"
629            );
630        }
631        Operation::MergePr { repo, number, .. } => {
632            let run = inquiry
633                .run
634                .as_ref()
635                .or_else(|| task.runs.last())
636                .context("task has no execution for this merge")?;
637            let state = crate::run::RunState::load_under(run, home)?;
638            let expected = format!("https://github.com/{repo}/pull/{number}");
639            ensure!(
640                state.repo == task.repo
641                    && state
642                        .pr
643                        .as_ref()
644                        .is_some_and(|pr| pr.url.eq_ignore_ascii_case(&expected)),
645                "merge targets another task or repository"
646            );
647        }
648        _ => bail!("use a task/run effect command with --decision; routed approvals use decide"),
649    }
650    let request = serde_json::to_string(&command)?;
651    let mut decision = inquiry.decision.context("inquiry is informational")?;
652    if decision.request.is_some()
653        && decision.status != Status::Resolved
654        && let Operation::Resume { run } = &command
655    {
656        ensure!(
657            decision.request.as_deref() == Some(&request),
658            "decision already binds a different request"
659        );
660        // Queued also includes successfully published resumes. Reconcile under
661        // the execution claim before permitting any retry, even if the run has
662        // since returned to a resumable state. Only proven non-publication may
663        // enter the retry path below.
664        reconcile_resume_claimed(queue, home, &outbox, id, run)?;
665        decision = outbox
666            .get(id)?
667            .decision
668            .context("inquiry is informational")?;
669        ensure!(
670            decision.status == Status::Resolved || decision.retry_safe,
671            "previous resume remains queued or executing; it will not be replayed"
672        );
673    }
674    if decision.status == Status::Resolved {
675        ensure!(
676            decision.request.as_deref() == Some(&request),
677            "decision resolved for a different request"
678        );
679        return Ok(format!(
680            "decision {id} is already resolved; inspect its outcome history"
681        ));
682    }
683    if let Operation::RerunChecks { run, request, .. } = &command {
684        // Reject correctable input before binding the decision to this exact
685        // command. Execution revalidates these reads before taking its lock.
686        rerun_preflight(queue, home, run, request)?;
687    }
688    if let Some(action) = &merge {
689        // Malformed input must not durably bind this decision to a command
690        // that can never reach its effect service.
691        action.validate()?;
692    }
693    // Keep admission across acceptance and execution: contention and request
694    // collisions must not bind a fresh decision to an unstartable operation.
695    let merge_admission = merge
696        .as_ref()
697        .map(|action| crate::chat_merge::admit(home, talks, chat, action))
698        .transpose()?;
699    if decision.request.is_none() && decision.status == Status::RetryNeeded {
700        if let Ok(source) = crate::ask::Questions::at(home.join("questions")).get(id) {
701            ensure!(
702                !crate::task_chat::awaits_decision(&source),
703                "a legacy effect still needs its receipt reconciled before another effect is accepted"
704            );
705        }
706    }
707    {
708        // A live task cannot accept a repair grant. Do not prevent decisions
709        // that its active driver is waiting for by taking its execution claim.
710        let claim = (queue.get(&task.id)?.status != TaskStatus::Running)
711            .then(|| queue.claim(&task.id))
712            .transpose();
713        let _claim = match claim {
714            Ok(claim) => claim,
715            Err(error) => {
716                // Admission could not start this attempt. Retain the exact
717                // owner request and pre-effect failure just as execution-side
718                // claim contention does, without publishing any task effect.
719                let message = format!(
720                    "{error:#}. No effect began; retry this same request after resolving the cause, or explicitly settle it."
721                );
722                outbox.update_decision(id, |d| {
723                    let safe = d.request.is_none() || d.retry_safe;
724                    d.accept(&request)?;
725                    if safe {
726                        d.fail_before_effect(&message)
727                    } else {
728                        // A prior queued/uncertain attempt still needs its own
729                        // receipt. Contention is not proof that it never ran.
730                        Ok(false)
731                    }
732                })?;
733                return Err(anyhow::Error::new(BeforeEffect(error)));
734            }
735        };
736        outbox.update_decision(id, |d| d.accept(&request))?;
737    }
738    if decision.request.is_some()
739        && matches!(decision.status, Status::InProgress | Status::RetryNeeded)
740    {
741        if decision.retry_safe {
742            outbox.update_decision(id, |d| {
743                d.retry_unapplied()?;
744                d.start()
745            })?;
746        } else {
747            let action = merge
748                .as_ref()
749                .context("previous effect needs receipt reconciliation; it will not be replayed")?;
750            ensure!(
751                merge_receipt(home, chat, action)?.is_some(),
752                "previous merge has no receipt; inspect the operation before retrying"
753            );
754        }
755        // The shared merge service only checks the forge once this exact
756        // request has a receipt; it never issues the merge command twice.
757    } else {
758        outbox.update_decision(id, |d| d.start())?;
759    }
760    let local = apply_local_decision(
761        queue,
762        home,
763        id,
764        &request,
765        &inquiry.task,
766        &inquiry.repo,
767        &command,
768    );
769    let result = if let Err(error) = local {
770        Err(error)
771    } else if let Some(message) = local? {
772        Ok(message)
773    } else if let Operation::Resume { run } = &command {
774        // Validation precedes any write: a refusal means nothing began.
775        crate::resume::validate(home, run)
776            .map(|_| ())
777            .map_err(|e| anyhow::Error::new(BeforeEffect(e)))
778            .and_then(|()| -> Result<String> {
779                let pinned =
780                    crate::resume::pin_queued(queue, run, None, Some(id)).map_err(|error| {
781                        if error.is::<crate::resume::BeforeQueueWrite>() {
782                            anyhow::Error::new(BeforeEffect(error))
783                        } else {
784                            error
785                        }
786                    })?;
787                if !pinned {
788                    return Err(anyhow::Error::new(BeforeEffect(anyhow::anyhow!(
789                        "no queued task owns this run"
790                    ))));
791                }
792                Ok(format!(
793                    "resume queued for {run}; execution start remains unconfirmed"
794                ))
795            })
796    } else if let Operation::Abandon { run } = &command {
797        crate::driver::abandon_decision(home, run, id, &request)
798            .map_err(|error| {
799                if error.is::<crate::driver::BeforeAbandonWrite>() {
800                    anyhow::Error::new(BeforeEffect(error))
801                } else {
802                    error
803                }
804            })
805            .map(|()| format!("abandoned run {run}"))
806    } else if let Some(admission) = merge_admission {
807        crate::chat_merge::merge_admitted(home, merge.as_ref().unwrap().clone(), admission)
808            .await
809            .map_err(|error| {
810                if error.is::<crate::chat_merge::BeforeMergeWrite>() {
811                    anyhow::Error::new(BeforeEffect(error))
812                } else {
813                    error
814                }
815            })
816    } else {
817        Box::pin(execute(queue, home, talks, chat, command)).await
818    };
819    match result {
820        Ok(message) => {
821            if let Some(action) = &merge {
822                if let Some(receipt) = merge_receipt(home, chat, action)? {
823                    if receipt["status"] == "merged" {
824                        outbox.update_decision(id, |d| d.applied(&message))?;
825                    } else if receipt["status"] != "pending" {
826                        outbox.update_decision(id, |d| {
827                            d.fail(&format!(
828                                "{message}; reuse this same request ID to reconcile only"
829                            ))
830                        })?;
831                    }
832                }
833            } else if !deferred {
834                outbox.update_decision(id, |d| {
835                    d.applied(&format!("typed command completed: {message}"))
836                })?;
837            }
838            if deferred
839                && outbox
840                    .get(id)?
841                    .decision
842                    .as_ref()
843                    .is_some_and(|d| d.status == Status::InProgress)
844            {
845                outbox.update_decision(id, |d| d.queued())?;
846            }
847            // Resume has only been queued. Its execution is confirmed by a
848            // later scheduler projection, never by this command's return.
849            Ok(message)
850        }
851        Err(error) => {
852            let message = if error.is::<BeforeEffect>() {
853                format!(
854                    "{error:#}. No effect began; retry this same request after resolving the cause, or explicitly settle it."
855                )
856            } else {
857                format!(
858                    "Operation failed or has an uncertain result: {error:#}. Inspect its receipt before retrying."
859                )
860            };
861            outbox.update_decision(id, |d| {
862                if error.is::<BeforeEffect>() {
863                    d.fail_before_effect(&message)
864                } else {
865                    d.fail(&message)
866                }
867            })?;
868            Err(error)
869        }
870    }
871}
872
873#[derive(Debug, thiserror::Error)]
874#[error("effect did not start: {0:#}")]
875struct BeforeEffect(anyhow::Error);
876
877/// Commit a task-local effect and its exact receipt under one queue claim.
878/// The inquiry projection may lag this write, but restart never has to infer
879/// completion from the task's current status or repeat the operation.
880fn apply_local_decision(
881    queue: &Queue,
882    home: &Path,
883    id: &str,
884    request: &str,
885    owner: &str,
886    repo: &Path,
887    command: &Operation,
888) -> Result<Option<String>> {
889    let target = match command {
890        Operation::Done { task }
891        | Operation::Hold { task, .. }
892        | Operation::Release { task }
893        | Operation::Retry { task, .. } => task,
894        _ => return Ok(None),
895    };
896    let prepare = || -> Result<_> {
897        let (_claim, mut task) = claimed(queue, target)?;
898        ensure!(
899            task.id == owner && task.repo == repo,
900            "decision ownership changed"
901        );
902        if let Some(prior) = task.decision_effects.get(id) {
903            ensure!(prior == request, "decision receipt binds another command");
904            let message = format!("task {}: decision {id} already applied", task.id);
905            return Ok((_claim, task, message, true));
906        }
907        let message = match command {
908            Operation::Done { .. } => {
909                task.succeed();
910                describe(&task, "done")
911            }
912            Operation::Hold { reason, .. } => {
913                check_hold_release(&task, "hold")?;
914                let reason = reason.trim();
915                task.hold_manual((!reason.is_empty()).then(|| reason.to_owned()));
916                describe(&task, "held")
917            }
918            Operation::Release { .. } => {
919                check_hold_release(&task, "release")?;
920                task.release_operator("chat", Some(id));
921                describe(&task, "released")
922            }
923            Operation::Retry {
924                title, instruction, ..
925            } => {
926                ensure!(
927                    !instruction.trim().is_empty(),
928                    "the new instruction is empty"
929                );
930                let title = title
931                    .clone()
932                    .unwrap_or_else(|| crate::queue::title_from(instruction, 72));
933                task.edit(title, instruction.clone())?;
934                task.release_operator("chat", Some(id));
935                describe(&task, "retry queued for")
936            }
937            _ => unreachable!("task-local operation checked above"),
938        };
939        task.decision_effects
940            .insert(id.to_owned(), request.to_owned());
941        Ok((_claim, task, message, false))
942    };
943    let (_claim, mut task, message, already_applied) = prepare().map_err(BeforeEffect)?;
944    if !already_applied {
945        queue.put(&mut task)?;
946    }
947    if matches!(command, Operation::Done { .. }) {
948        crate::daemon::supersede_prior_runs(&task, home);
949    }
950    Ok(Some(message))
951}
952
953/// Explicit owner-requested reconciliation executes nothing. Under the task
954/// claim, prove that the exact intended condition already holds; otherwise keep
955/// uncertainty visible. External effects require their own receipts instead.
956fn reconcile_task_decision(queue: &Queue, home: &Path, chat: &str, id: &str) -> Result<()> {
957    let outbox = crate::task_inquiry::Outbox::at(home);
958    let inquiry = outbox.get(id)?;
959    ensure!(
960        inquiry.delivered_to.as_deref() == Some(chat)
961            || (inquiry.task.is_empty() && inquiry.delivered_to.is_none()),
962        "decision belongs to another chat"
963    );
964    let decision = inquiry.decision.context("inquiry is informational")?;
965    if decision.status == crate::task_decision::Status::Resolved {
966        return Ok(());
967    }
968    if decision
969        .request
970        .as_ref()
971        .is_none_or(|request| request.starts_with("decision: "))
972    {
973        let source = crate::ask::Questions::at(home.join("questions")).read_history(id)?;
974        crate::task_chat::sync_effect_receipt(home, queue, &source);
975        ensure!(
976            outbox
977                .get(id)?
978                .decision
979                .is_some_and(|d| d.status == crate::task_decision::Status::Resolved),
980            "source effect remains unconfirmed; no operation was replayed"
981        );
982        return Ok(());
983    }
984    let request = decision
985        .request
986        .context("decision has no accepted operation to reconcile")?;
987    let command: Operation = serde_json::from_str(&request)?;
988    if let Operation::Resume { run } = &command {
989        reconcile_resume_decision(queue, home, &outbox, id, run)?;
990        ensure!(
991            outbox.get(id)?.decision.is_some_and(|d| {
992                d.status == crate::task_decision::Status::Resolved || d.retry_safe
993            }),
994            "resume remains queued or executing; no operation was replayed"
995        );
996        return Ok(());
997    }
998    let (_claim, task) = claimed(queue, &inquiry.task)?;
999    ensure!(task.repo == inquiry.repo, "decision repository changed");
1000    if let Some(receipt) = task.decision_effects.get(id) {
1001        ensure!(
1002            receipt == &request,
1003            "decision receipt binds another command"
1004        );
1005        return outbox.update_decision(id, |d| {
1006            d.applied("exact task command receipt confirmed; no operation replayed")
1007        });
1008    }
1009    let matches = match command {
1010        Operation::Hold {
1011            task: target,
1012            reason,
1013        } => {
1014            queue.resolve_id(&target)? == task.id
1015                && task.status == TaskStatus::Held
1016                && task.hold_reason.as_deref() == Some(reason.trim())
1017        }
1018        Operation::Release { task: target } => {
1019            queue.resolve_id(&target)? == task.id
1020                && task.status == TaskStatus::Queued
1021                && !task.operator_held()
1022        }
1023        Operation::Done { task: target } => {
1024            queue.resolve_id(&target)? == task.id && task.status == TaskStatus::Done
1025        }
1026        Operation::Retry {
1027            task: target,
1028            title,
1029            instruction,
1030        } => {
1031            queue.resolve_id(&target)? == task.id
1032                && task.instruction == instruction
1033                && title.as_ref().is_none_or(|title| *title == task.title)
1034                && task.status == TaskStatus::Queued
1035        }
1036        Operation::Abandon { run } => abandonment_receipt(home, &task, id, &run, &request)?,
1037        _ => anyhow::bail!(
1038            "external effects require their authoritative receipt; no operation was replayed"
1039        ),
1040    };
1041    ensure!(
1042        matches,
1043        "intended task condition is not confirmed; no operation was replayed"
1044    );
1045    outbox.update_decision(id, |d| d.applied("owner-requested reconciliation: exact intended task condition confirmed under its claim; no effect remains necessary"))
1046}
1047
1048/// Read the exact request's committed execution pass or durable pin supersession.
1049/// A transient task status alone never proves either outcome.
1050pub(crate) fn resume_started(home: &Path, task: &Task, inquiry: &str, run: &str) -> Result<bool> {
1051    ensure!(
1052        crate::run::is_run_id(run) && task.runs.iter().any(|id| id == run),
1053        "resume run ownership changed"
1054    );
1055    let state = crate::run::RunState::load_under(run, home)?;
1056    ensure!(state.repo == task.repo, "resume run repository changed");
1057    if task
1058        .superseded_resumes
1059        .get(inquiry)
1060        .is_some_and(|target| target == run)
1061    {
1062        return Ok(true);
1063    }
1064    Ok(state.decision_starts.get(inquiry).is_some_and(|index| {
1065        state
1066            .passes
1067            .get(*index)
1068            .is_some_and(|pass| pass.index == *index)
1069    }))
1070}
1071
1072/// Publication writes the pin and actions_applied marker atomically. Fence the
1073/// publisher and scheduler before treating their absence as pre-effect proof.
1074/// A published pin may already be consumed, so its absence alone is not proof.
1075fn reconcile_resume_decision(
1076    queue: &Queue,
1077    home: &Path,
1078    outbox: &crate::task_inquiry::Outbox,
1079    id: &str,
1080    run: &str,
1081) -> Result<()> {
1082    let Ok(_execution) = outbox.execution_claim(id) else {
1083        return Ok(());
1084    };
1085    reconcile_resume_claimed(queue, home, outbox, id, run)
1086}
1087
1088/// The caller holds this inquiry's execution claim, including on resubmission.
1089fn reconcile_resume_claimed(
1090    queue: &Queue,
1091    home: &Path,
1092    outbox: &crate::task_inquiry::Outbox,
1093    id: &str,
1094    run: &str,
1095) -> Result<()> {
1096    let inquiry = outbox.get(id)?;
1097    let Ok(_claim) = queue.claim(&inquiry.task) else {
1098        return Ok(());
1099    };
1100    let task = queue.get(&inquiry.task)?;
1101    ensure!(task.repo == inquiry.repo, "resume task repository changed");
1102    let decision = inquiry.decision.context("inquiry is informational")?;
1103    if decision.status == crate::task_decision::Status::Resolved {
1104        return Ok(());
1105    }
1106    if resume_started(home, &task, id, run)? {
1107        outbox.update_decision(id, |d| {
1108            d.applied("exact resume execution-start or supersession receipt confirmed")
1109        })?;
1110    } else if !task.action_applied(id)
1111        && !task.dispatched_resumes.contains_key(id)
1112        && !task.superseded_resumes.contains_key(id)
1113        && !task
1114            .resume_override
1115            .as_ref()
1116            .is_some_and(|pin| pin.question_id == id)
1117    {
1118        outbox.update_decision(id, |d| {
1119            d.fail_before_effect("Resume was not published to the queue; the owner may retry the same request or cancel it. No operation was replayed.")
1120        })?;
1121    }
1122    Ok(())
1123}
1124
1125fn abandonment_receipt(
1126    home: &Path,
1127    task: &Task,
1128    id: &str,
1129    run: &str,
1130    request: &str,
1131) -> Result<bool> {
1132    ensure!(
1133        task.runs.iter().any(|own| own == run),
1134        "abandon run ownership changed"
1135    );
1136    let state = crate::run::RunState::load_under(run, home)?;
1137    ensure!(state.repo == task.repo, "abandon run repository changed");
1138    Ok(state
1139        .abandonment_receipts
1140        .get(id)
1141        .is_some_and(|receipt| receipt == request))
1142}
1143
1144fn merge_receipt(
1145    home: &Path,
1146    chat: &str,
1147    action: &crate::chat_merge::Request,
1148) -> Result<Option<serde_json::Value>> {
1149    ensure!(
1150        crate::ask::valid_asset_name(chat) && crate::ask::valid_asset_name(&action.request),
1151        "invalid merge receipt identity"
1152    );
1153    let path = home
1154        .join("chat-controls")
1155        .join(chat)
1156        .join(format!("{}.json", action.request));
1157    let bytes = match std::fs::read(path) {
1158        Ok(bytes) => bytes,
1159        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
1160        Err(error) => return Err(error.into()),
1161    };
1162    let receipt: serde_json::Value = serde_json::from_slice(&bytes)?;
1163    ensure!(
1164        receipt["action"] == serde_json::to_value(action)?,
1165        "merge receipt names another operation"
1166    );
1167    Ok(Some(receipt))
1168}
1169
1170/// Repair the decision projection from independently durable command receipts.
1171/// This starts no workers and retries no operation.
1172pub fn reconcile_decisions(queue: &Queue, home: &Path) -> Result<()> {
1173    let outbox = crate::task_inquiry::Outbox::at(home);
1174    let (inquiries, unreadable) = outbox.list_readable()?;
1175    let mut errors = Vec::new();
1176    if unreadable != 0 {
1177        errors.push(format!("{unreadable} unreadable inquiry record(s)"));
1178    }
1179    for inquiry in inquiries {
1180        let id = inquiry.id.clone();
1181        if let Err(error) = reconcile_inquiry(queue, home, &outbox, inquiry) {
1182            let message = format!(
1183                "Decision receipt reconciliation failed: {error:#}. Inspect this inquiry's receipt before retrying."
1184            );
1185            tracing::warn!("decision {id}: {message}");
1186            if let Err(error) = outbox.update_decision(&id, |d| d.fail(&message)) {
1187                tracing::warn!("decision {id} error could not be persisted: {error:#}");
1188            }
1189            errors.push(format!("{id}: {message}"));
1190        }
1191    }
1192    ensure!(
1193        errors.is_empty(),
1194        "{} decision reconciliation problem(s): {}",
1195        errors.len(),
1196        errors.join("; ")
1197    );
1198    Ok(())
1199}
1200
1201fn reconcile_inquiry(
1202    queue: &Queue,
1203    home: &Path,
1204    outbox: &crate::task_inquiry::Outbox,
1205    inquiry: crate::task_inquiry::Inquiry,
1206) -> Result<()> {
1207    use crate::task_decision::Status;
1208    let Some(decision) = inquiry.decision else {
1209        return Ok(());
1210    };
1211    if decision.status == Status::Resolved {
1212        return Ok(());
1213    }
1214    let Some(request) = decision.request else {
1215        return Ok(());
1216    };
1217    let Ok(command) = serde_json::from_str::<Operation>(&request) else {
1218        return Ok(());
1219    };
1220    if let Operation::Resume { run } = &command {
1221        return reconcile_resume_decision(queue, home, outbox, &inquiry.id, run);
1222    }
1223    let task = queue.get(&inquiry.task)?;
1224    ensure!(task.repo == inquiry.repo, "decision repository changed");
1225    if let Some(receipt) = task.decision_effects.get(&inquiry.id) {
1226        ensure!(
1227            receipt == &request,
1228            "decision receipt binds another command"
1229        );
1230        outbox.update_decision(&inquiry.id, |d| {
1231            d.applied("exact task command receipt confirmed after restart")
1232        })?;
1233        return Ok(());
1234    }
1235    let mut pending_external = false;
1236    let receipt = match command {
1237        Operation::Abandon { run } => {
1238            abandonment_receipt(home, &task, &inquiry.id, &run, &request)?
1239                .then(|| format!("run {run}: exact abandonment receipt committed"))
1240        }
1241        Operation::RerunChecks {
1242            request,
1243            run,
1244            head,
1245            workflows,
1246        } => {
1247            let chat = inquiry.delivered_to.as_deref().unwrap_or_default();
1248            let path = home
1249                .join("chat-controls")
1250                .join(chat)
1251                .join(format!("{request}.json"));
1252            let state = crate::run::RunState::load_under(&run, home)?;
1253            let action = serde_json::json!({
1254                "run": run, "repo": state.repo,
1255                "pr": state.pr.as_ref().map(|pr| pr.url.as_str()),
1256                "head": head, "runs": workflows,
1257            });
1258            std::fs::read(path)
1259                .ok()
1260                .and_then(|bytes| serde_json::from_slice::<serde_json::Value>(&bytes).ok())
1261                .filter(|receipt| receipt["status"] == "applied" && receipt["action"] == action)
1262                .map(|_| format!("chat-controls/{chat}/{request}.json: applied"))
1263        }
1264        Operation::MergePr {
1265            repo,
1266            number,
1267            head,
1268            request,
1269        } => {
1270            let action = crate::chat_merge::Request {
1271                repo,
1272                number,
1273                head,
1274                request,
1275            };
1276            let chat = inquiry
1277                .delivered_to
1278                .as_deref()
1279                .context("merge decision has no chat")?;
1280            let receipt = merge_receipt(home, chat, &action)?;
1281            pending_external = receipt
1282                .as_ref()
1283                .is_some_and(|receipt| receipt["status"] == "pending");
1284            if let Some(receipt) = &receipt
1285                && receipt["status"] != "merged"
1286                && receipt["status"] != "pending"
1287            {
1288                outbox.update_decision(&inquiry.id, |d| d.fail(&format!("Merge outcome requires reconciliation: {}. Reuse the same request ID to check only.", receipt["detail"])))?;
1289            }
1290            receipt
1291                .filter(|receipt| receipt["status"] == "merged")
1292                .map(|receipt| format!("confirmed merge receipt: {}", receipt["detail"]))
1293        }
1294        _ => None,
1295    };
1296    if let Some(receipt) = receipt {
1297        outbox.update_decision(&inquiry.id, |d| d.applied(&receipt))?;
1298    } else if decision.status == Status::InProgress
1299        && !pending_external
1300        && outbox
1301            .get(&inquiry.id)?
1302            .decision
1303            .as_ref()
1304            .is_some_and(|d| d.status == Status::InProgress)
1305    {
1306        let talks = Talks::at(home.join("talks"));
1307        let chat = inquiry
1308            .delivered_to
1309            .as_deref()
1310            .context("executing decision has no chat")?;
1311        if !talks.turn_held(chat) && !crate::chat_worker::turn_worker_active(&talks, chat) {
1312            outbox.update_decision(&inquiry.id, |d| d.fail("Execution ended without a confirmed effect receipt. Inspect the operation before retrying; restart did not replay it."))?;
1313        }
1314    }
1315    Ok(())
1316}
1317
1318/// Record the owner's choice for a decision from an open standing chat. The
1319/// chat agent interprets the owner's request directly, a merge included; no
1320/// quote, consent phrase or task ownership is required. See [`record_decision`].
1321pub fn decide(
1322    talks: &Talks,
1323    home: &Path,
1324    talk: &str,
1325    question: &str,
1326    choice: &str,
1327) -> Result<crate::ask::Question> {
1328    authorize(talks, talk, crate::queue::CHAT_NODE)?;
1329    record_decision(home, question, choice, None)
1330}
1331
1332/// Answer an open decision whose answer the machinery consumes
1333/// ([`crate::task_chat::awaits_decision`]: a merge or release approval, the
1334/// posting gate, triage, a divergence reconcile, a structured choice action).
1335/// The question must still be open and `choice` one of its offered choices;
1336/// the consumer behind it keeps its own state and transition checks.
1337fn record_decision(
1338    home: &Path,
1339    question: &str,
1340    choice: &str,
1341    title: Option<&str>,
1342) -> Result<crate::ask::Question> {
1343    use crate::ask::{Answer, Questions};
1344    let questions = Questions::at(home.join("questions"));
1345    let id = questions.resolve_id(question)?;
1346    let q = questions.get(&id)?;
1347    let queue = Queue::at(home.join("queue"));
1348    let _claims = decision_claims(&queue, &q)?;
1349    for task in queue.list() {
1350        if q.run == task.id
1351            || task.runs.contains(&q.run)
1352            || q.routed_task.as_deref() == Some(&task.id)
1353        {
1354            ensure!(
1355                !task.stale_question(&q),
1356                "question predates task repository reassignment; inspect the current task and release it for fresh execution"
1357            );
1358        }
1359    }
1360    ensure!(
1361        crate::task_chat::awaits_decision(&q),
1362        "question {} is not a decision the machinery waits on; answer it with `magi answer`",
1363        q.short()
1364    );
1365    let (q, ()) = questions.update(&q.id, |r| {
1366        if crate::task_chat::saved_reply_requires_confirmation(home, r) {
1367            ensure!(
1368                crate::task_inquiry::Outbox::at(home)
1369                    .get(&r.id)?
1370                    .decision
1371                    .is_some_and(
1372                        |decision| decision.status != crate::task_decision::Status::Resolved
1373                    ),
1374                "saved decision is settled; no effect remains necessary"
1375            );
1376            r.status = crate::ask::QuestionStatus::Open;
1377            r.answer = None;
1378            r.answered_at = None;
1379            r.answer_authority = None;
1380        }
1381        ensure!(
1382            r.status.open(),
1383            "question {} is already {}",
1384            r.short(),
1385            r.status.as_str()
1386        );
1387        let reply = r.resolve_reply(choice)?.to_owned();
1388        ensure!(
1389            crate::land::approval(Some(&reply)) != crate::land::Approval::Merge || r.merge_target.is_some()
1390                || !(r.node == crate::land::APPROVAL_NODE || (r.node == crate::bump::NOTICE_NODE && r.seat == "release-watch")),
1391            "approval has no recorded PR/head; recover its target or discuss a non-merge operation in chat"
1392        );
1393        let replacement =
1394            r.node == crate::github_text::ASK_NODE && reply == crate::github_text::USE_MY_TEXT;
1395        ensure!(
1396            replacement || title.is_none(),
1397            "--title is only valid for a publication decision's `use my text` choice"
1398        );
1399        let title = if replacement {
1400            let title =
1401                title.context("use my text needs --title with the literal replacement title")?;
1402            ensure!(
1403                !title.trim().is_empty(),
1404                "replacement title must not be empty"
1405            );
1406            Some(title.to_owned())
1407        } else {
1408            None
1409        };
1410        let answer = if r.free_text() {
1411            Answer::Text(reply)
1412        } else {
1413            Answer::Choice(reply)
1414        };
1415        r.publication_title = title;
1416        r.answer(answer)?;
1417        Ok(())
1418    })?;
1419    Ok(q)
1420}
1421
1422/// Fence idle built-in triage answers with grant admission and worker writes.
1423/// Live drivers must remain answerable (grant admission refuses them). Other
1424/// question consumers keep their own claims, including synchronous dismissal.
1425/// Every grant also rechecks answered-but-unsettled effects before acceptance.
1426pub(crate) fn decision_claims(
1427    queue: &Queue,
1428    q: &crate::ask::Question,
1429) -> Result<Vec<crate::queue::Claim>> {
1430    let mut owners: Vec<_> = queue
1431        .list()
1432        .into_iter()
1433        .filter(|task| {
1434            q.run == task.id
1435                || task.runs.contains(&q.run)
1436                || q.routed_task.as_deref() == Some(&task.id)
1437        })
1438        .map(|task| task.id)
1439        .collect();
1440    owners.sort();
1441    let mut claims = Vec::new();
1442    if matches!(
1443        q.node.as_str(),
1444        crate::triage::NODE | crate::triage::DEPS_NODE
1445    ) {
1446        for id in &owners {
1447            if queue.get(id)?.status != TaskStatus::Running {
1448                claims.push(queue.claim(id)?);
1449            }
1450        }
1451    }
1452    for id in owners {
1453        ensure!(
1454            !crate::repair_budget::reconcile::superseded_question(&queue.get(&id)?, q),
1455            "question was superseded by explicit repair receipt recovery; inspect the reconciliation receipt"
1456        );
1457    }
1458    Ok(claims)
1459}
1460
1461/// The conversation this process speaks for, or why it may not act.
1462pub fn authorize(talks: &Talks, run: &str, node: &str) -> Result<Talk> {
1463    if node != crate::queue::CHAT_NODE || run.trim().is_empty() {
1464        bail!("task control requires MAGI_NODE=chat and MAGI_RUN from a standing chat");
1465    }
1466    let id = crate::chat_watch::authorize(talks, run, node)?;
1467    talks.get(&id)
1468}
1469
1470/// The task that recorded `run` (a full run id).
1471fn run_task(queue: &Queue, run: &str) -> Result<Task> {
1472    ensure!(
1473        crate::run::is_run_id(run),
1474        "an execution command needs the full run id"
1475    );
1476    queue
1477        .list()
1478        .into_iter()
1479        .find(|t| t.runs.iter().any(|r| r == run))
1480        .with_context(|| format!("run {run} belongs to no task"))
1481}
1482
1483/// Claim a task from a full or unambiguous-prefix id and read it under the
1484/// claim, never from a lookup made before it.
1485fn claimed(queue: &Queue, reference: &str) -> Result<(crate::queue::Claim, Task)> {
1486    let id = queue.resolve_id(reference)?;
1487    let claim = queue
1488        .claim(&id)
1489        .with_context(|| format!("task {id} is claimed by a running daemon"))?;
1490    let task = queue.get(&id)?;
1491    Ok((claim, task))
1492}
1493
1494fn check_hold_release(task: &Task, operation: &str) -> Result<()> {
1495    match task.status {
1496        TaskStatus::Queued
1497        | TaskStatus::Held
1498        | TaskStatus::Failed
1499        | TaskStatus::Blocked
1500        | TaskStatus::Parked => Ok(()),
1501        TaskStatus::Done => bail!(
1502            "cannot {operation} task {} (done): completed work must not be restarted; create a new task instead",
1503            task.id
1504        ),
1505        TaskStatus::Running => bail!(
1506            "cannot {operation} task {} (running): its run may still be active; use resume or abandon for the existing run instead",
1507            task.id
1508        ),
1509    }
1510}
1511
1512/// Mark a task complete under its queue claim, as `magi task done` does.
1513pub fn done(queue: &Queue, home: &Path, reference: &str) -> Result<Task> {
1514    let (_claim, mut task) = claimed(queue, reference)?;
1515    task.succeed();
1516    // Manual completion also retires earlier attempts when the latest one landed.
1517    crate::daemon::supersede_prior_runs(&task, home);
1518    queue.put(&mut task)?;
1519    Ok(task)
1520}
1521
1522/// Change priority under the same claim and state check as the terminal route.
1523pub fn set_priority(queue: &Queue, reference: &str, priority: i32) -> Result<Task> {
1524    let (_claim, mut task) = claimed(queue, reference)?;
1525    task.set_priority(priority)?;
1526    queue.put(&mut task)?;
1527    Ok(task)
1528}
1529
1530/// Hold a task for the owner.
1531pub fn hold(queue: &Queue, reference: &str, reason: &str) -> Result<Task> {
1532    let (_claim, mut task) = claimed(queue, reference)?;
1533    check_hold_release(&task, "hold")?;
1534    let reason = reason.trim();
1535    task.hold_manual((!reason.is_empty()).then(|| reason.to_owned()));
1536    queue.put(&mut task)?;
1537    Ok(task)
1538}
1539
1540/// Release a task (the same transition as `magi task release`: the attempt
1541/// count restarts, the history stays). An operator hold is released too: the
1542/// owner asked for it.
1543pub fn release(queue: &Queue, reference: &str) -> Result<Task> {
1544    let (_claim, mut task) = claimed(queue, reference)?;
1545    check_hold_release(&task, "release")?;
1546    crate::base_sync_recovery::ensure_generic_release(queue, &task)?;
1547    let run = task.execution_runs().last().cloned();
1548    let preserved = match run {
1549        Some(run) => crate::repair_budget::queue_resumption(queue, &mut task, &run)?,
1550        None => false,
1551    };
1552    if !preserved {
1553        task.release_operator("chat", None);
1554    }
1555    queue.put(&mut task)?;
1556    Ok(task)
1557}
1558
1559/// Change a queued or held task's instruction and queue it again, in one
1560/// save under one claim. Only what [`Task::edit`] allows can be retried; the
1561/// attempt count follows [`Task::release`] (restarts), while runs, passes and
1562/// the resumption history are kept.
1563pub fn retry(
1564    queue: &Queue,
1565    reference: &str,
1566    title: Option<String>,
1567    instruction: &str,
1568) -> Result<Task> {
1569    ensure!(
1570        !instruction.trim().is_empty(),
1571        "the new instruction is empty"
1572    );
1573    let (_claim, mut task) = claimed(queue, reference)?;
1574    if let Some(state) = crate::base_sync_recovery::held_run(queue, &task)
1575        && state
1576            .base_sync_recovery
1577            .stop
1578            .as_ref()
1579            .is_some_and(|stop| stop.kind == crate::base_sync_recovery::StopKind::Conflict)
1580    {
1581        anyhow::bail!(
1582            "retry cannot authorize editing a retained base-sync stop. {} Keep the retained review criteria and use a dedicated repair grant for the narrow resolution.",
1583            state.base_sync_next_action()
1584        );
1585    }
1586    crate::base_sync_recovery::ensure_generic_release(queue, &task)?;
1587    let title = title.unwrap_or_else(|| crate::queue::title_from(instruction, 72));
1588    task.edit(title, instruction.to_owned())?;
1589    task.release_operator("chat", None);
1590    queue.put(&mut task)?;
1591    Ok(task)
1592}
1593
1594/// Resume a stopped, blocked or parked run (its task's latest). Only queues
1595/// the pinned resume; returns the owning task.
1596pub fn resume(queue: &Queue, home: &Path, run: &str) -> Result<Task> {
1597    let task = run_task(queue, run)?;
1598    ensure!(
1599        task.execution_runs().last().map(String::as_str) == Some(run),
1600        "only the task's latest run can be resumed"
1601    );
1602    crate::resume::validate(home, run)?;
1603    ensure!(
1604        crate::resume::pin_queued(queue, run, None, None)?,
1605        "no queued task owns run {run}"
1606    );
1607    queue.get(&task.id)
1608}
1609
1610// These reads and input checks cannot start an effect. Keep them shared by
1611// decision acceptance and execution so invalid input never pins a new request.
1612fn rerun_preflight(
1613    queue: &Queue,
1614    home: &Path,
1615    run: &str,
1616    request: &str,
1617) -> Result<crate::run::RunState> {
1618    run_task(queue, run)?;
1619    let state = crate::run::RunState::load_under(run, home)?;
1620    ensure!(state.pr.is_some(), "the run recorded no pull request");
1621    ensure!(
1622        crate::ask::valid_asset_name(request),
1623        "request must be a safe filename of at most 64 bytes"
1624    );
1625    Ok(state)
1626}
1627
1628/// チャットのリクエスト単位で受付記録を残し、共通遷移でチェックを再実行する。
1629pub async fn rerun_checks(
1630    queue: &Queue,
1631    home: &Path,
1632    talk: &str,
1633    run: &str,
1634    request: &str,
1635    head: &str,
1636    workflows: &[String],
1637) -> Result<Vec<String>> {
1638    let state = rerun_preflight(queue, home, run, request).map_err(BeforeEffect)?;
1639    let dir = home.join("chat-controls").join(talk);
1640    std::fs::create_dir_all(&dir)?;
1641    let lock = std::fs::OpenOptions::new()
1642        .create(true)
1643        .truncate(false)
1644        .write(true)
1645        .open(dir.join(format!("{request}.lock")))?;
1646    crate::pr_head::try_lock_file(&lock).map_err(|error| BeforeEffect(error.into()))?;
1647    let path = dir.join(format!("{request}.json"));
1648    let pr = &state
1649        .pr
1650        .as_ref()
1651        .context("the run recorded no pull request")?
1652        .url;
1653    let action = serde_json::json!({
1654        "run": run, "repo": state.repo, "pr": pr, "head": head, "runs": workflows
1655    });
1656    if path.exists() {
1657        let prior: serde_json::Value = serde_json::from_slice(&std::fs::read(&path)?)?;
1658        if prior["action"] != action {
1659            return Err(BeforeEffect(anyhow::anyhow!(
1660                "request ID already binds a different operation"
1661            ))
1662            .into());
1663        }
1664        ensure!(
1665            prior["status"] == "applied",
1666            "previous request has an uncertain result; inspect its receipt before a new request"
1667        );
1668        return Ok(workflows.to_vec());
1669    }
1670    let record = |status: &str| -> Result<()> {
1671        let tmp = path.with_extension("tmp");
1672        std::fs::write(
1673            &tmp,
1674            serde_json::to_vec(&serde_json::json!({
1675                "action": action, "status": status
1676            }))?,
1677        )?;
1678        std::fs::rename(tmp, &path)?;
1679        Ok(())
1680    };
1681    let operation = format!("chat:{talk}:{request}");
1682    let started = std::sync::atomic::AtomicBool::new(false);
1683    crate::daemon::rerun_checks_once(home, &operation, &state.repo, pr, head, workflows, || {
1684        // Once a receipt exists, failure must remain uncertain even if the
1685        // external command has not returned yet.
1686        started.store(true, std::sync::atomic::Ordering::SeqCst);
1687        record("started")
1688    })
1689    .await
1690    .map_err(|error| {
1691        if started.load(std::sync::atomic::Ordering::SeqCst) {
1692            error
1693        } else {
1694            anyhow::Error::new(BeforeEffect(error))
1695        }
1696    })?;
1697    record("applied")?;
1698    Ok(workflows.to_vec())
1699}
1700
1701/// Abandon a recorded run whose driver is proven gone. No confirmation phrase
1702/// is needed; an unknown or live driver is refused by
1703/// [`crate::driver::abandon_proven_dead`], so a working driver is never broken.
1704pub fn abandon(queue: &Queue, home: &Path, run: &str) -> Result<()> {
1705    run_task(queue, run)?;
1706    crate::driver::abandon_proven_dead(home, run)
1707}
1708
1709/// One line a person or agent can read after a successful command.
1710pub fn describe(task: &Task, what: &str) -> String {
1711    let status = match task.status {
1712        TaskStatus::Queued => "queued",
1713        _ => task.status.as_str(),
1714    };
1715    format!("{what} {} {} ({status})", task.short(), task.title)
1716}
1717
1718#[cfg(test)]
1719mod tests {
1720    use super::*;
1721    use crate::queue::Source;
1722    use jiff::Timestamp;
1723
1724    fn talk(talks: &Talks, id: &str) -> Talk {
1725        let mut t: Talk = serde_json::from_value(serde_json::json!({
1726            "schema":1,"id":id,"repo":".","agent":"worker","status":"open","turns":[],
1727            "created_at":Timestamp::now(),"updated_at":Timestamp::now(),
1728            "seat":crate::agent::SeatState::new("talk","worker",1)
1729        }))
1730        .unwrap();
1731        talks.put(&mut t).unwrap();
1732        t
1733    }
1734
1735    fn filed(queue: &Queue, talk: &str, text: &str) -> Task {
1736        let mut t = Task::new(
1737            text.into(),
1738            text.into(),
1739            ".".into(),
1740            Source::Agent {
1741                run: talk.into(),
1742                node: crate::queue::CHAT_NODE.into(),
1743            },
1744        );
1745        queue.put(&mut t).unwrap();
1746        t
1747    }
1748
1749    #[test]
1750    fn ownerless_import_reconciliation_requires_effect_evidence_not_saved_consent() {
1751        use crate::ask::{Answer, Question, Questions};
1752        let home = tempfile::tempdir().unwrap();
1753        let home = home.path();
1754        let queue = Queue::at(home.join("queue"));
1755        let talks = Talks::at(home.join("talks"));
1756        let questions = Questions::at(home.join("questions"));
1757        let mut q = Question::new(
1758            String::new(),
1759            crate::bump::NOTICE_NODE.into(),
1760            "release-watch".into(),
1761            "Historical release hold".into(),
1762            String::new(),
1763            vec!["hold".into()],
1764        );
1765        q.answer(Answer::Choice("hold".into())).unwrap();
1766        q.answer_delivered = true;
1767        questions.put(&mut q).unwrap();
1768        let source = std::fs::read(questions.path_of(&q.id)).unwrap();
1769        crate::task_chat::sweep(&queue, &talks, &questions, home);
1770        assert!(reconcile_task_decision(&queue, home, "authorized-chat", &q.id).is_err());
1771        let outbox = crate::task_inquiry::Outbox::at(home);
1772        assert_eq!(
1773            outbox.get(&q.id).unwrap().decision.unwrap().status,
1774            crate::task_decision::Status::RetryNeeded
1775        );
1776        let dir = home.join("release-watch-receipts");
1777        std::fs::create_dir_all(&dir).unwrap();
1778        std::fs::write(
1779            dir.join(format!("{}.json", q.id)),
1780            serde_json::to_vec(&crate::release_watch::WatchState {
1781                applied: vec![q.id.clone()],
1782                ..Default::default()
1783            })
1784            .unwrap(),
1785        )
1786        .unwrap();
1787        for _ in 0..2 {
1788            reconcile_task_decision(&queue, home, "authorized-chat", &q.id).unwrap();
1789        }
1790        let decision = outbox.get(&q.id).unwrap().decision.unwrap();
1791        assert_eq!(decision.status, crate::task_decision::Status::Resolved);
1792        assert!(decision.request.is_none());
1793        assert!(decision.source_answer_at.is_none());
1794        assert_eq!(std::fs::read(questions.path_of(&q.id)).unwrap(), source);
1795        assert!(queue.list().is_empty());
1796        assert!(talks.list().is_empty());
1797    }
1798
1799    #[test]
1800    fn resume_recovery_waits_for_the_inquiry_publisher() {
1801        let tmp = tempfile::tempdir().unwrap();
1802        let queue = Queue::at(tmp.path().join("queue"));
1803        let mut task = filed(&queue, "talk-a", "work");
1804        let mut state = crate::run::RunState::new(
1805            task.repo.clone(),
1806            "main".into(),
1807            "base".into(),
1808            "work".into(),
1809            crate::config::Config::default(),
1810        );
1811        state.status = crate::run::RunStatus::Blocked;
1812        state.driver_exited = true;
1813        state.save_under(tmp.path()).unwrap();
1814        task.runs.push(state.id.clone());
1815        queue.put(&mut task).unwrap();
1816        let outbox = crate::task_inquiry::Outbox::at(tmp.path());
1817        let inquiry = outbox
1818            .file(
1819                &task,
1820                Some(state.id.clone()),
1821                "resume".into(),
1822                "Resume?",
1823                "",
1824            )
1825            .unwrap();
1826        let request = serde_json::to_string(&Operation::Resume {
1827            run: state.id.clone(),
1828        })
1829        .unwrap();
1830        outbox
1831            .update_decision(&inquiry.id, |d| {
1832                d.accept(&request)?;
1833                d.start()
1834            })
1835            .unwrap();
1836        let before = outbox.get(&inquiry.id).unwrap().decision.unwrap();
1837        let publisher = outbox.execution_claim(&inquiry.id).unwrap();
1838        reconcile_decisions(&queue, tmp.path()).unwrap();
1839        assert_eq!(outbox.get(&inquiry.id).unwrap().decision.unwrap(), before);
1840        drop(publisher);
1841        reconcile_decisions(&queue, tmp.path()).unwrap();
1842        let recovered = outbox.get(&inquiry.id).unwrap().decision.unwrap();
1843        assert_eq!(recovered.status, crate::task_decision::Status::RetryNeeded);
1844        assert!(recovered.retry_safe);
1845    }
1846
1847    #[test]
1848    fn only_the_chat_seat_of_an_open_talk_is_authorized() {
1849        let tmp = tempfile::tempdir().unwrap();
1850        let talks = Talks::at(tmp.path().join("talks"));
1851        let t = talk(&talks, "talk-a");
1852        assert!(authorize(&talks, &t.id, "chat").is_ok());
1853        assert!(authorize(&talks, &t.id, "deputy").is_err());
1854        assert!(authorize(&talks, &t.id, "").is_err());
1855        assert!(authorize(&talks, "", "chat").is_err());
1856        assert!(
1857            authorize(&talks, "talk-", "chat").is_err(),
1858            "prefix is not an id"
1859        );
1860    }
1861
1862    #[test]
1863    fn tasks_of_any_origin_are_controlled_on_request() {
1864        let tmp = tempfile::tempdir().unwrap();
1865        let queue = Queue::at(tmp.path().join("queue"));
1866        let theirs = filed(&queue, "talk-b", "theirs");
1867        let mut hand = Task::new("h".into(), "h".into(), ".".into(), Source::Human);
1868        hand.hold_manual(Some("operator".into()));
1869        queue.put(&mut hand).unwrap();
1870        // Another chat's task and an operator-held human task are the owner's
1871        // work too: the request goes through without any ownership scope.
1872        assert_eq!(
1873            hold(&queue, &theirs.id, "wait").unwrap().status,
1874            TaskStatus::Held
1875        );
1876        assert_eq!(
1877            release(&queue, &hand.id).unwrap().status,
1878            TaskStatus::Queued
1879        );
1880        let again = retry(&queue, &theirs.id, None, "new").unwrap();
1881        assert_eq!(again.instruction, "new");
1882        assert_eq!(again.status, TaskStatus::Queued);
1883    }
1884
1885    #[test]
1886    fn hold_then_release_keeps_history_and_restarts_attempts() {
1887        let tmp = tempfile::tempdir().unwrap();
1888        let queue = Queue::at(tmp.path().join("queue"));
1889        let mut t = filed(&queue, "talk-a", "work");
1890        t.attempts = 3;
1891        t.runs.push("20260101-000000-aaaa".into());
1892        queue.put(&mut t).unwrap();
1893        let held = hold(&queue, &t.id, "owner asked").unwrap();
1894        assert_eq!(held.status, TaskStatus::Held);
1895        assert_eq!(held.hold_reason.as_deref(), Some("owner asked"));
1896        let back = release(&queue, &t.id).unwrap();
1897        assert_eq!(back.status, TaskStatus::Queued);
1898        assert_eq!(back.attempts, 0);
1899        assert_eq!(back.runs, t.runs);
1900        assert!(back.resumption.is_some());
1901    }
1902
1903    #[test]
1904    fn hold_and_release_refuse_done_and_running_without_saving() {
1905        let tmp = tempfile::tempdir().unwrap();
1906        let queue = Queue::at(tmp.path().join("queue"));
1907        for status in [TaskStatus::Done, TaskStatus::Running] {
1908            let mut t = filed(&queue, "talk-a", "work");
1909            t.start("20260101-000000-aaaa".into());
1910            if status == TaskStatus::Done {
1911                t.succeed();
1912            }
1913            queue.put(&mut t).unwrap();
1914            let before = std::fs::read(queue.path_of(&t.id)).unwrap();
1915            for operation in ["hold", "release"] {
1916                let error = if operation == "hold" {
1917                    hold(&queue, &t.id, "owner asked")
1918                } else {
1919                    release(&queue, &t.id)
1920                }
1921                .unwrap_err()
1922                .to_string();
1923                assert!(error.contains(operation), "{error}");
1924                assert!(error.contains(&t.id), "{error}");
1925                assert!(error.contains(status.as_str()), "{error}");
1926                let guidance = if status == TaskStatus::Done {
1927                    "create a new task"
1928                } else {
1929                    "use resume or abandon"
1930                };
1931                assert!(error.contains(guidance), "{error}");
1932                assert_eq!(std::fs::read(queue.path_of(&t.id)).unwrap(), before);
1933            }
1934        }
1935    }
1936
1937    #[test]
1938    fn hold_and_release_allow_unfinished_inactive_tasks() {
1939        let tmp = tempfile::tempdir().unwrap();
1940        let queue = Queue::at(tmp.path().join("queue"));
1941        for status in [
1942            TaskStatus::Queued,
1943            TaskStatus::Held,
1944            TaskStatus::Failed,
1945            TaskStatus::Blocked,
1946            TaskStatus::Parked,
1947        ] {
1948            for operation in ["hold", "release"] {
1949                let mut t = filed(&queue, "talk-a", "work");
1950                t.status = status;
1951                t.hold_reason = Some("old reason".into());
1952                t.attempts = 3;
1953                t.runs.push("20260101-000000-aaaa".into());
1954                queue.put(&mut t).unwrap();
1955                let changed = if operation == "hold" {
1956                    let held = hold(&queue, &t.id, " new reason ").unwrap();
1957                    assert_eq!(held.status, TaskStatus::Held);
1958                    assert_eq!(held.hold_reason.as_deref(), Some("new reason"));
1959                    assert_eq!(held.attempts, t.attempts);
1960                    held
1961                } else {
1962                    let released = release(&queue, &t.id).unwrap();
1963                    assert_eq!(released.status, TaskStatus::Queued);
1964                    assert_eq!(released.attempts, 0);
1965                    assert_eq!(released.resumption.as_ref().unwrap().source, "chat");
1966                    released
1967                };
1968                assert_eq!(changed.runs, t.runs);
1969                assert_eq!(queue.get(&t.id).unwrap().status, changed.status);
1970            }
1971        }
1972    }
1973
1974    #[test]
1975    fn retry_edits_and_requeues_in_one_save() {
1976        let tmp = tempfile::tempdir().unwrap();
1977        let queue = Queue::at(tmp.path().join("queue"));
1978        let mut t = filed(&queue, "talk-a", "old text");
1979        t.runs.push("20260101-000000-aaaa".into());
1980        t.attempts = 2;
1981        t.hold_manual(Some("stopped".into()));
1982        queue.put(&mut t).unwrap();
1983        let again = retry(&queue, &t.id, None, "new text").unwrap();
1984        assert_eq!(again.instruction, "new text");
1985        assert_eq!(again.status, TaskStatus::Queued);
1986        assert_eq!(again.attempts, 0);
1987        assert_eq!(again.runs, t.runs, "run history is kept");
1988        assert_eq!(again.resumption.as_ref().unwrap().source, "chat");
1989        assert_eq!(again.resumption.as_ref().unwrap().instruction, "new text");
1990        // A running task cannot be edited: nothing is changed.
1991        let mut running = filed(&queue, "talk-a", "busy");
1992        running.start("20260101-000000-bbbb".into());
1993        queue.put(&mut running).unwrap();
1994        assert!(retry(&queue, &running.id, None, "x").is_err());
1995        assert_eq!(queue.get(&running.id).unwrap().instruction, "busy");
1996        assert!(retry(&queue, &t.id, None, "  ").is_err());
1997    }
1998
1999    #[test]
2000    fn execution_commands_need_the_full_id_of_a_recorded_run() {
2001        let tmp = tempfile::tempdir().unwrap();
2002        let queue = Queue::at(tmp.path().join("queue"));
2003        let mut t = filed(&queue, "talk-b", "work");
2004        t.runs.push("20260101-000000-aaaa".into());
2005        queue.put(&mut t).unwrap();
2006        assert_eq!(
2007            run_task(&queue, "20260101-000000-aaaa").unwrap().id,
2008            t.id,
2009            "any chat may address another chat's run"
2010        );
2011        assert!(run_task(&queue, "aaaa").is_err());
2012        assert!(run_task(&queue, "20260101-000000-bbbb").is_err());
2013        assert!(resume(&queue, tmp.path(), "aaaa").is_err());
2014    }
2015
2016    #[test]
2017    fn abandon_needs_no_phrase_but_refuses_unrecorded_and_unknown_runs() {
2018        let tmp = tempfile::tempdir().unwrap();
2019        let queue = Queue::at(tmp.path().join("queue"));
2020        let mut t = filed(&queue, "talk-b", "work");
2021        t.runs.push("20260101-000000-aaaa".into());
2022        queue.put(&mut t).unwrap();
2023        // A run no task recorded is refused before liveness is judged.
2024        assert!(abandon(&queue, tmp.path(), "20260101-000000-bbbb").is_err());
2025        // A recorded run whose driver is not proven dead (here: no state to
2026        // judge at all) is never abandoned.
2027        assert!(abandon(&queue, tmp.path(), "20260101-000000-aaaa").is_err());
2028    }
2029}