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
49pub(crate) mod standing;
50
51/// Only these operations cross the standing turn's inherited capability.
52/// No shell commands or calling conversation identities are input.
53#[derive(Debug, serde::Serialize, serde::Deserialize)]
54#[serde(tag = "operation", deny_unknown_fields)]
55pub enum Operation {
56    /// Request a recovery effect using machine-layer standing authorization.
57    Standing {
58        /// Task in the current automatic report.
59        task: String,
60        /// Evidence the chat checked, and why it justifies this action.
61        evidence: String,
62        /// Existing typed command; the launcher admits only the recovery allowlist.
63        command: Box<Operation>,
64    },
65    /// Persist owner-authorized follow-through through a turn capability.
66    Goal {
67        /// Typed lifecycle transition; completion is observer-only.
68        command: crate::chat_goal::Command,
69    },
70    /// Reassign an idle task to a different repository without migrating runs.
71    Reassign {
72        /// Task id or unambiguous prefix.
73        task: String,
74        /// Repository path, owner/repo, or unique short name.
75        repo: std::path::PathBuf,
76    },
77    /// Authorize bounded repair through the same transaction as the terminal.
78    GrantRepair {
79        /// Head-bound operator request.
80        request: crate::repair_budget::Request,
81    },
82    /// Reconcile an existing unimported repair receipt; never adds budget.
83    ReconcileRepairGrant {
84        /// Exact owner-authorized recovery identity.
85        request: crate::repair_budget::reconcile::Request,
86    },
87    /// Reconcile a task-local uncertain effect against its durable end condition.
88    ReconcileDecision {
89        /// Stable inquiry id.
90        inquiry: String,
91    },
92    /// Bind a command to its durable inquiry; acceptance is not resolution.
93    ForDecision {
94        /// Stable inquiry id.
95        inquiry: String,
96        /// Existing typed task/run command.
97        command: Box<Operation>,
98    },
99    /// Explicitly confirm no effect remains, including accepted legacy choices.
100    SettleDecision {
101        /// Stable inquiry id.
102        inquiry: String,
103        /// Owner's reason for settlement.
104        reason: String,
105        /// Replacement active inquiry in the same task/chat.
106        replacement: Option<String>,
107    },
108    /// File a new task through the launcher, including from read-only chats.
109    Add {
110        /// Validated filing inputs, without task state or a caller-selected id.
111        filing: Box<Filing>,
112    },
113    /// Mark a task complete using the terminal's transition.
114    Done {
115        /// Task id or unambiguous prefix.
116        task: String,
117        /// Optional explanation retained with the completion event.
118        #[serde(default)]
119        reason: Option<String>,
120        /// Close unfinished work without deleting its runs or branches.
121        #[serde(default)]
122        discard: bool,
123    },
124    /// Restore mistakenly closed unfinished work to an operator hold.
125    Reopen {
126        /// Task id or unambiguous prefix.
127        task: String,
128        /// Required explanation for recovery.
129        reason: String,
130    },
131    /// Change a task's queue priority.
132    Priority {
133        /// Task id or unambiguous prefix.
134        task: String,
135        /// New priority.
136        priority: i32,
137    },
138    /// Merge a PR the owner asked for, once per request.
139    MergePr {
140        /// Exact owner/repository name.
141        repo: String,
142        /// Pull request number.
143        number: u64,
144        /// Full head SHA the chat just read from the forge.
145        head: String,
146        /// Idempotency key minted by the chat agent.
147        request: String,
148    },
149    /// Authorize one bounded base-recovery interval and queue the existing run.
150    RecoverBase {
151        /// Exact retained run ID.
152        run: String,
153        /// Retained HEAD inspected for the owner's request (full SHA or 7+ hex digits).
154        head: String,
155        /// Durable idempotency key; reuse only for identical arguments.
156        request: String,
157    },
158    /// 既存 run の再開を queue に登録する。
159    Resume {
160        /// 完全な run ID。
161        run: String,
162    },
163    /// Queue a Git-only pass over the retained winner.
164    SyncBaseOnly {
165        /// Exact retained run ID.
166        run: String,
167    },
168    /// task を手動保留する。
169    Hold {
170        /// task ID または一意な接頭辞。
171        task: String,
172        /// 保留理由。
173        reason: String,
174    },
175    /// task を保留から解放する。
176    Release {
177        /// task ID または一意な接頭辞。
178        task: String,
179    },
180    /// 指示を変更して再試行する。
181    Retry {
182        /// task ID または一意な接頭辞。
183        task: String,
184        /// 新しいタイトル、省略時は指示から生成する。
185        title: Option<String>,
186        /// 新しい指示全文。
187        instruction: String,
188    },
189    /// PR の失敗した workflow を再実行する。
190    RerunChecks {
191        /// 完全な run ID。
192        run: String,
193        /// 冪等性を保証するリクエスト ID。
194        request: String,
195        /// 観測した PR head。
196        head: String,
197        /// 再実行対象の workflow run ID。
198        workflows: Vec<String>,
199    },
200    /// タスクチャットで所有者の判断を記録する(マージを含む)。
201    Decide {
202        /// 質問 ID(完全または一意な接頭辞)。
203        question: String,
204        /// 記録された選択肢のラベル。
205        choice: String,
206        /// 「use my text」で公開する置換タイトルそのもの。
207        #[serde(default)]
208        title: Option<String>,
209    },
210    /// `magi answer --reply`: the owner's answer to a question, as an ordinary
211    /// answer ([`crate::ask::record_answer`]).
212    Answer {
213        /// Full question id, resolved by the CLI.
214        question: String,
215        /// An offered choice (label or alias), or the free-text answer.
216        reply: String,
217        /// The literal replacement title for the posting gate's `use my text`.
218        #[serde(default)]
219        title: Option<String>,
220    },
221    /// `magi answer --reply-other`: the owner's decision outside the offered
222    /// choices, saved as a note that ends the consultation
223    /// ([`crate::consult::reply_other`]).
224    ReplyOther {
225        /// Full question id, resolved by the CLI.
226        question: String,
227        /// The owner's outcome.
228        text: String,
229    },
230    /// 保存された計画を作成、または適用する。
231    ReconcileRetention {
232        /// 対象タスク ID。
233        task: String,
234        /// 保護する実装の完全な run ID。
235        authority: String,
236        /// 適用する保存済み計画 ID(省略時は計画のみ)。
237        apply: Option<String>,
238    },
239    /// 生存が否定された run を破棄する。
240    Abandon {
241        /// 完全な run ID。
242        run: String,
243    },
244}
245
246/// Inputs prepared by `magi task add` before saving a fresh queue record.
247#[derive(Debug, serde::Serialize, serde::Deserialize)]
248#[serde(deny_unknown_fields)]
249pub struct Filing {
250    /// Task title.
251    pub title: String,
252    /// Complete task instruction.
253    pub instruction: String,
254    /// Validated absolute repository path.
255    pub repo: std::path::PathBuf,
256    /// Filing provenance prepared by the CLI.
257    pub source: crate::queue::Source,
258    /// Resolved implementation imports.
259    pub sources: crate::refs::Sources,
260    /// Optional initial hold reason.
261    pub hold: Option<String>,
262    /// Queue priority.
263    pub priority: i32,
264    /// Use one implementer.
265    pub solo: bool,
266    /// Prioritize execution.
267    pub urgent: bool,
268    /// Optional implementer count.
269    pub implementers: Option<usize>,
270    /// Optional Cargo build output policy.
271    #[serde(default, skip_serializing_if = "Option::is_none")]
272    pub build_cache: Option<crate::config::BuildCache>,
273    /// Absolute attachment paths to copy into the queue.
274    pub attach: Vec<std::path::PathBuf>,
275}
276
277/// Whether this process inherited a launcher control channel.
278/// Provenance-only CLI calls without a channel retain their ordinary local route.
279pub fn has_channel() -> bool {
280    #[cfg(any(unix, windows))]
281    {
282        #[cfg(unix)]
283        let socket = std::env::var_os("MAGI_CHAT_CONTROL_SOCKET").is_some();
284        #[cfg(windows)]
285        let socket = false;
286        std::env::var_os(bridge::CHANNEL_ENV).is_some() || socket
287    }
288    #[cfg(not(any(unix, windows)))]
289    {
290        false
291    }
292}
293
294/// The CLI sends only a typed operation when it inherited a turn capability.
295/// Outside a launched turn the existing, authorized local route remains usable.
296pub async fn dispatch(
297    queue: &Queue,
298    home: &Path,
299    talks: &Talks,
300    talk: &str,
301    operation: Operation,
302) -> Result<String> {
303    if matches!(
304        &operation,
305        Operation::Reassign { .. }
306            | Operation::RecoverBase { .. }
307            | Operation::SyncBaseOnly { .. }
308            | Operation::Goal { .. }
309            | Operation::Standing { .. }
310    ) {
311        #[cfg(unix)]
312        {
313            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");
314        }
315        #[cfg(windows)]
316        {
317            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");
318        }
319        #[cfg(not(any(unix, windows)))]
320        {
321            bail!("authenticated chat control channel is unavailable on this platform");
322        }
323    }
324    if standing_turn() {
325        #[cfg(unix)]
326        return bridge::request(&operation)
327            .context("automatic recovery requires the authenticated chat control channel");
328        #[cfg(windows)]
329        return bridge::request(&operation)
330            .await
331            .context("automatic recovery requires the authenticated chat control channel");
332        #[cfg(not(any(unix, windows)))]
333        bail!("authenticated chat control channel is unavailable on this platform");
334    }
335    #[cfg(unix)]
336    if std::env::var_os(bridge::CHANNEL_ENV).is_some()
337        || std::env::var_os("MAGI_CHAT_CONTROL_SOCKET").is_some()
338    {
339        // The launcher sets this flag for writable seats, including effective
340        // unsandboxed chat turns. execute() still enforces talk authorization.
341        match bridge::request(&operation) {
342            Err(error)
343                if error.is::<bridge::Unavailable>()
344                    && std::env::var("MAGI_ALLOW_WRITE").as_deref() == Ok("1") => {}
345            result => return result,
346        }
347    }
348    #[cfg(windows)]
349    if std::env::var_os(bridge::CHANNEL_ENV).is_some() {
350        return bridge::request(&operation).await;
351    }
352    Box::pin(execute(queue, home, talks, talk, operation)).await
353}
354
355/// The transport supplies immutable launcher authority, never the CLI frame.
356async fn execute_authenticated(
357    queue: &Queue,
358    home: &Path,
359    talks: &Talks,
360    talk: &str,
361    source: crate::chat_goal::Source,
362    operation: Operation,
363) -> Result<String> {
364    if let crate::chat_goal::Source::Standing(scope) = source {
365        return Box::pin(standing::execute(
366            queue, home, talks, talk, &scope, operation,
367        ))
368        .await;
369    }
370    crate::chat_goal::with_source(
371        source,
372        Box::pin(execute(queue, home, talks, talk, operation)),
373    )
374    .await
375}
376
377/// Whether the launcher restricted this CLI to read-only inspection and typed controls.
378/// The environment marker can only restrict the CLI; it cannot grant bridge authority.
379pub fn standing_turn() -> bool {
380    std::env::var_os(standing::ENV).is_some()
381}
382
383async fn execute(
384    queue: &Queue,
385    home: &Path,
386    talks: &Talks,
387    talk: &str,
388    operation: Operation,
389) -> Result<String> {
390    authorize(talks, talk, crate::queue::CHAT_NODE)?;
391    crate::chat_goal::fence(talks, talk, &crate::chat_goal::current_source())?;
392    admit_goal_operation(queue, home, talks, talk, &operation)?;
393    Ok(match operation {
394        Operation::Standing { .. } => bail!(
395            "standing authorization is disabled or this turn is not an eligible automatic report"
396        ),
397        Operation::Goal { command } => {
398            crate::chat_goal::apply(
399                queue,
400                home,
401                talks,
402                talk,
403                &crate::chat_goal::current_source(),
404                command,
405            )
406            .await?
407        }
408        Operation::Reassign { task, repo } => {
409            let cwd = &talks.get(talk)?.repo;
410            let task = crate::task_reassign::reassign(
411                queue,
412                home,
413                cwd,
414                &task,
415                &repo,
416                &format!("chat:{talk}"),
417            )
418            .await?;
419            let mut message = describe(&task, "reassigned");
420            for note in crate::task_reassign::advisory_notes(&task, home) {
421                message.push_str(&format!("\n  {note}"));
422            }
423            message
424        }
425        Operation::ReconcileDecision { inquiry } => {
426            reconcile_task_decision(queue, home, talk, &inquiry)?;
427            format!("decision {inquiry} reconciled from the task's durable state")
428        }
429        Operation::ForDecision { inquiry, command } => {
430            Box::pin(execute_decision(
431                queue, home, talks, talk, &inquiry, *command,
432            ))
433            .await?
434        }
435        Operation::SettleDecision {
436            inquiry,
437            reason,
438            replacement,
439        } => {
440            let outbox = crate::task_inquiry::Outbox::at(home);
441            let record = outbox.get(&inquiry)?;
442            let questions = crate::ask::Questions::at(home.join("questions"));
443            let source = questions.read_history(&inquiry).ok();
444            // A quarantined saved reply is not a live unanswered decision.
445            // The owner can explicitly confirm that its unknown effect needs
446            // no further work without accepting or replaying the old reply.
447            let unaccepted_history = record
448                .decision
449                .as_ref()
450                .is_some_and(|d| d.request.is_none())
451                && source.as_ref().is_some_and(|source| {
452                    source.status == crate::ask::QuestionStatus::Answered
453                        && crate::task_chat::saved_reply_requires_confirmation(home, source)
454                });
455            // Task-backed legacy consumers run under the task claim. Hold it
456            // through settlement; ownerless release consumers use the inquiry
457            // execution fence inside Outbox::settle instead.
458            let _task_claim = if !record.task.is_empty()
459                && (unaccepted_history
460                    || record
461                        .decision
462                        .as_ref()
463                        .is_some_and(|d| d.request.is_some()))
464            {
465                Some(
466                    queue
467                        .claim(&record.task)
468                        .context("decision task is executing")?,
469                )
470            } else {
471                None
472            };
473            if record
474                .decision
475                .as_ref()
476                .is_some_and(|d| d.request.is_none())
477                && let Some(source) = source
478                && !(record.task.is_empty() && record.delivered_to.is_none())
479            {
480                ensure!(
481                    unaccepted_history || !crate::task_chat::awaits_decision(&source),
482                    "a legacy effect still awaits consumer reconciliation; settlement executes no action"
483                );
484            }
485            outbox.settle(&inquiry, talk, &reason, replacement.as_deref())?;
486            format!("settled decision {inquiry}: {reason}")
487        }
488        Operation::Add { filing } => serde_json::to_string(&file_task(queue, *filing)?)?,
489        Operation::Done {
490            task,
491            reason,
492            discard,
493        } => {
494            let claimed = claimed_for_chat(queue, &task, talks, talk)?;
495            let task = Box::pin(crate::task_completion::close_claimed(
496                queue,
497                home,
498                claimed,
499                crate::queue::CompletionActor::Chat(talk.to_owned()),
500                reason,
501                discard,
502            ))
503            .await?;
504            crate::task_completion::describe(&task)
505        }
506        Operation::Reopen { task, reason } => {
507            let (_claim, mut t) = claimed_for_chat(queue, &task, talks, talk)?;
508            let expected = t.clone();
509            let (_guards, context) = Box::pin(crate::task_completion::admit_reopen(
510                &t,
511                home,
512                crate::queue::CompletionActor::Chat(talk.to_owned()),
513                &reason,
514            ))
515            .await?;
516            t.reopen(context)?;
517            queue.commit_completion(&mut t, &expected)?;
518            describe(&t, "reopened on hold")
519        }
520        Operation::Priority { task, priority } => {
521            let t = priority_claimed(
522                queue,
523                claimed_for_chat(queue, &task, talks, talk)?,
524                priority,
525            )?;
526            format!("{} priority now {} - {}", t.short(), t.priority, t.title)
527        }
528        Operation::MergePr {
529            repo,
530            number,
531            head,
532            request,
533        } => crate::chat_merge::merge(
534            home,
535            talks,
536            talk,
537            crate::chat_merge::Request {
538                repo,
539                number,
540                head,
541                request,
542            },
543        )
544        .await
545        .map_err(|error| {
546            if error.is::<crate::chat_merge::BeforeMergeWrite>() {
547                anyhow::Error::new(BeforeEffect(error))
548            } else {
549                error
550            }
551        })?,
552        Operation::ReconcileRepairGrant { request } => serde_json::to_string(
553            &Box::pin(crate::repair_budget::reconcile::apply(queue, home, request)).await?,
554        )?,
555        Operation::GrantRepair { request } => {
556            // Keep run-state admission out of the shared control dispatcher
557            // future, which is also embedded in ordinary CLI task operations.
558            let owner_requested_at = match crate::chat_goal::current_source() {
559                crate::chat_goal::Source::Input { turn } => talks
560                    .get(talk)?
561                    .turns
562                    .get(turn)
563                    .and_then(|turn| crate::talk::owner_send_boundary(&turn.messages)),
564                _ => None,
565            };
566            let receipt = Box::pin(crate::repair_budget::grant_with_claim(
567                queue,
568                home,
569                request,
570                None,
571                owner_requested_at,
572            ))
573            .await
574            .map_err(|error| {
575                if error.is::<crate::repair_budget::PublicationUnknown>() {
576                    error
577                } else {
578                    BeforeEffect(error).into()
579                }
580            })?;
581            serde_json::to_string(&receipt)?
582        }
583        Operation::RecoverBase { run, head, request } => {
584            let result = Box::pin(crate::base_recovery_control::recover(
585                queue,
586                home,
587                crate::base_recovery_control::Request {
588                    run,
589                    head,
590                    request,
591                    actor: talk.to_owned(),
592                    decision: None,
593                    expected_stop: None,
594                },
595            ))
596            .await?;
597            if result.repeated {
598                format!(
599                    "This base-recovery request was already applied to task {}; inspect its current status before continuing",
600                    result.task.id
601                )
602            } else {
603                format!(
604                    "{}; bounded base recovery authorized; the daemon resumes the exact run under its execution lease",
605                    describe(&result.task, "recovery queued for")
606                )
607            }
608        }
609        Operation::Resume { run } => {
610            let t = resume(queue, home, &run)?;
611            format!(
612                "{}; the loop (`magi serve`) resumes the run under its execution lease",
613                describe(&t, "resume queued for")
614            )
615        }
616        Operation::SyncBaseOnly { run } => {
617            ensure!(
618                matches!(
619                    crate::chat_goal::current_source(),
620                    crate::chat_goal::Source::Input { .. }
621                ),
622                "sync-base-only requires an explicit owner request in this chat turn"
623            );
624            let owner = run_task(queue, &run)?;
625            let _claim = queue.claim(&owner.id)?;
626            let mut task = queue.get(&owner.id)?;
627            crate::base_sync_only::queue(&mut task, home, &run)?;
628            queue.put(&mut task)?;
629            describe(&task, "base synchronization only queued for")
630        }
631        Operation::Hold { task, reason } => describe(
632            &hold_claimed(queue, claimed_for_chat(queue, &task, talks, talk)?, &reason)?,
633            "held",
634        ),
635        Operation::Release { task } => describe(
636            &release_claimed(queue, claimed_for_chat(queue, &task, talks, talk)?)?,
637            "released",
638        ),
639        Operation::Retry {
640            task,
641            title,
642            instruction,
643        } => describe(
644            &retry_claimed(
645                queue,
646                claimed_for_chat(queue, &task, talks, talk)?,
647                title,
648                &instruction,
649            )?,
650            "retry queued for",
651        ),
652        Operation::RerunChecks {
653            run,
654            request,
655            head,
656            workflows,
657        } => {
658            let ids = rerun_checks(queue, home, talk, &run, &request, &head, &workflows).await?;
659            format!("requested a rerun of workflow run(s) {}", ids.join(", "))
660        }
661        Operation::Decide {
662            question,
663            choice,
664            title,
665        } => {
666            let q = record_decision(home, &question, &choice, title.as_deref())?;
667            format!(
668                "recorded `{choice}` for decision {}; effect pending until its durable application receipt is confirmed",
669                q.short()
670            )
671        }
672        Operation::Answer {
673            question,
674            reply,
675            title,
676        } => crate::ask::record_answer(
677            &crate::ask::Questions::at(home.join("questions")),
678            &question,
679            &reply,
680            title.as_deref(),
681        )?,
682        Operation::ReplyOther { question, text } => crate::consult::reply_other(
683            &crate::ask::Questions::at(home.join("questions")),
684            &question,
685            &text,
686        )?,
687        Operation::ReconcileRetention {
688            task,
689            authority,
690            apply,
691        } => {
692            let path = Box::pin(crate::retention::reconcile::run_chat(
693                home,
694                &task,
695                &authority,
696                apply.as_deref(),
697                crate::retention::reconcile::ChatRequest {
698                    talks,
699                    conversation: talk,
700                },
701            ))
702            .await?;
703            if apply.is_none() {
704                // Return the complete saved evidence through the capability bridge.
705                crate::retention::reconcile::chat_summary(&path)?
706            } else {
707                format!(
708                    "Applied saved plan {}",
709                    apply.as_deref().unwrap_or_default()
710                )
711            }
712        }
713        Operation::Abandon { run } => {
714            abandon(queue, home, &run)?;
715            format!("abandoned run {run}")
716        }
717    })
718}
719
720fn file_task(queue: &Queue, filing: Filing) -> Result<Task> {
721    let mut task = Task::new(filing.title, filing.instruction, filing.repo, filing.source);
722    task.sources = filing.sources;
723    if let Some(reason) = filing.hold {
724        task.hold_manual(Some(reason));
725    }
726    task.priority = filing.priority;
727    task.solo = filing.solo;
728    task.urgent = filing.urgent;
729    if filing.implementers.is_some() || filing.build_cache.is_some() {
730        task.overrides = Some(crate::queue::RunOverrides {
731            inherit_daemon_options: filing.implementers.is_none(),
732            candidates: filing.implementers,
733            build_cache: filing.build_cache,
734            ..Default::default()
735        });
736    }
737    if filing.attach.is_empty() {
738        queue.put(&mut task)?;
739    } else {
740        queue.attach_and_put(&mut task, &filing.attach)?;
741    }
742    Ok(task)
743}
744
745/// A goal turn cannot redirect existing effects to unrelated work.
746fn admit_goal_operation(
747    queue: &Queue,
748    home: &Path,
749    talks: &Talks,
750    talk_id: &str,
751    operation: &Operation,
752) -> Result<()> {
753    let crate::chat_goal::Source::Goal { id, generation } = crate::chat_goal::current_source()
754    else {
755        return Ok(());
756    };
757    let talk = talks.get(talk_id)?;
758    let goal = talk
759        .goals
760        .iter()
761        .find(|goal| goal.id == id)
762        .context("unknown goal")?;
763    goal.admit(generation)?;
764    ensure!(
765        !goal.owner_input.is_empty(),
766        "this goal was registered under standing authorization; fresh owner input is required with the setting off"
767    );
768    let repo = goal.effective_repo(&talk.repo);
769    let task_allowed = |reference: &str| -> Result<()> {
770        let id = queue.resolve_id(reference)?;
771        ensure!(
772            goal.tasks.contains(&id),
773            "effect targets a task outside this goal"
774        );
775        crate::chat_goal::task_record(queue, &id, repo)?;
776        Ok(())
777    };
778    let run_allowed = |run: &str| -> Result<()> {
779        ensure!(
780            goal.runs.iter().any(|id| id == run)
781                || goal
782                    .tasks
783                    .iter()
784                    .any(|id| crate::chat_goal::task_record(queue, id, repo)
785                        .is_ok_and(|task| task.execution_runs().iter().any(|id| id == run))),
786            "effect targets an execution outside this goal"
787        );
788        crate::chat_goal::run_record(home, run, repo)?;
789        Ok(())
790    };
791    match operation {
792        Operation::Standing { .. } => bail!("standing authorization is disabled for this turn"),
793        Operation::Goal { .. } => {}
794        Operation::Add { filing } => {
795            crate::chat_goal::require_repo("filing", talk_id, &filing.repo, repo)?;
796            ensure!(
797                matches!(&filing.source, crate::queue::Source::Agent { run, node }
798                    if run == talk_id && node == crate::queue::CHAT_NODE),
799                "goal filing must retain this conversation's provenance"
800            );
801        }
802        Operation::Done { discard: true, .. } | Operation::Reopen { .. } => {
803            anyhow::bail!("task discard and reopen require an explicit owner turn");
804        }
805        Operation::Done {
806            task,
807            discard: false,
808            ..
809        }
810        | Operation::Priority { task, .. }
811        | Operation::Hold { task, .. }
812        | Operation::Release { task }
813        | Operation::Retry { task, .. }
814        | Operation::ReconcileRetention { task, .. } => task_allowed(task)?,
815        Operation::GrantRepair { request } => {
816            task_allowed(&request.task)?;
817            run_allowed(&request.run)?;
818        }
819        Operation::ReconcileRepairGrant { request } => {
820            task_allowed(&request.task)?;
821            run_allowed(&request.run)?;
822        }
823        Operation::Resume { run }
824        | Operation::SyncBaseOnly { run }
825        | Operation::RecoverBase { run, .. }
826        | Operation::Abandon { run }
827        | Operation::RerunChecks { run, .. } => run_allowed(run)?,
828        Operation::ForDecision { inquiry, .. }
829        | Operation::ReconcileDecision { inquiry }
830        | Operation::SettleDecision { inquiry, .. } => {
831            let record = crate::task_inquiry::Outbox::at(home).get(inquiry)?;
832            crate::chat_goal::require_repo("inquiry", inquiry, &record.repo, repo)?;
833            task_allowed(&record.task)?;
834            if let Some(run) = record.run {
835                run_allowed(&run)?;
836            }
837        }
838        Operation::Decide { question, .. }
839        | Operation::Answer { question, .. }
840        | Operation::ReplyOther { question, .. } => {
841            let questions = crate::ask::Questions::at(home.join("questions"));
842            let question = questions.get_for_effects(&questions.resolve_id(question)?)?;
843            if question.run_names_task() {
844                task_allowed(&question.run)?;
845            } else {
846                run_allowed(&question.run)?;
847            }
848        }
849        Operation::MergePr {
850            repo: slug, number, ..
851        } => {
852            let expected = format!("https://github.com/{slug}/pull/{number}");
853            let mut found = false;
854            let mut inspect = |run: &str| -> Result<()> {
855                let state = crate::chat_goal::run_record(home, run, repo)?;
856                found |= state
857                    .pr
858                    .as_ref()
859                    .is_some_and(|pr| pr.url.eq_ignore_ascii_case(&expected));
860                Ok(())
861            };
862            for run in &goal.runs {
863                inspect(run)?;
864            }
865            for task in &goal.tasks {
866                for run in crate::chat_goal::task_record(queue, task, repo)?.execution_runs() {
867                    inspect(run)?;
868                }
869            }
870            ensure!(found, "merge targets a pull request outside this goal");
871        }
872        Operation::Reassign { .. } => bail!("automatic goal turns cannot change repository scope"),
873    }
874    Ok(())
875}
876
877/// Run one typed operation on behalf of the owner, retaining failures and
878/// uncertainty. A repeated command never blindly replays a possibly applied
879/// external effect. The underlying operation retains its existing claims and
880/// receipts; this journal is its user-visible lifecycle, not a second worker.
881async fn execute_decision(
882    queue: &Queue,
883    home: &Path,
884    talks: &Talks,
885    chat: &str,
886    id: &str,
887    command: Operation,
888) -> Result<String> {
889    use crate::task_decision::Status;
890    admit_goal_operation(queue, home, talks, chat, &command)?;
891    let outbox = crate::task_inquiry::Outbox::at(home);
892    let _execution = outbox.execution_claim(id)?;
893    let inquiry = outbox.get(id)?;
894    ensure!(
895        inquiry.delivered_to.as_deref() == Some(chat),
896        "decision belongs to another chat"
897    );
898    let task = queue.get(&inquiry.task)?;
899    ensure!(task.repo == inquiry.repo, "decision repository changed");
900    let deferred = matches!(
901        command,
902        Operation::Resume { .. } | Operation::MergePr { .. }
903    );
904    let merge = match &command {
905        Operation::MergePr {
906            repo,
907            number,
908            head,
909            request,
910        } => Some(crate::chat_merge::Request {
911            repo: repo.clone(),
912            number: *number,
913            head: head.clone(),
914            request: request.clone(),
915        }),
916        _ => None,
917    };
918    match &command {
919        Operation::Done { task: target, .. }
920        | Operation::Reopen { task: target, .. }
921        | Operation::Hold { task: target, .. }
922        | Operation::Release { task: target }
923        | Operation::Retry { task: target, .. } => {
924            ensure!(
925                queue.resolve_id(target)? == task.id,
926                "command targets another task"
927            );
928        }
929        Operation::Resume { run }
930        | Operation::Abandon { run }
931        | Operation::RerunChecks { run, .. } => {
932            ensure!(
933                task.runs.contains(run) && inquiry.run.as_ref().is_none_or(|own| own == run),
934                "command targets another execution"
935            );
936            ensure!(
937                queue
938                    .list()
939                    .iter()
940                    .filter(|owner| owner.runs.contains(run))
941                    .count()
942                    == 1,
943                "execution ownership is ambiguous"
944            );
945        }
946        Operation::MergePr { repo, number, .. } => {
947            let run = inquiry
948                .run
949                .as_ref()
950                .or_else(|| task.runs.last())
951                .context("task has no execution for this merge")?;
952            let state = crate::run::RunState::load_under(run, home)?;
953            ensure!(state.id == *run, "merge run identity changed");
954            ensure!(
955                crate::git::same_checkout(&state.repo, &task.repo)?,
956                "merge targets another repository"
957            );
958            let expected = format!("https://github.com/{repo}/pull/{number}");
959            ensure!(
960                state
961                    .pr
962                    .as_ref()
963                    .is_some_and(|pr| pr.url.eq_ignore_ascii_case(&expected)),
964                "merge targets another task or repository"
965            );
966        }
967        _ => bail!("use a task/run effect command with --decision; routed approvals use decide"),
968    }
969    let request = serde_json::to_string(&command)?;
970    let mut decision = inquiry.decision.context("inquiry is informational")?;
971    if decision.request.is_some()
972        && decision.status != Status::Resolved
973        && let Operation::Resume { run } = &command
974    {
975        ensure!(
976            decision.request.as_deref() == Some(&request),
977            "decision already binds a different request"
978        );
979        // Queued also includes successfully published resumes. Reconcile under
980        // the execution claim before permitting any retry, even if the run has
981        // since returned to a resumable state. Only proven non-publication may
982        // enter the retry path below.
983        reconcile_resume_claimed(queue, home, &outbox, id, run)?;
984        decision = outbox
985            .get(id)?
986            .decision
987            .context("inquiry is informational")?;
988        ensure!(
989            decision.status == Status::Resolved || decision.retry_safe,
990            "previous resume remains queued or executing; it will not be replayed"
991        );
992    }
993    if decision.status == Status::Resolved {
994        ensure!(
995            decision.request.as_deref() == Some(&request),
996            "decision resolved for a different request"
997        );
998        return Ok(format!(
999            "decision {id} is already resolved; inspect its outcome history"
1000        ));
1001    }
1002    if let Operation::RerunChecks { run, request, .. } = &command {
1003        // Reject correctable input before binding the decision to this exact
1004        // command. Execution revalidates these reads before taking its lock.
1005        rerun_preflight(queue, home, run, request)?;
1006    }
1007    if let Some(action) = &merge {
1008        // Malformed input must not durably bind this decision to a command
1009        // that can never reach its effect service.
1010        action.validate()?;
1011    }
1012    // Keep admission across acceptance and execution: contention and request
1013    // collisions must not bind a fresh decision to an unstartable operation.
1014    let merge_admission = merge
1015        .as_ref()
1016        .map(|action| crate::chat_merge::admit(home, talks, chat, action))
1017        .transpose()?;
1018    if decision.request.is_none() && decision.status == Status::RetryNeeded {
1019        if let Ok(source) = crate::ask::Questions::at(home.join("questions")).get(id) {
1020            ensure!(
1021                !crate::task_chat::awaits_decision(&source),
1022                "a legacy effect still needs its receipt reconciled before another effect is accepted"
1023            );
1024        }
1025    }
1026    {
1027        // A live task cannot accept a repair grant. Do not prevent decisions
1028        // that its active driver is waiting for by taking its execution claim.
1029        let claim = (queue.get(&task.id)?.status != TaskStatus::Running)
1030            .then(|| queue.claim(&task.id))
1031            .transpose();
1032        let _claim = match claim {
1033            Ok(claim) => claim,
1034            Err(error) => {
1035                // Admission could not start this attempt. Retain the exact
1036                // owner request and pre-effect failure just as execution-side
1037                // claim contention does, without publishing any task effect.
1038                let message = format!(
1039                    "{error:#}. No effect began; retry this same request after resolving the cause, or explicitly settle it."
1040                );
1041                outbox.update_decision(id, |d| {
1042                    let safe = d.request.is_none() || d.retry_safe;
1043                    d.accept(&request)?;
1044                    if safe {
1045                        d.fail_before_effect(&message)
1046                    } else {
1047                        // A prior queued/uncertain attempt still needs its own
1048                        // receipt. Contention is not proof that it never ran.
1049                        Ok(false)
1050                    }
1051                })?;
1052                return Err(anyhow::Error::new(BeforeEffect(error)));
1053            }
1054        };
1055        outbox.update_decision(id, |d| d.accept(&request))?;
1056    }
1057    let late_admission = crate::chat_goal::fence(talks, chat, &crate::chat_goal::current_source())
1058        .and_then(|()| admit_goal_operation(queue, home, talks, chat, &command));
1059    if late_admission.is_ok()
1060        && decision.request.is_some()
1061        && matches!(decision.status, Status::InProgress | Status::RetryNeeded)
1062    {
1063        if decision.retry_safe {
1064            outbox.update_decision(id, |d| {
1065                d.retry_unapplied()?;
1066                d.start()
1067            })?;
1068        } else {
1069            let action = merge
1070                .as_ref()
1071                .context("previous effect needs receipt reconciliation; it will not be replayed")?;
1072            ensure!(
1073                merge_receipt(home, chat, action)?.is_some(),
1074                "previous merge has no receipt; inspect the operation before retrying"
1075            );
1076        }
1077        // The shared merge service only checks the forge once this exact
1078        // request has a receipt; it never issues the merge command twice.
1079    } else if late_admission.is_ok() {
1080        outbox.update_decision(id, |d| d.start())?;
1081    }
1082    let local = match late_admission {
1083        // A refusal now says nothing about a prior attempt that may have acted.
1084        Err(error)
1085            if decision.request.is_some()
1086                && !decision.retry_safe
1087                && (matches!(decision.status, Status::InProgress | Status::RetryNeeded)
1088                    || decision
1089                        .history
1090                        .iter()
1091                        .any(|event| event.status == Status::InProgress)) =>
1092        {
1093            return Err(error);
1094        }
1095        Err(error) => Err(anyhow::Error::new(BeforeEffect(error))),
1096        Ok(()) => {
1097            Box::pin(apply_local_decision(
1098                queue,
1099                home,
1100                id,
1101                &request,
1102                &inquiry.task,
1103                &inquiry.repo,
1104                &command,
1105            ))
1106            .await
1107        }
1108    };
1109    let result = if let Err(error) = local {
1110        Err(error)
1111    } else if let Some(message) = local? {
1112        Ok(message)
1113    } else if let Operation::Resume { run } = &command {
1114        // Validation precedes any write: a refusal means nothing began.
1115        crate::resume::validate(home, run)
1116            .map(|_| ())
1117            .map_err(|e| anyhow::Error::new(BeforeEffect(e)))
1118            .and_then(|()| -> Result<String> {
1119                let pinned =
1120                    crate::resume::pin_queued(queue, run, None, Some(id)).map_err(|error| {
1121                        if error.is::<crate::resume::BeforeQueueWrite>() {
1122                            anyhow::Error::new(BeforeEffect(error))
1123                        } else {
1124                            error
1125                        }
1126                    })?;
1127                if !pinned {
1128                    return Err(anyhow::Error::new(BeforeEffect(anyhow::anyhow!(
1129                        "no queued task owns this run"
1130                    ))));
1131                }
1132                Ok(format!(
1133                    "resume queued for {run}; execution start remains unconfirmed"
1134                ))
1135            })
1136    } else if let Operation::Abandon { run } = &command {
1137        crate::driver::abandon_decision(home, run, id, &request)
1138            .map_err(|error| {
1139                if error.is::<crate::driver::BeforeAbandonWrite>() {
1140                    anyhow::Error::new(BeforeEffect(error))
1141                } else {
1142                    error
1143                }
1144            })
1145            .map(|()| format!("abandoned run {run}"))
1146    } else if let Some(admission) = merge_admission {
1147        crate::chat_merge::merge_admitted(home, merge.as_ref().unwrap().clone(), admission)
1148            .await
1149            .map_err(|error| {
1150                if error.is::<crate::chat_merge::BeforeMergeWrite>() {
1151                    anyhow::Error::new(BeforeEffect(error))
1152                } else {
1153                    error
1154                }
1155            })
1156    } else {
1157        Box::pin(execute(queue, home, talks, chat, command)).await
1158    };
1159    match result {
1160        Ok(message) => {
1161            if let Some(action) = &merge {
1162                if let Some(receipt) = merge_receipt(home, chat, action)? {
1163                    if receipt["status"] == "merged" {
1164                        outbox.update_decision(id, |d| d.applied(&message))?;
1165                    } else if receipt["status"] != "pending" {
1166                        outbox.update_decision(id, |d| {
1167                            d.fail(&format!(
1168                                "{message}; reuse this same request ID to reconcile only"
1169                            ))
1170                        })?;
1171                    }
1172                }
1173            } else if !deferred {
1174                outbox.update_decision(id, |d| {
1175                    d.applied(&format!("typed command completed: {message}"))
1176                })?;
1177            }
1178            if deferred
1179                && outbox
1180                    .get(id)?
1181                    .decision
1182                    .as_ref()
1183                    .is_some_and(|d| d.status == Status::InProgress)
1184            {
1185                outbox.update_decision(id, |d| d.queued())?;
1186            }
1187            // Resume has only been queued. Its execution is confirmed by a
1188            // later scheduler projection, never by this command's return.
1189            Ok(message)
1190        }
1191        Err(error) => {
1192            let message = if error.is::<BeforeEffect>() {
1193                format!(
1194                    "{error:#}. No effect began; retry this same request after resolving the cause, or explicitly settle it."
1195                )
1196            } else {
1197                format!(
1198                    "Operation failed or has an uncertain result: {error:#}. Inspect its receipt before retrying."
1199                )
1200            };
1201            outbox.update_decision(id, |d| {
1202                if error.is::<BeforeEffect>() {
1203                    d.fail_before_effect(&message)
1204                } else {
1205                    d.fail(&message)
1206                }
1207            })?;
1208            Err(error)
1209        }
1210    }
1211}
1212
1213#[derive(Debug, thiserror::Error)]
1214#[error("effect did not start: {0:#}")]
1215struct BeforeEffect(anyhow::Error);
1216
1217/// Commit a task-local effect and its exact receipt under one queue claim.
1218/// The inquiry projection may lag this write, but restart never has to infer
1219/// completion from the task's current status or repeat the operation.
1220async fn apply_local_decision(
1221    queue: &Queue,
1222    home: &Path,
1223    id: &str,
1224    request: &str,
1225    owner: &str,
1226    repo: &Path,
1227    command: &Operation,
1228) -> Result<Option<String>> {
1229    let target = match command {
1230        Operation::Done { task, .. }
1231        | Operation::Reopen { task, .. }
1232        | Operation::Hold { task, .. }
1233        | Operation::Release { task }
1234        | Operation::Retry { task, .. } => task,
1235        _ => return Ok(None),
1236    };
1237    let prepare = async {
1238        let (_claim, mut task) = claimed(queue, target)?;
1239        let expected = task.clone();
1240        ensure!(
1241            task.id == owner && task.repo == repo,
1242            "decision ownership changed"
1243        );
1244        if let Some(prior) = task.decision_effects.get(id) {
1245            ensure!(prior == request, "decision receipt binds another command");
1246            let message = format!("task {}: decision {id} already applied", task.id);
1247            return Ok((_claim, task, message, true, None, expected));
1248        }
1249        let mut close_guard = None;
1250        let message = match command {
1251            Operation::Done {
1252                reason, discard, ..
1253            } => {
1254                let (guards, context) = crate::task_completion::admit_close(
1255                    &task,
1256                    home,
1257                    crate::queue::CompletionActor::Chat(
1258                        crate::task_inquiry::Outbox::at(home)
1259                            .get(id)?
1260                            .delivered_to
1261                            .context("decision has no chat")?,
1262                    ),
1263                    reason.clone(),
1264                    *discard,
1265                )
1266                .await?;
1267                close_guard = Some(guards);
1268                task.succeed(context);
1269                crate::task_completion::describe(&task)
1270            }
1271            Operation::Reopen { reason, .. } => {
1272                let (guards, context) = crate::task_completion::admit_reopen(
1273                    &task,
1274                    home,
1275                    crate::queue::CompletionActor::Chat(
1276                        crate::task_inquiry::Outbox::at(home)
1277                            .get(id)?
1278                            .delivered_to
1279                            .context("decision has no chat")?,
1280                    ),
1281                    reason,
1282                )
1283                .await?;
1284                close_guard = Some(guards);
1285                task.reopen(context)?;
1286                describe(&task, "reopened on hold")
1287            }
1288            Operation::Hold { reason, .. } => {
1289                check_hold_release(&task, "hold")?;
1290                let reason = reason.trim();
1291                task.hold_manual((!reason.is_empty()).then(|| reason.to_owned()));
1292                describe(&task, "held")
1293            }
1294            Operation::Release { .. } => {
1295                check_hold_release(&task, "release")?;
1296                task.release_operator("chat", Some(id));
1297                describe(&task, "released")
1298            }
1299            Operation::Retry {
1300                title, instruction, ..
1301            } => {
1302                ensure!(
1303                    !instruction.trim().is_empty(),
1304                    "the new instruction is empty"
1305                );
1306                let title = title
1307                    .clone()
1308                    .unwrap_or_else(|| crate::queue::title_from(instruction, 72));
1309                task.edit(title, instruction.clone())?;
1310                task.release_operator("chat", Some(id));
1311                describe(&task, "retry queued for")
1312            }
1313            _ => unreachable!("task-local operation checked above"),
1314        };
1315        task.decision_effects
1316            .insert(id.to_owned(), request.to_owned());
1317        Ok::<_, anyhow::Error>((_claim, task, message, false, close_guard, expected))
1318    };
1319    let (_claim, mut task, message, already_applied, close_guard, expected) =
1320        prepare.await.map_err(BeforeEffect)?;
1321    if !already_applied {
1322        if close_guard.is_some() {
1323            queue.commit_completion(&mut task, &expected)?;
1324        } else {
1325            queue.put(&mut task)?;
1326        }
1327    }
1328    if matches!(command, Operation::Done { .. }) {
1329        crate::daemon::supersede_prior_runs(&task, home);
1330    }
1331    Ok(Some(message))
1332}
1333
1334/// Explicit owner-requested reconciliation executes nothing. Under the task
1335/// claim, prove that the exact intended condition already holds; otherwise keep
1336/// uncertainty visible. External effects require their own receipts instead.
1337fn reconcile_task_decision(queue: &Queue, home: &Path, chat: &str, id: &str) -> Result<()> {
1338    let outbox = crate::task_inquiry::Outbox::at(home);
1339    let inquiry = outbox.get(id)?;
1340    ensure!(
1341        inquiry.delivered_to.as_deref() == Some(chat)
1342            || (inquiry.task.is_empty() && inquiry.delivered_to.is_none()),
1343        "decision belongs to another chat"
1344    );
1345    let decision = inquiry.decision.context("inquiry is informational")?;
1346    if decision.status == crate::task_decision::Status::Resolved {
1347        return Ok(());
1348    }
1349    if decision
1350        .request
1351        .as_ref()
1352        .is_none_or(|request| request.starts_with("decision: "))
1353    {
1354        let source = crate::ask::Questions::at(home.join("questions")).read_history(id)?;
1355        crate::task_chat::sync_effect_receipt(home, queue, &source);
1356        ensure!(
1357            outbox
1358                .get(id)?
1359                .decision
1360                .is_some_and(|d| d.status == crate::task_decision::Status::Resolved),
1361            "source effect remains unconfirmed; no operation was replayed"
1362        );
1363        return Ok(());
1364    }
1365    let request = decision
1366        .request
1367        .context("decision has no accepted operation to reconcile")?;
1368    let command: Operation = serde_json::from_str(&request)?;
1369    if let Operation::Resume { run } = &command {
1370        reconcile_resume_decision(queue, home, &outbox, id, run)?;
1371        ensure!(
1372            outbox.get(id)?.decision.is_some_and(|d| {
1373                d.status == crate::task_decision::Status::Resolved || d.retry_safe
1374            }),
1375            "resume remains queued or executing; no operation was replayed"
1376        );
1377        return Ok(());
1378    }
1379    let (_claim, task) = claimed(queue, &inquiry.task)?;
1380    ensure!(task.repo == inquiry.repo, "decision repository changed");
1381    if let Some(receipt) = task.decision_effects.get(id) {
1382        ensure!(
1383            receipt == &request,
1384            "decision receipt binds another command"
1385        );
1386        return outbox.update_decision(id, |d| {
1387            d.applied("exact task command receipt confirmed; no operation replayed")
1388        });
1389    }
1390    let matches = match command {
1391        Operation::Hold {
1392            task: target,
1393            reason,
1394        } => {
1395            queue.resolve_id(&target)? == task.id
1396                && task.status == TaskStatus::Held
1397                && task.hold_reason.as_deref() == Some(reason.trim())
1398        }
1399        Operation::Release { task: target } => {
1400            queue.resolve_id(&target)? == task.id
1401                && task.status == TaskStatus::Queued
1402                && !task.operator_held()
1403        }
1404        Operation::Done { task: target, .. } => {
1405            queue.resolve_id(&target)? == task.id && task.status == TaskStatus::Done
1406        }
1407        Operation::Retry {
1408            task: target,
1409            title,
1410            instruction,
1411        } => {
1412            queue.resolve_id(&target)? == task.id
1413                && task.instruction == instruction
1414                && title.as_ref().is_none_or(|title| *title == task.title)
1415                && task.status == TaskStatus::Queued
1416        }
1417        Operation::Abandon { run } => abandonment_receipt(home, &task, id, &run, &request)?,
1418        _ => anyhow::bail!(
1419            "external effects require their authoritative receipt; no operation was replayed"
1420        ),
1421    };
1422    ensure!(
1423        matches,
1424        "intended task condition is not confirmed; no operation was replayed"
1425    );
1426    outbox.update_decision(id, |d| d.applied("owner-requested reconciliation: exact intended task condition confirmed under its claim; no effect remains necessary"))
1427}
1428
1429/// Read the exact request's committed execution pass or durable pin supersession.
1430/// A transient task status alone never proves either outcome.
1431pub(crate) fn resume_started(home: &Path, task: &Task, inquiry: &str, run: &str) -> Result<bool> {
1432    ensure!(
1433        crate::run::is_run_id(run) && task.runs.iter().any(|id| id == run),
1434        "resume run ownership changed"
1435    );
1436    let state = crate::run::RunState::load_under(run, home)?;
1437    ensure!(state.id == run, "resume run identity changed");
1438    ensure!(
1439        crate::git::same_checkout(&state.repo, &task.repo)?,
1440        "resume run repository changed"
1441    );
1442    if task
1443        .superseded_resumes
1444        .get(inquiry)
1445        .is_some_and(|target| target == run)
1446    {
1447        return Ok(true);
1448    }
1449    Ok(state.decision_starts.get(inquiry).is_some_and(|index| {
1450        state
1451            .passes
1452            .get(*index)
1453            .is_some_and(|pass| pass.index == *index)
1454    }))
1455}
1456
1457/// Publication writes the pin and actions_applied marker atomically. Fence the
1458/// publisher and scheduler before treating their absence as pre-effect proof.
1459/// A published pin may already be consumed, so its absence alone is not proof.
1460fn reconcile_resume_decision(
1461    queue: &Queue,
1462    home: &Path,
1463    outbox: &crate::task_inquiry::Outbox,
1464    id: &str,
1465    run: &str,
1466) -> Result<()> {
1467    let Ok(_execution) = outbox.execution_claim(id) else {
1468        return Ok(());
1469    };
1470    reconcile_resume_claimed(queue, home, outbox, id, run)
1471}
1472
1473/// The caller holds this inquiry's execution claim, including on resubmission.
1474fn reconcile_resume_claimed(
1475    queue: &Queue,
1476    home: &Path,
1477    outbox: &crate::task_inquiry::Outbox,
1478    id: &str,
1479    run: &str,
1480) -> Result<()> {
1481    let inquiry = outbox.get(id)?;
1482    let Ok(_claim) = queue.claim(&inquiry.task) else {
1483        return Ok(());
1484    };
1485    let task = queue.get(&inquiry.task)?;
1486    ensure!(task.repo == inquiry.repo, "resume task repository changed");
1487    let decision = inquiry.decision.context("inquiry is informational")?;
1488    if decision.status == crate::task_decision::Status::Resolved {
1489        return Ok(());
1490    }
1491    if resume_started(home, &task, id, run)? {
1492        outbox.update_decision(id, |d| {
1493            d.applied("exact resume execution-start or supersession receipt confirmed")
1494        })?;
1495    } else if !task.action_applied(id)
1496        && !task.dispatched_resumes.contains_key(id)
1497        && !task.superseded_resumes.contains_key(id)
1498        && !task
1499            .resume_override
1500            .as_ref()
1501            .is_some_and(|pin| pin.question_id == id)
1502    {
1503        outbox.update_decision(id, |d| {
1504            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.")
1505        })?;
1506    }
1507    Ok(())
1508}
1509
1510fn abandonment_receipt(
1511    home: &Path,
1512    task: &Task,
1513    id: &str,
1514    run: &str,
1515    request: &str,
1516) -> Result<bool> {
1517    ensure!(
1518        task.runs.iter().any(|own| own == run),
1519        "abandon run ownership changed"
1520    );
1521    let state = crate::run::RunState::load_under(run, home)?;
1522    ensure!(state.id == run, "abandon run identity changed");
1523    ensure!(
1524        crate::git::same_checkout(&state.repo, &task.repo)?,
1525        "abandon run repository changed"
1526    );
1527    Ok(state
1528        .abandonment_receipts
1529        .get(id)
1530        .is_some_and(|receipt| receipt == request))
1531}
1532
1533fn merge_receipt(
1534    home: &Path,
1535    chat: &str,
1536    action: &crate::chat_merge::Request,
1537) -> Result<Option<serde_json::Value>> {
1538    ensure!(
1539        crate::ask::valid_asset_name(chat) && crate::ask::valid_asset_name(&action.request),
1540        "invalid merge receipt identity"
1541    );
1542    let path = home
1543        .join("chat-controls")
1544        .join(chat)
1545        .join(format!("{}.json", action.request));
1546    let bytes = match std::fs::read(path) {
1547        Ok(bytes) => bytes,
1548        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
1549        Err(error) => return Err(error.into()),
1550    };
1551    let receipt: serde_json::Value = serde_json::from_slice(&bytes)?;
1552    ensure!(
1553        receipt["action"] == serde_json::to_value(action)?,
1554        "merge receipt names another operation"
1555    );
1556    Ok(Some(receipt))
1557}
1558
1559/// Repair the decision projection from independently durable command receipts.
1560/// This starts no workers and retries no operation.
1561pub fn reconcile_decisions(queue: &Queue, home: &Path) -> Result<()> {
1562    let outbox = crate::task_inquiry::Outbox::at(home);
1563    let (inquiries, unreadable) = outbox.list_readable()?;
1564    let mut errors = Vec::new();
1565    if unreadable != 0 {
1566        errors.push(format!("{unreadable} unreadable inquiry record(s)"));
1567    }
1568    for inquiry in inquiries {
1569        let id = inquiry.id.clone();
1570        if let Err(error) = reconcile_inquiry(queue, home, &outbox, inquiry) {
1571            let message = format!(
1572                "Decision receipt reconciliation failed: {error:#}. Inspect this inquiry's receipt before retrying."
1573            );
1574            tracing::warn!("decision {id}: {message}");
1575            if let Err(error) = outbox.update_decision(&id, |d| d.fail(&message)) {
1576                tracing::warn!("decision {id} error could not be persisted: {error:#}");
1577            }
1578            errors.push(format!("{id}: {message}"));
1579        }
1580    }
1581    ensure!(
1582        errors.is_empty(),
1583        "{} decision reconciliation problem(s): {}",
1584        errors.len(),
1585        errors.join("; ")
1586    );
1587    Ok(())
1588}
1589
1590fn reconcile_inquiry(
1591    queue: &Queue,
1592    home: &Path,
1593    outbox: &crate::task_inquiry::Outbox,
1594    inquiry: crate::task_inquiry::Inquiry,
1595) -> Result<()> {
1596    use crate::task_decision::Status;
1597    let Some(decision) = inquiry.decision else {
1598        return Ok(());
1599    };
1600    if decision.status == Status::Resolved {
1601        return Ok(());
1602    }
1603    let Some(request) = decision.request else {
1604        return Ok(());
1605    };
1606    let Ok(command) = serde_json::from_str::<Operation>(&request) else {
1607        return Ok(());
1608    };
1609    if let Operation::Resume { run } = &command {
1610        return reconcile_resume_decision(queue, home, outbox, &inquiry.id, run);
1611    }
1612    let task = queue.get(&inquiry.task)?;
1613    ensure!(task.repo == inquiry.repo, "decision repository changed");
1614    if let Some(receipt) = task.decision_effects.get(&inquiry.id) {
1615        ensure!(
1616            receipt == &request,
1617            "decision receipt binds another command"
1618        );
1619        outbox.update_decision(&inquiry.id, |d| {
1620            d.applied("exact task command receipt confirmed after restart")
1621        })?;
1622        return Ok(());
1623    }
1624    let mut pending_external = false;
1625    let receipt = match command {
1626        Operation::Abandon { run } => {
1627            abandonment_receipt(home, &task, &inquiry.id, &run, &request)?
1628                .then(|| format!("run {run}: exact abandonment receipt committed"))
1629        }
1630        Operation::RerunChecks {
1631            request,
1632            run,
1633            head,
1634            workflows,
1635        } => {
1636            let chat = inquiry.delivered_to.as_deref().unwrap_or_default();
1637            let path = home
1638                .join("chat-controls")
1639                .join(chat)
1640                .join(format!("{request}.json"));
1641            let state = crate::run::RunState::load_under(&run, home)?;
1642            let action = serde_json::json!({
1643                "run": run, "repo": state.repo,
1644                "pr": state.pr.as_ref().map(|pr| pr.url.as_str()),
1645                "head": head, "runs": workflows,
1646            });
1647            std::fs::read(path)
1648                .ok()
1649                .and_then(|bytes| serde_json::from_slice::<serde_json::Value>(&bytes).ok())
1650                .filter(|receipt| receipt["status"] == "applied" && receipt["action"] == action)
1651                .map(|_| format!("chat-controls/{chat}/{request}.json: applied"))
1652        }
1653        Operation::MergePr {
1654            repo,
1655            number,
1656            head,
1657            request,
1658        } => {
1659            let action = crate::chat_merge::Request {
1660                repo,
1661                number,
1662                head,
1663                request,
1664            };
1665            let chat = inquiry
1666                .delivered_to
1667                .as_deref()
1668                .context("merge decision has no chat")?;
1669            let receipt = merge_receipt(home, chat, &action)?;
1670            pending_external = receipt
1671                .as_ref()
1672                .is_some_and(|receipt| receipt["status"] == "pending");
1673            if let Some(receipt) = &receipt
1674                && receipt["status"] != "merged"
1675                && receipt["status"] != "pending"
1676            {
1677                outbox.update_decision(&inquiry.id, |d| d.fail(&format!("Merge outcome requires reconciliation: {}. Reuse the same request ID to check only.", receipt["detail"])))?;
1678            }
1679            receipt
1680                .filter(|receipt| receipt["status"] == "merged")
1681                .map(|receipt| format!("confirmed merge receipt: {}", receipt["detail"]))
1682        }
1683        _ => None,
1684    };
1685    if let Some(receipt) = receipt {
1686        outbox.update_decision(&inquiry.id, |d| d.applied(&receipt))?;
1687    } else if decision.status == Status::InProgress
1688        && !pending_external
1689        && outbox
1690            .get(&inquiry.id)?
1691            .decision
1692            .as_ref()
1693            .is_some_and(|d| d.status == Status::InProgress)
1694    {
1695        let talks = Talks::at(home.join("talks"));
1696        let chat = inquiry
1697            .delivered_to
1698            .as_deref()
1699            .context("executing decision has no chat")?;
1700        if !talks.turn_held(chat) && !crate::chat_worker::turn_worker_active(&talks, chat) {
1701            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."))?;
1702        }
1703    }
1704    Ok(())
1705}
1706
1707/// Record the owner's choice for a decision from an open standing chat. The
1708/// chat agent interprets the owner's request directly, a merge included; no
1709/// quote, consent phrase or task ownership is required. See [`record_decision`].
1710pub fn decide(
1711    talks: &Talks,
1712    home: &Path,
1713    talk: &str,
1714    question: &str,
1715    choice: &str,
1716) -> Result<crate::ask::Question> {
1717    authorize(talks, talk, crate::queue::CHAT_NODE)?;
1718    record_decision(home, question, choice, None)
1719}
1720
1721/// Answer an open decision whose answer the machinery consumes
1722/// ([`crate::task_chat::awaits_decision`]: a merge or release approval, the
1723/// posting gate, triage, a divergence reconcile, a structured choice action).
1724/// The question must still be open and `choice` one of its offered choices;
1725/// the consumer behind it keeps its own state and transition checks.
1726fn record_decision(
1727    home: &Path,
1728    question: &str,
1729    choice: &str,
1730    title: Option<&str>,
1731) -> Result<crate::ask::Question> {
1732    use crate::ask::{Answer, Questions};
1733    let questions = Questions::at(home.join("questions"));
1734    let id = questions.resolve_id(question)?;
1735    let q = questions.get(&id)?;
1736    let queue = Queue::at(home.join("queue"));
1737    let _claims = decision_claims(&queue, &q)?;
1738    for task in queue.list() {
1739        if q.run == task.id
1740            || task.runs.contains(&q.run)
1741            || q.routed_task.as_deref() == Some(&task.id)
1742        {
1743            ensure!(
1744                !task.stale_question(&q),
1745                "question predates task repository reassignment; inspect the current task and release it for fresh execution"
1746            );
1747        }
1748    }
1749    ensure!(
1750        crate::task_chat::awaits_decision(&q),
1751        "question {} is not a decision the machinery waits on; answer it with `magi answer`",
1752        q.short()
1753    );
1754    let (q, ()) = questions.update(&q.id, |r| {
1755        if crate::task_chat::saved_reply_requires_confirmation(home, r) {
1756            ensure!(
1757                crate::task_inquiry::Outbox::at(home)
1758                    .get(&r.id)?
1759                    .decision
1760                    .is_some_and(
1761                        |decision| decision.status != crate::task_decision::Status::Resolved
1762                    ),
1763                "saved decision is settled; no effect remains necessary"
1764            );
1765            r.status = crate::ask::QuestionStatus::Open;
1766            r.answer = None;
1767            r.answered_at = None;
1768            r.answer_authority = None;
1769        }
1770        ensure!(
1771            r.status.open(),
1772            "question {} is already {}",
1773            r.short(),
1774            r.status.as_str()
1775        );
1776        let reply = r.resolve_reply(choice)?.to_owned();
1777        ensure!(
1778            crate::land::approval(Some(&reply)) != crate::land::Approval::Merge || r.merge_target.is_some()
1779                || !(r.node == crate::land::APPROVAL_NODE || (r.node == crate::bump::NOTICE_NODE && r.seat == "release-watch")),
1780            "approval has no recorded PR/head; recover its target or discuss a non-merge operation in chat"
1781        );
1782        let replacement =
1783            r.node == crate::github_text::ASK_NODE && reply == crate::github_text::USE_MY_TEXT;
1784        ensure!(
1785            replacement || title.is_none(),
1786            "--title is only valid for a publication decision's `use my text` choice"
1787        );
1788        let title = if replacement {
1789            let title =
1790                title.context("use my text needs --title with the literal replacement title")?;
1791            ensure!(
1792                !title.trim().is_empty(),
1793                "replacement title must not be empty"
1794            );
1795            Some(title.to_owned())
1796        } else {
1797            None
1798        };
1799        let answer = if r.free_text() {
1800            Answer::Text(reply)
1801        } else {
1802            Answer::Choice(reply)
1803        };
1804        r.publication_title = title;
1805        r.answer(answer)?;
1806        Ok(())
1807    })?;
1808    Ok(q)
1809}
1810
1811/// Fence idle built-in triage answers with grant admission and worker writes.
1812/// Live drivers must remain answerable (grant admission refuses them). Other
1813/// question consumers keep their own claims, including synchronous dismissal.
1814/// Every grant also rechecks answered-but-unsettled effects before acceptance.
1815pub(crate) fn decision_claims(
1816    queue: &Queue,
1817    q: &crate::ask::Question,
1818) -> Result<Vec<crate::queue::Claim>> {
1819    let mut owners: Vec<_> = queue
1820        .list()
1821        .into_iter()
1822        .filter(|task| {
1823            q.run == task.id
1824                || task.runs.contains(&q.run)
1825                || q.routed_task.as_deref() == Some(&task.id)
1826        })
1827        .map(|task| task.id)
1828        .collect();
1829    owners.sort();
1830    let mut claims = Vec::new();
1831    if matches!(
1832        q.node.as_str(),
1833        crate::triage::NODE | crate::triage::DEPS_NODE
1834    ) {
1835        for id in &owners {
1836            if queue.get(id)?.status != TaskStatus::Running {
1837                claims.push(queue.claim(id)?);
1838            }
1839        }
1840    }
1841    for id in owners {
1842        ensure!(
1843            !crate::repair_budget::reconcile::superseded_question(&queue.get(&id)?, q),
1844            "question was superseded by explicit repair receipt recovery; inspect the reconciliation receipt"
1845        );
1846    }
1847    Ok(claims)
1848}
1849
1850/// The conversation this process speaks for, or why it may not act.
1851pub fn authorize(talks: &Talks, run: &str, node: &str) -> Result<Talk> {
1852    if node != crate::queue::CHAT_NODE || run.trim().is_empty() {
1853        bail!("task control requires MAGI_NODE=chat and MAGI_RUN from a standing chat");
1854    }
1855    let id = crate::chat_watch::authorize(talks, run, node)?;
1856    talks.get(&id)
1857}
1858
1859/// The task that recorded `run` (a full run id).
1860fn run_task(queue: &Queue, run: &str) -> Result<Task> {
1861    ensure!(
1862        crate::run::is_run_id(run),
1863        "an execution command needs the full run id"
1864    );
1865    queue
1866        .list()
1867        .into_iter()
1868        .find(|t| t.runs.iter().any(|r| r == run))
1869        .with_context(|| format!("run {run} belongs to no task"))
1870}
1871
1872/// Claim a task from a full or unambiguous-prefix id and read it under the
1873/// claim, never from a lookup made before it.
1874fn claimed(queue: &Queue, reference: &str) -> Result<(crate::queue::Claim, Task)> {
1875    let id = queue.resolve_id(reference)?;
1876    let claim = queue
1877        .claim(&id)
1878        .with_context(|| format!("task {id} is claimed by a running daemon"))?;
1879    let task = queue.get(&id)?;
1880    Ok((claim, task))
1881}
1882
1883fn claimed_for_chat(
1884    queue: &Queue,
1885    reference: &str,
1886    talks: &Talks,
1887    chat: &str,
1888) -> Result<(crate::queue::Claim, Task)> {
1889    let claimed = claimed(queue, reference)?;
1890    if let crate::chat_goal::Source::Goal { id, generation } = crate::chat_goal::current_source() {
1891        let talk = talks.get(chat)?;
1892        let goal = talk
1893            .goals
1894            .iter()
1895            .find(|goal| goal.id == id)
1896            .context("unknown goal")?;
1897        goal.admit(generation)?;
1898        let task = &claimed.1;
1899        ensure!(
1900            goal.tasks.contains(&task.id),
1901            "effect targets a task outside this goal"
1902        );
1903        crate::chat_goal::require_repo(
1904            "task",
1905            &task.id,
1906            &task.repo,
1907            goal.effective_repo(&talk.repo),
1908        )?;
1909    }
1910    Ok(claimed)
1911}
1912
1913fn check_hold_release(task: &Task, operation: &str) -> Result<()> {
1914    match task.status {
1915        TaskStatus::Queued
1916        | TaskStatus::Held
1917        | TaskStatus::Failed
1918        | TaskStatus::Blocked
1919        | TaskStatus::Parked => Ok(()),
1920        TaskStatus::Done => bail!(
1921            "cannot {operation} task {} (done): completed work must not be restarted; create a new task instead",
1922            task.id
1923        ),
1924        TaskStatus::Running => bail!(
1925            "cannot {operation} task {} (running): its run may still be active; use resume or abandon for the existing run instead",
1926            task.id
1927        ),
1928    }
1929}
1930
1931/// Mark a task complete as a terminal caller, using the audited close transition.
1932pub async fn done(
1933    queue: &Queue,
1934    home: &Path,
1935    reference: &str,
1936    reason: Option<String>,
1937    discard: bool,
1938) -> Result<Task> {
1939    crate::task_completion::close(
1940        queue,
1941        home,
1942        reference,
1943        crate::queue::CompletionActor::Cli,
1944        reason,
1945        discard,
1946    )
1947    .await
1948}
1949
1950/// Change priority under the same claim and state check as the terminal route.
1951pub fn set_priority(queue: &Queue, reference: &str, priority: i32) -> Result<Task> {
1952    priority_claimed(queue, claimed(queue, reference)?, priority)
1953}
1954
1955fn priority_claimed(
1956    queue: &Queue,
1957    (_claim, mut task): (crate::queue::Claim, Task),
1958    priority: i32,
1959) -> Result<Task> {
1960    task.set_priority(priority)?;
1961    queue.put(&mut task)?;
1962    Ok(task)
1963}
1964
1965/// Hold a task for the owner.
1966pub fn hold(queue: &Queue, reference: &str, reason: &str) -> Result<Task> {
1967    hold_claimed(queue, claimed(queue, reference)?, reason)
1968}
1969
1970fn hold_claimed(
1971    queue: &Queue,
1972    (_claim, mut task): (crate::queue::Claim, Task),
1973    reason: &str,
1974) -> Result<Task> {
1975    check_hold_release(&task, "hold")?;
1976    let reason = reason.trim();
1977    task.hold_manual((!reason.is_empty()).then(|| reason.to_owned()));
1978    queue.put(&mut task)?;
1979    Ok(task)
1980}
1981
1982/// Release a task (the same transition as `magi task release`: the attempt
1983/// count restarts, the history stays). An operator hold is released too: the
1984/// owner asked for it.
1985pub fn release(queue: &Queue, reference: &str) -> Result<Task> {
1986    release_claimed(queue, claimed(queue, reference)?)
1987}
1988
1989fn release_claimed(queue: &Queue, (_claim, mut task): (crate::queue::Claim, Task)) -> Result<Task> {
1990    check_hold_release(&task, "release")?;
1991    crate::base_sync_recovery::ensure_generic_release(queue, &task)?;
1992    let run = task.execution_runs().last().cloned();
1993    let preserved = match run {
1994        Some(run) => crate::repair_budget::queue_resumption(queue, &mut task, &run)?,
1995        None => false,
1996    };
1997    if !preserved {
1998        task.release_operator("chat", None);
1999    }
2000    queue.put(&mut task)?;
2001    Ok(task)
2002}
2003
2004/// Change a queued or held task's instruction and queue it again, in one
2005/// save under one claim. Only what [`Task::edit`] allows can be retried; the
2006/// attempt count follows [`Task::release`] (restarts), while runs, passes and
2007/// the resumption history are kept.
2008pub fn retry(
2009    queue: &Queue,
2010    reference: &str,
2011    title: Option<String>,
2012    instruction: &str,
2013) -> Result<Task> {
2014    retry_claimed(queue, claimed(queue, reference)?, title, instruction)
2015}
2016
2017fn retry_claimed(
2018    queue: &Queue,
2019    (_claim, mut task): (crate::queue::Claim, Task),
2020    title: Option<String>,
2021    instruction: &str,
2022) -> Result<Task> {
2023    ensure!(
2024        !instruction.trim().is_empty(),
2025        "the new instruction is empty"
2026    );
2027    if let Some(state) = crate::base_sync_recovery::held_run(queue, &task)
2028        && state
2029            .base_sync_recovery
2030            .stop
2031            .as_ref()
2032            .is_some_and(|stop| stop.kind == crate::base_sync_recovery::StopKind::Conflict)
2033    {
2034        anyhow::bail!(
2035            "retry cannot authorize editing a retained base-sync stop. {}",
2036            state.base_sync_next_action()
2037        );
2038    }
2039    crate::base_sync_recovery::ensure_generic_release(queue, &task)?;
2040    let title = title.unwrap_or_else(|| crate::queue::title_from(instruction, 72));
2041    task.edit(title, instruction.to_owned())?;
2042    task.release_operator("chat", None);
2043    queue.put(&mut task)?;
2044    Ok(task)
2045}
2046
2047/// Resume a stopped, blocked or parked run (its task's latest). Only queues
2048/// the pinned resume; returns the owning task.
2049pub fn resume(queue: &Queue, home: &Path, run: &str) -> Result<Task> {
2050    let task = run_task(queue, run)?;
2051    ensure!(
2052        task.execution_runs().last().map(String::as_str) == Some(run),
2053        "only the task's latest run can be resumed"
2054    );
2055    crate::resume::validate(home, run)?;
2056    ensure!(
2057        crate::resume::pin_queued(queue, run, None, None)?,
2058        "no queued task owns run {run}"
2059    );
2060    queue.get(&task.id)
2061}
2062
2063// These reads and input checks cannot start an effect. Keep them shared by
2064// decision acceptance and execution so invalid input never pins a new request.
2065fn rerun_preflight(
2066    queue: &Queue,
2067    home: &Path,
2068    run: &str,
2069    request: &str,
2070) -> Result<crate::run::RunState> {
2071    run_task(queue, run)?;
2072    let state = crate::run::RunState::load_under(run, home)?;
2073    ensure!(state.pr.is_some(), "the run recorded no pull request");
2074    ensure!(
2075        crate::ask::valid_asset_name(request),
2076        "request must be a safe filename of at most 64 bytes"
2077    );
2078    Ok(state)
2079}
2080
2081/// チャットのリクエスト単位で受付記録を残し、共通遷移でチェックを再実行する。
2082pub async fn rerun_checks(
2083    queue: &Queue,
2084    home: &Path,
2085    talk: &str,
2086    run: &str,
2087    request: &str,
2088    head: &str,
2089    workflows: &[String],
2090) -> Result<Vec<String>> {
2091    let state = rerun_preflight(queue, home, run, request).map_err(BeforeEffect)?;
2092    let dir = home.join("chat-controls").join(talk);
2093    std::fs::create_dir_all(&dir)?;
2094    let lock = std::fs::OpenOptions::new()
2095        .create(true)
2096        .truncate(false)
2097        .write(true)
2098        .open(dir.join(format!("{request}.lock")))?;
2099    crate::pr_head::try_lock_file(&lock).map_err(|error| BeforeEffect(error.into()))?;
2100    let path = dir.join(format!("{request}.json"));
2101    let pr = &state
2102        .pr
2103        .as_ref()
2104        .context("the run recorded no pull request")?
2105        .url;
2106    let action = serde_json::json!({
2107        "run": run, "repo": state.repo, "pr": pr, "head": head, "runs": workflows
2108    });
2109    if path.exists() {
2110        let prior: serde_json::Value = serde_json::from_slice(&std::fs::read(&path)?)?;
2111        if prior["action"] != action {
2112            return Err(BeforeEffect(anyhow::anyhow!(
2113                "request ID already binds a different operation"
2114            ))
2115            .into());
2116        }
2117        ensure!(
2118            prior["status"] == "applied",
2119            "previous request has an uncertain result; inspect its receipt before a new request"
2120        );
2121        return Ok(workflows.to_vec());
2122    }
2123    let record = |status: &str| -> Result<()> {
2124        let tmp = path.with_extension("tmp");
2125        std::fs::write(
2126            &tmp,
2127            serde_json::to_vec(&serde_json::json!({
2128                "action": action, "status": status
2129            }))?,
2130        )?;
2131        std::fs::rename(tmp, &path)?;
2132        Ok(())
2133    };
2134    let operation = format!("chat:{talk}:{request}");
2135    let started = std::sync::atomic::AtomicBool::new(false);
2136    crate::daemon::rerun_checks_once(home, &operation, &state.repo, pr, head, workflows, || {
2137        // Once a receipt exists, failure must remain uncertain even if the
2138        // external command has not returned yet.
2139        started.store(true, std::sync::atomic::Ordering::SeqCst);
2140        record("started")
2141    })
2142    .await
2143    .map_err(|error| {
2144        if started.load(std::sync::atomic::Ordering::SeqCst) {
2145            error
2146        } else {
2147            anyhow::Error::new(BeforeEffect(error))
2148        }
2149    })?;
2150    record("applied")?;
2151    Ok(workflows.to_vec())
2152}
2153
2154/// Abandon a recorded run whose driver is proven gone. No confirmation phrase
2155/// is needed; an unknown or live driver is refused by
2156/// [`crate::driver::abandon_proven_dead`], so a working driver is never broken.
2157pub fn abandon(queue: &Queue, home: &Path, run: &str) -> Result<()> {
2158    run_task(queue, run)?;
2159    crate::driver::abandon_proven_dead(home, run)
2160}
2161
2162/// One line a person or agent can read after a successful command.
2163pub fn describe(task: &Task, what: &str) -> String {
2164    let status = match task.status {
2165        TaskStatus::Queued => "queued",
2166        _ => task.status.as_str(),
2167    };
2168    format!("{what} {} {} ({status})", task.short(), task.title)
2169}
2170
2171#[cfg(test)]
2172mod tests {
2173    use super::*;
2174    use crate::queue::Source;
2175    use jiff::Timestamp;
2176
2177    fn talk(talks: &Talks, id: &str) -> Talk {
2178        let mut t: Talk = serde_json::from_value(serde_json::json!({
2179            "schema":1,"id":id,"repo":".","agent":"worker","status":"open","turns":[],
2180            "created_at":Timestamp::now(),"updated_at":Timestamp::now(),
2181            "seat":crate::agent::SeatState::new("talk","worker",1)
2182        }))
2183        .unwrap();
2184        talks.put(&mut t).unwrap();
2185        t
2186    }
2187
2188    fn filed(queue: &Queue, talk: &str, text: &str) -> Task {
2189        let mut t = Task::new(
2190            text.into(),
2191            text.into(),
2192            ".".into(),
2193            Source::Agent {
2194                run: talk.into(),
2195                node: crate::queue::CHAT_NODE.into(),
2196            },
2197        );
2198        queue.put(&mut t).unwrap();
2199        t
2200    }
2201
2202    #[tokio::test]
2203    async fn direct_chat_completion_supersedes_the_earlier_blocked_run() {
2204        use crate::run::{RunState, RunStatus};
2205
2206        let dir = tempfile::tempdir().unwrap();
2207        let home = dir.path();
2208        let talks = Talks::at(home.join("talks"));
2209        let queue = Queue::at(home.join("queue"));
2210        let talk = talk(&talks, "talk-a");
2211        let mut task = filed(&queue, &talk.id, "deliver");
2212        for status in [RunStatus::Blocked, RunStatus::Merged] {
2213            let mut run = RunState::new(
2214                task.repo.clone(),
2215                "main".into(),
2216                "base".into(),
2217                task.instruction.clone(),
2218                crate::config::Config::default(),
2219            );
2220            run.status = status;
2221            run.driver_exited = true;
2222            run.reserve_under(home).unwrap();
2223            task.link_run(&run.id);
2224        }
2225        queue.put(&mut task).unwrap();
2226        execute(
2227            &queue,
2228            home,
2229            &talks,
2230            &talk.id,
2231            Operation::Done {
2232                task: task.id.clone(),
2233                reason: None,
2234                discard: false,
2235            },
2236        )
2237        .await
2238        .unwrap();
2239        assert_eq!(
2240            RunState::load_under(&task.runs[0], home).unwrap().status,
2241            RunStatus::Superseded
2242        );
2243    }
2244
2245    #[test]
2246    fn ownerless_import_reconciliation_requires_effect_evidence_not_saved_consent() {
2247        use crate::ask::{Answer, Question, Questions};
2248        let home = tempfile::tempdir().unwrap();
2249        let home = home.path();
2250        let queue = Queue::at(home.join("queue"));
2251        let talks = Talks::at(home.join("talks"));
2252        let questions = Questions::at(home.join("questions"));
2253        let mut q = Question::new(
2254            String::new(),
2255            crate::bump::NOTICE_NODE.into(),
2256            "release-watch".into(),
2257            "Historical release hold".into(),
2258            String::new(),
2259            vec!["hold".into()],
2260        );
2261        q.answer(Answer::Choice("hold".into())).unwrap();
2262        q.answer_delivered = true;
2263        questions.put(&mut q).unwrap();
2264        let source = std::fs::read(questions.path_of(&q.id)).unwrap();
2265        crate::task_chat::sweep(&queue, &talks, &questions, home);
2266        assert!(reconcile_task_decision(&queue, home, "authorized-chat", &q.id).is_err());
2267        let outbox = crate::task_inquiry::Outbox::at(home);
2268        assert_eq!(
2269            outbox.get(&q.id).unwrap().decision.unwrap().status,
2270            crate::task_decision::Status::RetryNeeded
2271        );
2272        let dir = home.join("release-watch-receipts");
2273        std::fs::create_dir_all(&dir).unwrap();
2274        std::fs::write(
2275            dir.join(format!("{}.json", q.id)),
2276            serde_json::to_vec(&crate::release_watch::WatchState {
2277                applied: vec![q.id.clone()],
2278                ..Default::default()
2279            })
2280            .unwrap(),
2281        )
2282        .unwrap();
2283        for _ in 0..2 {
2284            reconcile_task_decision(&queue, home, "authorized-chat", &q.id).unwrap();
2285        }
2286        let decision = outbox.get(&q.id).unwrap().decision.unwrap();
2287        assert_eq!(decision.status, crate::task_decision::Status::Resolved);
2288        assert!(decision.request.is_none());
2289        assert!(decision.source_answer_at.is_none());
2290        assert_eq!(std::fs::read(questions.path_of(&q.id)).unwrap(), source);
2291        assert!(queue.list().is_empty());
2292        assert!(talks.list().is_empty());
2293    }
2294
2295    #[test]
2296    fn resume_recovery_waits_for_the_inquiry_publisher() {
2297        let tmp = tempfile::tempdir().unwrap();
2298        let queue = Queue::at(tmp.path().join("queue"));
2299        let mut task = filed(&queue, "talk-a", "work");
2300        let mut state = crate::run::RunState::new(
2301            task.repo.clone(),
2302            "main".into(),
2303            "base".into(),
2304            "work".into(),
2305            crate::config::Config::default(),
2306        );
2307        state.status = crate::run::RunStatus::Blocked;
2308        state.driver_exited = true;
2309        state.save_under(tmp.path()).unwrap();
2310        task.runs.push(state.id.clone());
2311        queue.put(&mut task).unwrap();
2312        let outbox = crate::task_inquiry::Outbox::at(tmp.path());
2313        let inquiry = outbox
2314            .file(
2315                &task,
2316                Some(state.id.clone()),
2317                "resume".into(),
2318                "Resume?",
2319                "",
2320            )
2321            .unwrap();
2322        let request = serde_json::to_string(&Operation::Resume {
2323            run: state.id.clone(),
2324        })
2325        .unwrap();
2326        outbox
2327            .update_decision(&inquiry.id, |d| {
2328                d.accept(&request)?;
2329                d.start()
2330            })
2331            .unwrap();
2332        let before = outbox.get(&inquiry.id).unwrap().decision.unwrap();
2333        let publisher = outbox.execution_claim(&inquiry.id).unwrap();
2334        reconcile_decisions(&queue, tmp.path()).unwrap();
2335        assert_eq!(outbox.get(&inquiry.id).unwrap().decision.unwrap(), before);
2336        drop(publisher);
2337        reconcile_decisions(&queue, tmp.path()).unwrap();
2338        let recovered = outbox.get(&inquiry.id).unwrap().decision.unwrap();
2339        assert_eq!(recovered.status, crate::task_decision::Status::RetryNeeded);
2340        assert!(recovered.retry_safe);
2341    }
2342
2343    #[tokio::test]
2344    async fn resume_receipt_matches_checkout_root_not_filing_directory() {
2345        use crate::task_decision::Status;
2346        let tmp = tempfile::tempdir().unwrap();
2347        let home = tmp.path();
2348        let repo = home.join("checkout");
2349        let subdir = repo.join("src");
2350        let foreign = home.join("foreign");
2351        std::fs::create_dir_all(&subdir).unwrap();
2352        std::fs::create_dir(&foreign).unwrap();
2353        for checkout in [&repo, &foreign] {
2354            crate::git::git(checkout, &["init", "-q"]).await.unwrap();
2355        }
2356        let queue = Queue::at(home.join("queue"));
2357        let mut task = Task::new("work".into(), "work".into(), subdir, Source::Human);
2358        let mut state = crate::run::RunState::new(
2359            repo,
2360            "main".into(),
2361            "base".into(),
2362            "work".into(),
2363            crate::config::Config::default(),
2364        );
2365        state.reserve_under(home).unwrap();
2366        task.runs.push(state.id.clone());
2367        queue.put(&mut task).unwrap();
2368        let outbox = crate::task_inquiry::Outbox::at(home);
2369        let inquiry = outbox
2370            .file(
2371                &task,
2372                Some(state.id.clone()),
2373                "resume".into(),
2374                "Resume?",
2375                "",
2376            )
2377            .unwrap();
2378        let request = serde_json::to_string(&Operation::Resume {
2379            run: state.id.clone(),
2380        })
2381        .unwrap();
2382        outbox
2383            .update_decision(&inquiry.id, |d| {
2384                d.accept(&request)?;
2385                d.start()
2386            })
2387            .unwrap();
2388        task.dispatched_resumes
2389            .insert(inquiry.id.clone(), state.id.clone());
2390        queue.put(&mut task).unwrap();
2391        reconcile_decisions(&queue, home).unwrap();
2392        assert_eq!(
2393            outbox.get(&inquiry.id).unwrap().decision.unwrap().status,
2394            Status::InProgress
2395        );
2396
2397        state.carry_dispatched_resumes(&task);
2398        state.begin_pass();
2399        state.save_under(home).unwrap();
2400        let mut reassigned = task.clone();
2401        reassigned.repo = foreign;
2402        assert!(resume_started(home, &reassigned, &inquiry.id, &state.id).is_err());
2403        reconcile_decisions(&queue, home).unwrap();
2404        assert_eq!(
2405            outbox.get(&inquiry.id).unwrap().decision.unwrap().status,
2406            Status::Resolved
2407        );
2408    }
2409
2410    #[test]
2411    fn only_the_chat_seat_of_an_open_talk_is_authorized() {
2412        let tmp = tempfile::tempdir().unwrap();
2413        let talks = Talks::at(tmp.path().join("talks"));
2414        let t = talk(&talks, "talk-a");
2415        assert!(authorize(&talks, &t.id, "chat").is_ok());
2416        assert!(authorize(&talks, &t.id, "deputy").is_err());
2417        assert!(authorize(&talks, &t.id, "").is_err());
2418        assert!(authorize(&talks, "", "chat").is_err());
2419        assert!(
2420            authorize(&talks, "talk-", "chat").is_err(),
2421            "prefix is not an id"
2422        );
2423    }
2424
2425    #[test]
2426    fn tasks_of_any_origin_are_controlled_on_request() {
2427        let tmp = tempfile::tempdir().unwrap();
2428        let queue = Queue::at(tmp.path().join("queue"));
2429        let theirs = filed(&queue, "talk-b", "theirs");
2430        let mut hand = Task::new("h".into(), "h".into(), ".".into(), Source::Human);
2431        hand.hold_manual(Some("operator".into()));
2432        queue.put(&mut hand).unwrap();
2433        // Another chat's task and an operator-held human task are the owner's
2434        // work too: the request goes through without any ownership scope.
2435        assert_eq!(
2436            hold(&queue, &theirs.id, "wait").unwrap().status,
2437            TaskStatus::Held
2438        );
2439        assert_eq!(
2440            release(&queue, &hand.id).unwrap().status,
2441            TaskStatus::Queued
2442        );
2443        let again = retry(&queue, &theirs.id, None, "new").unwrap();
2444        assert_eq!(again.instruction, "new");
2445        assert_eq!(again.status, TaskStatus::Queued);
2446    }
2447
2448    #[test]
2449    fn hold_then_release_keeps_history_and_restarts_attempts() {
2450        let tmp = tempfile::tempdir().unwrap();
2451        let queue = Queue::at(tmp.path().join("queue"));
2452        let mut t = filed(&queue, "talk-a", "work");
2453        t.attempts = 3;
2454        t.runs.push("20260101-000000-aaaa".into());
2455        queue.put(&mut t).unwrap();
2456        let held = hold(&queue, &t.id, "owner asked").unwrap();
2457        assert_eq!(held.status, TaskStatus::Held);
2458        assert_eq!(held.hold_reason.as_deref(), Some("owner asked"));
2459        let back = release(&queue, &t.id).unwrap();
2460        assert_eq!(back.status, TaskStatus::Queued);
2461        assert_eq!(back.attempts, 0);
2462        assert_eq!(back.runs, t.runs);
2463        assert!(back.resumption.is_some());
2464    }
2465
2466    #[test]
2467    fn hold_and_release_refuse_done_and_running_without_saving() {
2468        let tmp = tempfile::tempdir().unwrap();
2469        let queue = Queue::at(tmp.path().join("queue"));
2470        for status in [TaskStatus::Done, TaskStatus::Running] {
2471            let mut t = filed(&queue, "talk-a", "work");
2472            t.start("20260101-000000-aaaa".into());
2473            if status == TaskStatus::Done {
2474                t.succeed(crate::queue::CompletionContext::new(
2475                    crate::queue::CompletionActor::Cli,
2476                    None,
2477                    tmp.path(),
2478                    &t,
2479                ));
2480            }
2481            queue.put(&mut t).unwrap();
2482            let before = std::fs::read(queue.path_of(&t.id)).unwrap();
2483            for operation in ["hold", "release"] {
2484                let error = if operation == "hold" {
2485                    hold(&queue, &t.id, "owner asked")
2486                } else {
2487                    release(&queue, &t.id)
2488                }
2489                .unwrap_err()
2490                .to_string();
2491                assert!(error.contains(operation), "{error}");
2492                assert!(error.contains(&t.id), "{error}");
2493                assert!(error.contains(status.as_str()), "{error}");
2494                let guidance = if status == TaskStatus::Done {
2495                    "create a new task"
2496                } else {
2497                    "use resume or abandon"
2498                };
2499                assert!(error.contains(guidance), "{error}");
2500                assert_eq!(std::fs::read(queue.path_of(&t.id)).unwrap(), before);
2501            }
2502        }
2503    }
2504
2505    #[test]
2506    fn hold_and_release_allow_unfinished_inactive_tasks() {
2507        let tmp = tempfile::tempdir().unwrap();
2508        let queue = Queue::at(tmp.path().join("queue"));
2509        for status in [
2510            TaskStatus::Queued,
2511            TaskStatus::Held,
2512            TaskStatus::Failed,
2513            TaskStatus::Blocked,
2514            TaskStatus::Parked,
2515        ] {
2516            for operation in ["hold", "release"] {
2517                let mut t = filed(&queue, "talk-a", "work");
2518                t.status = status;
2519                t.hold_reason = Some("old reason".into());
2520                t.attempts = 3;
2521                t.runs.push("20260101-000000-aaaa".into());
2522                queue.put(&mut t).unwrap();
2523                let changed = if operation == "hold" {
2524                    let held = hold(&queue, &t.id, " new reason ").unwrap();
2525                    assert_eq!(held.status, TaskStatus::Held);
2526                    assert_eq!(held.hold_reason.as_deref(), Some("new reason"));
2527                    assert_eq!(held.attempts, t.attempts);
2528                    held
2529                } else {
2530                    let released = release(&queue, &t.id).unwrap();
2531                    assert_eq!(released.status, TaskStatus::Queued);
2532                    assert_eq!(released.attempts, 0);
2533                    assert_eq!(released.resumption.as_ref().unwrap().source, "chat");
2534                    released
2535                };
2536                assert_eq!(changed.runs, t.runs);
2537                assert_eq!(queue.get(&t.id).unwrap().status, changed.status);
2538            }
2539        }
2540    }
2541
2542    #[test]
2543    fn retry_edits_and_requeues_in_one_save() {
2544        let tmp = tempfile::tempdir().unwrap();
2545        let queue = Queue::at(tmp.path().join("queue"));
2546        let mut t = filed(&queue, "talk-a", "old text");
2547        t.runs.push("20260101-000000-aaaa".into());
2548        t.attempts = 2;
2549        t.hold_manual(Some("stopped".into()));
2550        queue.put(&mut t).unwrap();
2551        let again = retry(&queue, &t.id, None, "new text").unwrap();
2552        assert_eq!(again.instruction, "new text");
2553        assert_eq!(again.status, TaskStatus::Queued);
2554        assert_eq!(again.attempts, 0);
2555        assert_eq!(again.runs, t.runs, "run history is kept");
2556        assert_eq!(again.resumption.as_ref().unwrap().source, "chat");
2557        assert_eq!(again.resumption.as_ref().unwrap().instruction, "new text");
2558        // A running task cannot be edited: nothing is changed.
2559        let mut running = filed(&queue, "talk-a", "busy");
2560        running.start("20260101-000000-bbbb".into());
2561        queue.put(&mut running).unwrap();
2562        assert!(retry(&queue, &running.id, None, "x").is_err());
2563        assert_eq!(queue.get(&running.id).unwrap().instruction, "busy");
2564        assert!(retry(&queue, &t.id, None, "  ").is_err());
2565    }
2566
2567    #[test]
2568    fn execution_commands_need_the_full_id_of_a_recorded_run() {
2569        let tmp = tempfile::tempdir().unwrap();
2570        let queue = Queue::at(tmp.path().join("queue"));
2571        let mut t = filed(&queue, "talk-b", "work");
2572        t.runs.push("20260101-000000-aaaa".into());
2573        queue.put(&mut t).unwrap();
2574        assert_eq!(
2575            run_task(&queue, "20260101-000000-aaaa").unwrap().id,
2576            t.id,
2577            "any chat may address another chat's run"
2578        );
2579        assert!(run_task(&queue, "aaaa").is_err());
2580        assert!(run_task(&queue, "20260101-000000-bbbb").is_err());
2581        assert!(resume(&queue, tmp.path(), "aaaa").is_err());
2582    }
2583
2584    #[test]
2585    fn abandon_needs_no_phrase_but_refuses_unrecorded_and_unknown_runs() {
2586        let tmp = tempfile::tempdir().unwrap();
2587        let queue = Queue::at(tmp.path().join("queue"));
2588        let mut t = filed(&queue, "talk-b", "work");
2589        t.runs.push("20260101-000000-aaaa".into());
2590        queue.put(&mut t).unwrap();
2591        // A run no task recorded is refused before liveness is judged.
2592        assert!(abandon(&queue, tmp.path(), "20260101-000000-bbbb").is_err());
2593        // A recorded run whose driver is not proven dead (here: no state to
2594        // judge at all) is never abandoned.
2595        assert!(abandon(&queue, tmp.path(), "20260101-000000-aaaa").is_err());
2596    }
2597}
2598
2599#[cfg(test)]
2600mod goal_admission_tests {
2601    use super::*;
2602
2603    #[tokio::test]
2604    async fn goal_effects_require_current_generation_scope_and_no_new_owner_input() {
2605        let tmp = tempfile::tempdir().unwrap();
2606        let talks = Talks::at(tmp.path().join("talks"));
2607        let queue = Queue::at(tmp.path().join("queue"));
2608        let target = tmp.path().join("target");
2609        std::fs::create_dir(&target).unwrap();
2610        crate::git::git(&target, &["init", "-q"]).await.unwrap();
2611        let mut talk = crate::talk::seeded_for_test("goal-effect", tmp.path().into());
2612        talk.turns.push(
2613            serde_json::from_value(serde_json::json!({
2614                "sender": "operator", "who": "operator", "body": "Follow this task through",
2615                "at": jiff::Timestamp::now()
2616            }))
2617            .unwrap(),
2618        );
2619        talks.put(&mut talk).unwrap();
2620        let mut task = Task::new(
2621            "work".into(),
2622            "work".into(),
2623            target.clone(),
2624            crate::queue::Source::Agent {
2625                run: talk.id.clone(),
2626                node: crate::queue::CHAT_NODE.into(),
2627            },
2628        );
2629        queue.put(&mut task).unwrap();
2630        let mut unrelated = Task::new(
2631            "other".into(),
2632            "other".into(),
2633            target.clone(),
2634            crate::queue::Source::Agent {
2635                run: talk.id.clone(),
2636                node: crate::queue::CHAT_NODE.into(),
2637            },
2638        );
2639        queue.put(&mut unrelated).unwrap();
2640        crate::chat_goal::apply(
2641            &queue,
2642            tmp.path(),
2643            &talks,
2644            &talk.id,
2645            &crate::chat_goal::Source::Input { turn: 0 },
2646            crate::chat_goal::Command::Establish {
2647                id: "g".into(),
2648                purpose: "Deliver this task".into(),
2649                scope: "This task only".into(),
2650                condition: "Verified delivery".into(),
2651                completion: crate::chat_goal::Completion::TasksDone,
2652                repo: Some(target),
2653                tasks: vec![task.id.clone()],
2654                runs: vec![],
2655                watches: vec![],
2656            },
2657        )
2658        .await
2659        .unwrap();
2660        talks
2661            .mutate(&talk.id, |talk| {
2662                let boundary = talk.turns.len();
2663                let goal = &mut talk.goals[0];
2664                goal.wake = 1;
2665                goal.started = Some(1);
2666                goal.launch_turns = Some(boundary);
2667                Ok(())
2668            })
2669            .unwrap();
2670        let source = crate::chat_goal::Source::Goal {
2671            id: "g".into(),
2672            generation: 1,
2673        };
2674        assert!(
2675            execute_authenticated(
2676                &queue,
2677                tmp.path(),
2678                &talks,
2679                &talk.id,
2680                source.clone(),
2681                Operation::Priority {
2682                    task: unrelated.id.clone(),
2683                    priority: 8
2684                }
2685            )
2686            .await
2687            .is_err()
2688        );
2689        execute_authenticated(
2690            &queue,
2691            tmp.path(),
2692            &talks,
2693            &talk.id,
2694            source.clone(),
2695            Operation::Priority {
2696                task: task.id.clone(),
2697                priority: 3,
2698            },
2699        )
2700        .await
2701        .unwrap();
2702        let hold = Operation::Hold {
2703            task: task.id.clone(),
2704            reason: "pause".into(),
2705        };
2706        crate::chat_goal::with_source(source.clone(), async {
2707            // Reassignment publishes under this same claim, between the first
2708            // admission and the mutation's claim acquisition.
2709            admit_goal_operation(&queue, tmp.path(), &talks, &talk.id, &hold).unwrap();
2710            let original = task.repo.clone();
2711            {
2712                let claim = queue.claim(&task.id).unwrap();
2713                task = queue.get(&task.id).unwrap();
2714                task.repo = talk.repo.clone();
2715                queue.put(&mut task).unwrap();
2716                drop(claim);
2717            }
2718            let result = claimed_for_chat(&queue, &task.id, &talks, &talk.id)
2719                .and_then(|claimed| hold_claimed(&queue, claimed, "pause"));
2720            assert!(result.unwrap_err().to_string().contains(&task.id));
2721            assert_eq!(queue.get(&task.id).unwrap().status, TaskStatus::Queued);
2722            task.repo = original;
2723            queue.put(&mut task).unwrap();
2724        })
2725        .await;
2726        let error = execute_authenticated(
2727            &queue,
2728            tmp.path(),
2729            &talks,
2730            &talk.id,
2731            source.clone(),
2732            Operation::Done {
2733                task: task.id.clone(),
2734                reason: Some("discard unfinished work".into()),
2735                discard: true,
2736            },
2737        )
2738        .await
2739        .unwrap_err();
2740        assert!(
2741            error.to_string().contains("explicit owner turn"),
2742            "{error:#}"
2743        );
2744        assert_eq!(queue.get(&task.id).unwrap().status, TaskStatus::Queued);
2745        assert!(queue.get(&task.id).unwrap().completion_history.is_empty());
2746        assert!(
2747            execute_authenticated(
2748                &queue,
2749                tmp.path(),
2750                &talks,
2751                &talk.id,
2752                source.clone(),
2753                Operation::Done {
2754                    task: unrelated.id.clone(),
2755                    reason: None,
2756                    discard: false,
2757                },
2758            )
2759            .await
2760            .is_err()
2761        );
2762        execute_authenticated(
2763            &queue,
2764            tmp.path(),
2765            &talks,
2766            &talk.id,
2767            source.clone(),
2768            Operation::Done {
2769                task: task.id.clone(),
2770                reason: Some("goal work finished".into()),
2771                discard: false,
2772            },
2773        )
2774        .await
2775        .unwrap();
2776        let error = execute_authenticated(
2777            &queue,
2778            tmp.path(),
2779            &talks,
2780            &talk.id,
2781            source.clone(),
2782            Operation::Reopen {
2783                task: task.id.clone(),
2784                reason: "recover unfinished work".into(),
2785            },
2786        )
2787        .await
2788        .unwrap_err();
2789        assert!(
2790            error.to_string().contains("explicit owner turn"),
2791            "{error:#}"
2792        );
2793        assert_eq!(queue.get(&task.id).unwrap().status, TaskStatus::Done);
2794        execute_authenticated(
2795            &queue,
2796            tmp.path(),
2797            &talks,
2798            &talk.id,
2799            crate::chat_goal::Source::Input { turn: 0 },
2800            Operation::Reopen {
2801                task: task.id.clone(),
2802                reason: "recover unfinished work".into(),
2803            },
2804        )
2805        .await
2806        .unwrap();
2807        assert_eq!(queue.get(&task.id).unwrap().status, TaskStatus::Held);
2808        talks
2809            .mutate(&talk.id, |talk| {
2810                talk.turns.push(serde_json::from_value(serde_json::json!({
2811                    "sender": "operator", "who": "operator", "body": "Stop",
2812                    "at": jiff::Timestamp::now()
2813                }))?);
2814                Ok(())
2815            })
2816            .unwrap();
2817        assert!(
2818            execute_authenticated(
2819                &queue,
2820                tmp.path(),
2821                &talks,
2822                &talk.id,
2823                source.clone(),
2824                Operation::Priority {
2825                    task: task.id.clone(),
2826                    priority: 9
2827                }
2828            )
2829            .await
2830            .is_err()
2831        );
2832        talks
2833            .mutate(&talk.id, |talk| {
2834                talk.turns.pop();
2835                talk.goals[0].state = crate::chat_goal::State::Stopped;
2836                talk.goals[0].wake = 2;
2837                talk.goals[0].started = None;
2838                Ok(())
2839            })
2840            .unwrap();
2841        assert!(
2842            execute_authenticated(
2843                &queue,
2844                tmp.path(),
2845                &talks,
2846                &talk.id,
2847                source,
2848                Operation::Priority {
2849                    task: task.id.clone(),
2850                    priority: 9
2851                }
2852            )
2853            .await
2854            .is_err()
2855        );
2856        assert_eq!(queue.get(&task.id).unwrap().priority, 3);
2857    }
2858}