Skip to main content

magi/
chat_control.rs

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