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