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