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