Skip to main content

magi/
chat_control.rs

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