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 ([`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    /// File a new immediate task through the authenticated bridge on an
114    /// explicit owner chat turn, bound by a durable per-request receipt.
115    AddImmediate {
116        /// Durable idempotency key; reuse only for identical arguments in this turn.
117        request: String,
118        /// Validated filing inputs; only this path enables `Task::immediate`.
119        filing: Box<Filing>,
120        /// Skip launcher duplicate screening only when explicitly forced.
121        #[serde(default)]
122        force: bool,
123    },
124    /// Enable or clear `immediate` on one existing queued or held task through
125    /// the authenticated bridge on an explicit owner chat turn.
126    SetImmediate {
127        /// Durable idempotency key; reuse only for identical arguments in this turn.
128        request: String,
129        /// Task id or unambiguous prefix/suffix.
130        task: String,
131        /// Disable instead of enable.
132        #[serde(default)]
133        clear: bool,
134    },
135    /// Mark a task complete using the terminal's transition.
136    Done {
137        /// Task id or unambiguous prefix.
138        task: String,
139        /// Optional explanation retained with the completion event.
140        #[serde(default)]
141        reason: Option<String>,
142        /// Nonblank findings required to complete an investigation.
143        #[serde(default, skip_serializing_if = "Option::is_none")]
144        result: Option<String>,
145        /// Close unfinished work without deleting its runs or branches.
146        #[serde(default)]
147        discard: bool,
148    },
149    /// Restore mistakenly closed unfinished work to an operator hold.
150    Reopen {
151        /// Task id or unambiguous prefix.
152        task: String,
153        /// Required explanation for recovery.
154        reason: String,
155    },
156    /// Change a task's queue priority.
157    Priority {
158        /// Task id or unambiguous prefix.
159        task: String,
160        /// New priority.
161        priority: i32,
162    },
163    /// Merge a PR the owner asked for, once per request.
164    MergePr {
165        /// Exact owner/repository name.
166        repo: String,
167        /// Pull request number.
168        number: u64,
169        /// Full head SHA the chat just read from the forge.
170        head: String,
171        /// Idempotency key minted by the chat agent.
172        request: String,
173    },
174    /// Authorize one bounded base-recovery interval and queue the existing run.
175    RecoverBase {
176        /// Exact retained run ID.
177        run: String,
178        /// Retained HEAD inspected for the owner's request (full SHA or 7+ hex digits).
179        head: String,
180        /// Durable idempotency key; reuse only for identical arguments.
181        request: String,
182        /// Inspected preparation-stop evidence; absent for ordinary exhaustion.
183        #[serde(default, skip_serializing_if = "Option::is_none")]
184        evidence_digest: Option<String>,
185    },
186    /// Authorize one bounded landing base-sync recovery attempt and queue the existing run.
187    RecoverLandSync {
188        /// Exact retained run ID.
189        run: String,
190        /// Full 40-character retained worktree HEAD SHA; the published PR head is bound separately.
191        head: String,
192        /// Durable idempotency key; reuse only for identical arguments.
193        request: String,
194    },
195    /// Adopt the task's revised instruction into its retained run and open PR,
196    /// then queue one bounded repair and fresh review of that same PR.
197    AdoptInstruction {
198        /// Exact retained run ID.
199        run: String,
200        /// Full 40-character HEAD SHA verified on the retained worktree, public branch and open PR.
201        head: String,
202        /// Durable idempotency key; reuse only for identical arguments.
203        request: String,
204    },
205    /// 既存 run の再開を queue に登録する。
206    Resume {
207        /// 完全な run ID。
208        run: String,
209    },
210    /// Queue a Git-only pass over the retained winner.
211    SyncBaseOnly {
212        /// Exact retained run ID.
213        run: String,
214    },
215    /// task を手動保留する。
216    Hold {
217        /// task ID または一意な接頭辞。
218        task: String,
219        /// 保留理由。
220        reason: String,
221    },
222    /// task を保留から解放する。
223    Release {
224        /// task ID または一意な接頭辞。
225        task: String,
226    },
227    /// 指示を変更して再試行する。
228    Retry {
229        /// task ID または一意な接頭辞。
230        task: String,
231        /// 新しいタイトル、省略時は指示から生成する。
232        title: Option<String>,
233        /// 新しい指示全文。
234        instruction: String,
235    },
236    /// PR の失敗した workflow を再実行する。
237    RerunChecks {
238        /// 完全な run ID。
239        run: String,
240        /// 冪等性を保証するリクエスト ID。
241        request: String,
242        /// 観測した PR head。
243        head: String,
244        /// 再実行対象の workflow run ID。
245        workflows: Vec<String>,
246    },
247    /// タスクチャットで所有者の判断を記録する(マージを含む)。
248    Decide {
249        /// 質問 ID(完全または一意な接頭辞)。
250        question: String,
251        /// 記録された選択肢のラベル。
252        choice: String,
253        /// 「use my text」で公開する置換タイトルそのもの。
254        #[serde(default)]
255        title: Option<String>,
256    },
257    /// `magi answer --reply`: the owner's answer to a question, as an ordinary
258    /// answer ([`crate::ask::record_answer`]).
259    Answer {
260        /// Full question id, resolved by the CLI.
261        question: String,
262        /// An offered choice (label or alias), or the free-text answer.
263        reply: String,
264        /// The literal replacement title for the posting gate's `use my text`.
265        #[serde(default)]
266        title: Option<String>,
267    },
268    /// `magi answer --reply-other`: the owner's decision outside the offered
269    /// choices, saved as a note that ends the consultation
270    /// ([`crate::consult::reply_other`]).
271    ReplyOther {
272        /// Full question id, resolved by the CLI.
273        question: String,
274        /// The owner's outcome.
275        text: String,
276    },
277    /// 保存された計画を作成、または適用する。
278    ReconcileRetention {
279        /// 対象タスク ID。
280        task: String,
281        /// 保護する実装の完全な run ID。
282        authority: String,
283        /// 適用する保存済み計画 ID(省略時は計画のみ)。
284        apply: Option<String>,
285    },
286    /// 生存が否定された run を破棄する。
287    Abandon {
288        /// 完全な run ID。
289        run: String,
290    },
291}
292
293/// Inputs prepared by `magi task add` before saving a fresh queue record.
294#[derive(Debug, serde::Serialize, serde::Deserialize)]
295#[serde(deny_unknown_fields)]
296pub struct Filing {
297    /// Task title.
298    pub title: String,
299    /// Complete task instruction.
300    pub instruction: String,
301    /// Validated absolute repository path.
302    pub repo: std::path::PathBuf,
303    /// Explicitly file a result-only investigation (exempt from landing audit).
304    #[serde(default)]
305    pub investigation: bool,
306    /// Filing provenance prepared by the CLI.
307    pub source: crate::queue::Source,
308    /// Imported issue, if any.
309    #[serde(default, skip_serializing_if = "Option::is_none")]
310    pub issue: Option<crate::queue::IssueRef>,
311    /// Resolved implementation imports.
312    pub sources: crate::refs::Sources,
313    /// Optional initial hold reason.
314    pub hold: Option<String>,
315    /// Queue priority.
316    pub priority: i32,
317    /// Use one implementer.
318    pub solo: bool,
319    /// Prioritize execution.
320    pub urgent: bool,
321    /// Optional implementer count.
322    pub implementers: Option<usize>,
323    /// Optional Cargo build output policy.
324    #[serde(default, skip_serializing_if = "Option::is_none")]
325    pub build_cache: Option<crate::config::BuildCache>,
326    /// Absolute attachment paths to copy into the queue.
327    pub attach: Vec<std::path::PathBuf>,
328}
329
330/// Whether this process inherited a launcher control channel.
331/// Provenance-only CLI calls without a channel retain their ordinary local route.
332pub fn has_channel() -> bool {
333    #[cfg(any(unix, windows))]
334    {
335        #[cfg(unix)]
336        let socket = std::env::var_os("MAGI_CHAT_CONTROL_SOCKET").is_some();
337        #[cfg(windows)]
338        let socket = false;
339        std::env::var_os(bridge::CHANNEL_ENV).is_some() || socket
340    }
341    #[cfg(not(any(unix, windows)))]
342    {
343        false
344    }
345}
346
347/// The CLI sends only a typed operation when it inherited a turn capability.
348/// Outside a launched turn the existing, authorized local route remains usable.
349pub async fn dispatch(
350    queue: &Queue,
351    home: &Path,
352    talks: &Talks,
353    talk: &str,
354    operation: Operation,
355) -> Result<String> {
356    if matches!(
357        &operation,
358        Operation::Reassign { .. }
359            | Operation::RecoverBase { .. }
360            | Operation::RecoverLandSync { .. }
361            | Operation::AdoptInstruction { .. }
362            | Operation::SyncBaseOnly { .. }
363            | Operation::Goal { .. }
364            | Operation::Standing { .. }
365            | Operation::AddImmediate { .. }
366            | Operation::SetImmediate { .. }
367    ) {
368        #[cfg(unix)]
369        {
370            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");
371        }
372        #[cfg(windows)]
373        {
374            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");
375        }
376        #[cfg(not(any(unix, windows)))]
377        {
378            bail!("authenticated chat control channel is unavailable on this platform");
379        }
380    }
381    if standing_turn() {
382        #[cfg(unix)]
383        return bridge::request(&operation)
384            .context("automatic recovery requires the authenticated chat control channel");
385        #[cfg(windows)]
386        return bridge::request(&operation)
387            .await
388            .context("automatic recovery requires the authenticated chat control channel");
389        #[cfg(not(any(unix, windows)))]
390        bail!("authenticated chat control channel is unavailable on this platform");
391    }
392    #[cfg(unix)]
393    if std::env::var_os(bridge::CHANNEL_ENV).is_some()
394        || std::env::var_os("MAGI_CHAT_CONTROL_SOCKET").is_some()
395    {
396        // The launcher sets this flag for writable seats, including effective
397        // unsandboxed chat turns. execute() still enforces talk authorization.
398        match bridge::request(&operation) {
399            Err(error)
400                if error.is::<bridge::Unavailable>()
401                    && std::env::var("MAGI_ALLOW_WRITE").as_deref() == Ok("1") => {}
402            result => return result,
403        }
404    }
405    #[cfg(windows)]
406    if std::env::var_os(bridge::CHANNEL_ENV).is_some() {
407        return bridge::request(&operation).await;
408    }
409    Box::pin(execute(queue, home, talks, talk, operation)).await
410}
411
412/// The transport supplies a launcher authority snapshot, never the CLI frame.
413pub(crate) async fn execute_authenticated(
414    queue: &Queue,
415    home: &Path,
416    talks: &Talks,
417    talk: &str,
418    source: crate::chat_goal::Source,
419    operation: Operation,
420) -> Result<String> {
421    if let crate::chat_goal::Source::Standing(scope) = source {
422        return Box::pin(standing::execute(
423            queue, home, talks, talk, &scope, operation,
424        ))
425        .await;
426    }
427    crate::chat_goal::with_source(
428        source,
429        Box::pin(execute(queue, home, talks, talk, operation)),
430    )
431    .await
432}
433
434/// Whether the launcher restricted this CLI to read-only inspection and typed controls.
435/// The environment marker can only restrict the CLI; it cannot grant bridge authority.
436pub fn standing_turn() -> bool {
437    std::env::var_os(standing::ENV).is_some()
438}
439
440async fn execute(
441    queue: &Queue,
442    home: &Path,
443    talks: &Talks,
444    talk: &str,
445    operation: Operation,
446) -> Result<String> {
447    authorize(talks, talk, crate::queue::CHAT_NODE)?;
448    crate::chat_goal::fence(talks, talk, &crate::chat_goal::current_source())?;
449    admit_goal_operation(queue, home, talks, talk, &operation)?;
450    Ok(match operation {
451        Operation::Standing { .. } => bail!(
452            "standing authorization is disabled or this turn is not an eligible automatic report"
453        ),
454        Operation::Goal { command } => {
455            crate::chat_goal::apply(
456                queue,
457                home,
458                talks,
459                talk,
460                &crate::chat_goal::current_source(),
461                command,
462            )
463            .await?
464        }
465        Operation::Reassign { task, repo } => {
466            let cwd = &talks.get(talk)?.repo;
467            let task = crate::task_reassign::reassign(
468                queue,
469                home,
470                cwd,
471                &task,
472                &repo,
473                &format!("chat:{talk}"),
474            )
475            .await?;
476            let mut message = describe(&task, "reassigned");
477            for note in crate::task_reassign::advisory_notes(&task, home) {
478                message.push_str(&format!("\n  {note}"));
479            }
480            message
481        }
482        Operation::ReconcileDecision { inquiry } => {
483            reconcile_task_decision(queue, home, talk, &inquiry)?;
484            format!("decision {inquiry} reconciled from the task's durable state")
485        }
486        Operation::ForDecision { inquiry, command } => {
487            Box::pin(execute_decision(
488                queue, home, talks, talk, &inquiry, *command,
489            ))
490            .await?
491        }
492        Operation::SettleDecision {
493            inquiry,
494            reason,
495            replacement,
496        } => {
497            let outbox = crate::task_inquiry::Outbox::at(home);
498            let record = outbox.get(&inquiry)?;
499            let questions = crate::ask::Questions::at(home.join("questions"));
500            let source = questions.read_history(&inquiry).ok();
501            // A quarantined saved reply is not a live unanswered decision.
502            // The owner can explicitly confirm that its unknown effect needs
503            // no further work without accepting or replaying the old reply.
504            let unaccepted_history = record
505                .decision
506                .as_ref()
507                .is_some_and(|d| d.request.is_none())
508                && source.as_ref().is_some_and(|source| {
509                    source.status == crate::ask::QuestionStatus::Answered
510                        && crate::task_chat::saved_reply_requires_confirmation(home, source)
511                });
512            // Task-backed legacy consumers run under the task claim. Hold it
513            // through settlement; ownerless release consumers use the inquiry
514            // execution fence inside Outbox::settle instead.
515            let _task_claim = if !record.task.is_empty()
516                && (unaccepted_history
517                    || record
518                        .decision
519                        .as_ref()
520                        .is_some_and(|d| d.request.is_some()))
521            {
522                Some(
523                    queue
524                        .claim(&record.task)
525                        .context("decision task is executing")?,
526                )
527            } else {
528                None
529            };
530            if record
531                .decision
532                .as_ref()
533                .is_some_and(|d| d.request.is_none())
534                && let Some(source) = source
535                && !(record.task.is_empty() && record.delivered_to.is_none())
536            {
537                ensure!(
538                    unaccepted_history || !crate::task_chat::awaits_decision(&source),
539                    "a legacy effect still awaits consumer reconciliation; settlement executes no action"
540                );
541            }
542            outbox.settle(&inquiry, talk, &reason, replacement.as_deref())?;
543            format!("settled decision {inquiry}: {reason}")
544        }
545        Operation::Add { filing } => {
546            ensure!(
547                matches!(&filing.source, crate::queue::Source::Agent { run, node }
548                    if run == talk && node == crate::queue::CHAT_NODE),
549                "filing must retain this conversation's provenance"
550            );
551            serde_json::to_string(&file_task(queue, *filing)?)?
552        }
553        Operation::AddImmediate {
554            request,
555            filing,
556            force,
557        } => serde_json::to_string(
558            &Box::pin(crate::immediate_filing_control::file(
559                queue, home, talks, talk, &request, *filing, force,
560            ))
561            .await?,
562        )?,
563        Operation::SetImmediate {
564            request,
565            task,
566            clear,
567        } => serde_json::to_string(&crate::immediate_filing_control::set(
568            queue, home, talks, talk, &request, &task, clear,
569        )?)?,
570        Operation::Done {
571            task,
572            reason,
573            result,
574            discard,
575        } => {
576            let claimed = claimed_for_chat(queue, &task, talks, talk)?;
577            let task = Box::pin(crate::task_completion::close_claimed(
578                queue,
579                home,
580                claimed,
581                crate::queue::CompletionActor::Chat(talk.to_owned()),
582                reason,
583                result,
584                discard,
585            ))
586            .await?;
587            crate::task_completion::describe(&task)
588        }
589        Operation::Reopen { task, reason } => {
590            let (_claim, mut t) = claimed_for_chat(queue, &task, talks, talk)?;
591            let expected = t.clone();
592            let (_guards, context) = Box::pin(crate::task_completion::admit_reopen(
593                &t,
594                home,
595                crate::queue::CompletionActor::Chat(talk.to_owned()),
596                &reason,
597            ))
598            .await?;
599            t.reopen(context)?;
600            queue.commit_completion(&mut t, &expected)?;
601            describe(&t, "reopened on hold")
602        }
603        Operation::Priority { task, priority } => {
604            let t = priority_claimed(
605                queue,
606                claimed_for_chat(queue, &task, talks, talk)?,
607                priority,
608            )?;
609            format!("{} priority now {} - {}", t.short(), t.priority, t.title)
610        }
611        Operation::MergePr {
612            repo,
613            number,
614            head,
615            request,
616        } => crate::chat_merge::merge(
617            home,
618            talks,
619            talk,
620            crate::chat_merge::Request {
621                repo,
622                number,
623                head,
624                request,
625            },
626        )
627        .await
628        .map_err(|error| {
629            if error.is::<crate::chat_merge::BeforeMergeWrite>() {
630                anyhow::Error::new(BeforeEffect(error))
631            } else {
632                error
633            }
634        })?,
635        Operation::ReconcileRepairGrant { request } => serde_json::to_string(
636            &Box::pin(crate::repair_budget::reconcile::apply(queue, home, request)).await?,
637        )?,
638        Operation::GrantRepair { request } => {
639            // Keep run-state admission out of the shared control dispatcher
640            // future, which is also embedded in ordinary CLI task operations.
641            let owner_requested_at = match crate::chat_goal::current_source() {
642                crate::chat_goal::Source::Input { turn } => talks
643                    .get(talk)?
644                    .turns
645                    .get(turn)
646                    .and_then(|turn| crate::talk::owner_send_boundary(&turn.messages)),
647                _ => None,
648            };
649            let receipt = Box::pin(crate::repair_budget::grant_with_claim(
650                queue,
651                home,
652                request,
653                None,
654                owner_requested_at,
655            ))
656            .await
657            .map_err(|error| {
658                if error.is::<crate::repair_budget::PublicationUnknown>() {
659                    error
660                } else {
661                    BeforeEffect(error).into()
662                }
663            })?;
664            serde_json::to_string(&receipt)?
665        }
666        Operation::RecoverBase {
667            run,
668            head,
669            request,
670            evidence_digest,
671        } => {
672            if evidence_digest.is_some() {
673                ensure!(
674                    matches!(
675                        crate::chat_goal::current_source(),
676                        crate::chat_goal::Source::Input { .. }
677                    ),
678                    "preparation recovery requires explicit owner input"
679                );
680            }
681            let result = Box::pin(crate::base_recovery_control::recover(
682                queue,
683                home,
684                crate::base_recovery_control::Request {
685                    run,
686                    head,
687                    request,
688                    actor: talk.to_owned(),
689                    decision: None,
690                    expected_stop: None,
691                    evidence_digest,
692                },
693            ))
694            .await?;
695            if result.repeated {
696                format!(
697                    "This base-recovery request was already applied to task {}; inspect its current status before continuing",
698                    result.task.id
699                )
700            } else {
701                format!(
702                    "{}; bounded base recovery authorized; the daemon resumes the exact run under its execution lease",
703                    describe(&result.task, "recovery queued for")
704                )
705            }
706        }
707        Operation::RecoverLandSync { run, head, request } => {
708            ensure!(
709                matches!(
710                    crate::chat_goal::current_source(),
711                    crate::chat_goal::Source::Input { .. }
712                ),
713                "recover-land-sync requires explicit owner input"
714            );
715            let result = Box::pin(crate::land_sync_recovery_control::recover(
716                queue,
717                home,
718                crate::land_sync_recovery_control::Request {
719                    run,
720                    head,
721                    request,
722                    actor: talk.to_owned(),
723                },
724            ))
725            .await
726            .map_err(|error| {
727                if error.is::<crate::land_sync_recovery_control::BeforeWrite>() {
728                    anyhow::Error::new(BeforeEffect(error))
729                } else {
730                    error
731                }
732            })?;
733            if result.repeated {
734                format!(
735                    "This landing base-sync recovery request was already applied to task {}; inspect its current status before continuing",
736                    result.task.id
737                )
738            } else {
739                format!(
740                    "{}; bounded landing base-sync recovery authorized (1 attempt); the daemon resumes the exact run under its execution lease",
741                    describe(&result.task, "landing sync recovery queued for")
742                )
743            }
744        }
745        Operation::AdoptInstruction { run, head, request } => {
746            ensure!(
747                matches!(
748                    crate::chat_goal::current_source(),
749                    crate::chat_goal::Source::Input { .. }
750                ),
751                "adopt-instruction requires explicit owner input"
752            );
753            let result = Box::pin(crate::instruction_revision_control::adopt(
754                queue,
755                home,
756                crate::instruction_revision_control::Request {
757                    run,
758                    head,
759                    request,
760                    actor: talk.to_owned(),
761                },
762            ))
763            .await
764            .map_err(|error| {
765                if error.is::<crate::instruction_revision_control::BeforeWrite>() {
766                    anyhow::Error::new(BeforeEffect(error))
767                } else {
768                    error
769                }
770            })?;
771            if result.repeated {
772                format!(
773                    "This instruction adoption request was already applied to task {}; inspect its current status before continuing",
774                    result.task.id
775                )
776            } else {
777                format!(
778                    "{}; revised instruction adopted into the existing run and PR; the daemon resumes it for one bounded repair and fresh review",
779                    describe(&result.task, "instruction adoption queued for")
780                )
781            }
782        }
783        Operation::Resume { run } => {
784            let t = resume(queue, home, &run)?;
785            format!(
786                "{}; the loop (`magi serve`) resumes the run under its execution lease",
787                describe(&t, "resume queued for")
788            )
789        }
790        Operation::SyncBaseOnly { run } => {
791            ensure!(
792                matches!(
793                    crate::chat_goal::current_source(),
794                    crate::chat_goal::Source::Input { .. }
795                ),
796                "sync-base-only requires an explicit owner request in this chat turn"
797            );
798            let owner = run_task(queue, &run)?;
799            let _claim = queue.claim(&owner.id)?;
800            let mut task = queue.get(&owner.id)?;
801            crate::base_sync_only::queue(&mut task, home, &run)?;
802            queue.put(&mut task)?;
803            describe(&task, "base synchronization only queued for")
804        }
805        Operation::Hold { task, reason } => describe(
806            &hold_claimed(queue, claimed_for_chat(queue, &task, talks, talk)?, &reason)?,
807            "held",
808        ),
809        Operation::Release { task } => describe(
810            &release_claimed(queue, claimed_for_chat(queue, &task, talks, talk)?)?,
811            "released",
812        ),
813        Operation::Retry {
814            task,
815            title,
816            instruction,
817        } => describe(
818            &retry_claimed(
819                queue,
820                claimed_for_chat(queue, &task, talks, talk)?,
821                title,
822                &instruction,
823            )?,
824            "retry queued for",
825        ),
826        Operation::RerunChecks {
827            run,
828            request,
829            head,
830            workflows,
831        } => {
832            let ids = rerun_checks(queue, home, talk, &run, &request, &head, &workflows).await?;
833            format!("requested a rerun of workflow run(s) {}", ids.join(", "))
834        }
835        Operation::Decide {
836            question,
837            choice,
838            title,
839        } => {
840            let q = record_decision(home, &question, &choice, title.as_deref())?;
841            format!(
842                "recorded `{choice}` for decision {}; effect pending until its durable application receipt is confirmed",
843                q.short()
844            )
845        }
846        Operation::Answer {
847            question,
848            reply,
849            title,
850        } => crate::ask::record_answer(
851            &crate::ask::Questions::at(home.join("questions")),
852            &question,
853            &reply,
854            title.as_deref(),
855        )?,
856        Operation::ReplyOther { question, text } => crate::consult::reply_other(
857            &crate::ask::Questions::at(home.join("questions")),
858            &question,
859            &text,
860        )?,
861        Operation::ReconcileRetention {
862            task,
863            authority,
864            apply,
865        } => {
866            let path = Box::pin(crate::retention::reconcile::run_chat(
867                home,
868                &task,
869                &authority,
870                apply.as_deref(),
871                crate::retention::reconcile::ChatRequest {
872                    talks,
873                    conversation: talk,
874                },
875            ))
876            .await?;
877            if apply.is_none() {
878                // Return the complete saved evidence through the capability bridge.
879                crate::retention::reconcile::chat_summary(&path)?
880            } else {
881                format!(
882                    "Applied saved plan {}",
883                    apply.as_deref().unwrap_or_default()
884                )
885            }
886        }
887        Operation::Abandon { run } => {
888            abandon(queue, home, &run)?;
889            format!("abandoned run {run}")
890        }
891    })
892}
893
894pub(crate) fn build_task(filing: Filing, immediate: bool) -> Task {
895    let mut task = Task::new(filing.title, filing.instruction, filing.repo, filing.source);
896    task.issue = filing.issue;
897    task.investigation = filing.investigation;
898    task.sources = filing.sources;
899    if let Some(reason) = filing.hold {
900        task.hold_manual(Some(reason));
901    }
902    task.priority = filing.priority;
903    task.solo = filing.solo;
904    task.urgent = filing.urgent;
905    task.immediate = immediate;
906    if filing.implementers.is_some() || filing.build_cache.is_some() {
907        task.overrides = Some(crate::queue::RunOverrides {
908            inherit_daemon_options: filing.implementers.is_none(),
909            candidates: filing.implementers,
910            build_cache: filing.build_cache,
911            ..Default::default()
912        });
913    }
914    task
915}
916
917fn file_task(queue: &Queue, filing: Filing) -> Result<Task> {
918    let attach = filing.attach.clone();
919    let mut task = build_task(filing, false);
920    if attach.is_empty() {
921        queue.put(&mut task)?;
922    } else {
923        queue.attach_and_put(&mut task, &attach)?;
924    }
925    Ok(task)
926}
927
928/// A goal turn cannot redirect existing effects to unrelated work.
929fn admit_goal_operation(
930    queue: &Queue,
931    home: &Path,
932    talks: &Talks,
933    talk_id: &str,
934    operation: &Operation,
935) -> Result<()> {
936    let crate::chat_goal::Source::Goal { id, generation } = crate::chat_goal::current_source()
937    else {
938        return Ok(());
939    };
940    let talk = talks.get(talk_id)?;
941    let goal = talk
942        .goals
943        .iter()
944        .find(|goal| goal.id == id)
945        .context("unknown goal")?;
946    goal.admit(generation)?;
947    ensure!(
948        !goal.owner_input.is_empty(),
949        "this goal was registered under standing authorization; fresh owner input is required with the setting off"
950    );
951    let repo = goal.effective_repo(&talk.repo);
952    let task_allowed = |reference: &str| -> Result<()> {
953        let id = queue.resolve_id(reference)?;
954        ensure!(
955            goal.tasks.contains(&id),
956            "effect targets a task outside this goal"
957        );
958        crate::chat_goal::task_record(queue, &id, repo)?;
959        Ok(())
960    };
961    let run_allowed = |run: &str| -> Result<()> {
962        ensure!(
963            goal.runs.iter().any(|id| id == run)
964                || goal
965                    .tasks
966                    .iter()
967                    .any(|id| crate::chat_goal::task_record(queue, id, repo)
968                        .is_ok_and(|task| task.execution_runs().iter().any(|id| id == run))),
969            "effect targets an execution outside this goal"
970        );
971        crate::chat_goal::run_record(home, run, repo)?;
972        Ok(())
973    };
974    match operation {
975        Operation::Standing { .. } => bail!("standing authorization is disabled for this turn"),
976        Operation::Goal { .. } => {}
977        Operation::Add { filing } => {
978            crate::chat_goal::require_repo("filing", talk_id, &filing.repo, repo)?;
979            ensure!(
980                matches!(&filing.source, crate::queue::Source::Agent { run, node }
981                    if run == talk_id && node == crate::queue::CHAT_NODE),
982                "goal filing must retain this conversation's provenance"
983            );
984        }
985        Operation::SetImmediate { .. } => {
986            bail!(
987                "automatic goal turns cannot change immediate settings; explicit owner input is required"
988            )
989        }
990        Operation::AddImmediate { .. } => {
991            bail!(
992                "automatic goal turns cannot file immediate tasks; explicit owner input is required"
993            )
994        }
995        Operation::Done { discard: true, .. } | Operation::Reopen { .. } => {
996            anyhow::bail!("task discard and reopen require an explicit owner turn");
997        }
998        Operation::Done {
999            task,
1000            discard: false,
1001            ..
1002        }
1003        | Operation::Priority { task, .. }
1004        | Operation::Hold { task, .. }
1005        | Operation::Release { task }
1006        | Operation::Retry { task, .. }
1007        | Operation::ReconcileRetention { task, .. } => task_allowed(task)?,
1008        Operation::GrantRepair { request } => {
1009            task_allowed(&request.task)?;
1010            run_allowed(&request.run)?;
1011        }
1012        Operation::ReconcileRepairGrant { request } => {
1013            task_allowed(&request.task)?;
1014            run_allowed(&request.run)?;
1015        }
1016        Operation::AdoptInstruction { .. } => {
1017            bail!(
1018                "automatic goal turns cannot adopt a revised instruction; explicit owner input is required"
1019            )
1020        }
1021        Operation::RecoverLandSync { .. } => {
1022            bail!(
1023                "automatic goal turns cannot authorize landing base-sync recovery; explicit owner input is required"
1024            )
1025        }
1026        Operation::Resume { run }
1027        | Operation::SyncBaseOnly { run }
1028        | Operation::RecoverBase { run, .. }
1029        | Operation::Abandon { run }
1030        | Operation::RerunChecks { run, .. } => run_allowed(run)?,
1031        Operation::ForDecision { inquiry, .. }
1032        | Operation::ReconcileDecision { inquiry }
1033        | Operation::SettleDecision { inquiry, .. } => {
1034            let record = crate::task_inquiry::Outbox::at(home).get(inquiry)?;
1035            crate::chat_goal::require_repo("inquiry", inquiry, &record.repo, repo)?;
1036            task_allowed(&record.task)?;
1037            if let Some(run) = record.run {
1038                run_allowed(&run)?;
1039            }
1040        }
1041        Operation::Decide { question, .. }
1042        | Operation::Answer { question, .. }
1043        | Operation::ReplyOther { question, .. } => {
1044            let questions = crate::ask::Questions::at(home.join("questions"));
1045            let question = questions.get_for_effects(&questions.resolve_id(question)?)?;
1046            if question.run_names_task() {
1047                task_allowed(&question.run)?;
1048            } else {
1049                run_allowed(&question.run)?;
1050            }
1051        }
1052        Operation::MergePr {
1053            repo: slug, number, ..
1054        } => {
1055            let expected = format!("https://github.com/{slug}/pull/{number}");
1056            let mut found = false;
1057            let mut inspect = |run: &str| -> Result<()> {
1058                let state = crate::chat_goal::run_record(home, run, repo)?;
1059                found |= state
1060                    .pr
1061                    .as_ref()
1062                    .is_some_and(|pr| pr.url.eq_ignore_ascii_case(&expected));
1063                Ok(())
1064            };
1065            for run in &goal.runs {
1066                inspect(run)?;
1067            }
1068            for task in &goal.tasks {
1069                for run in crate::chat_goal::task_record(queue, task, repo)?.execution_runs() {
1070                    inspect(run)?;
1071                }
1072            }
1073            ensure!(found, "merge targets a pull request outside this goal");
1074        }
1075        Operation::Reassign { .. } => bail!("automatic goal turns cannot change repository scope"),
1076    }
1077    Ok(())
1078}
1079
1080/// Run one typed operation on behalf of the owner, retaining failures and
1081/// uncertainty. A repeated command never blindly replays a possibly applied
1082/// external effect. The underlying operation retains its existing claims and
1083/// receipts; this journal is its user-visible lifecycle, not a second worker.
1084async fn execute_decision(
1085    queue: &Queue,
1086    home: &Path,
1087    talks: &Talks,
1088    chat: &str,
1089    id: &str,
1090    command: Operation,
1091) -> Result<String> {
1092    use crate::task_decision::Status;
1093    admit_goal_operation(queue, home, talks, chat, &command)?;
1094    let outbox = crate::task_inquiry::Outbox::at(home);
1095    let _execution = outbox.execution_claim(id)?;
1096    let inquiry = outbox.get(id)?;
1097    ensure!(
1098        inquiry.delivered_to.as_deref() == Some(chat),
1099        "decision belongs to another chat"
1100    );
1101    let task = queue.get(&inquiry.task)?;
1102    ensure!(task.repo == inquiry.repo, "decision repository changed");
1103    let deferred = matches!(
1104        command,
1105        Operation::Resume { .. } | Operation::MergePr { .. }
1106    );
1107    let merge = match &command {
1108        Operation::MergePr {
1109            repo,
1110            number,
1111            head,
1112            request,
1113        } => Some(crate::chat_merge::Request {
1114            repo: repo.clone(),
1115            number: *number,
1116            head: head.clone(),
1117            request: request.clone(),
1118        }),
1119        _ => None,
1120    };
1121    match &command {
1122        Operation::Done { task: target, .. }
1123        | Operation::Reopen { task: target, .. }
1124        | Operation::Hold { task: target, .. }
1125        | Operation::Release { task: target }
1126        | Operation::Retry { task: target, .. } => {
1127            ensure!(
1128                queue.resolve_id(target)? == task.id,
1129                "command targets another task"
1130            );
1131        }
1132        Operation::Resume { run }
1133        | Operation::Abandon { run }
1134        | Operation::RerunChecks { run, .. } => {
1135            ensure!(
1136                task.runs.contains(run) && inquiry.run.as_ref().is_none_or(|own| own == run),
1137                "command targets another execution"
1138            );
1139            ensure!(
1140                queue
1141                    .list()
1142                    .iter()
1143                    .filter(|owner| owner.runs.contains(run))
1144                    .count()
1145                    == 1,
1146                "execution ownership is ambiguous"
1147            );
1148        }
1149        Operation::MergePr { repo, number, .. } => {
1150            let run = inquiry
1151                .run
1152                .as_ref()
1153                .or_else(|| task.runs.last())
1154                .context("task has no execution for this merge")?;
1155            let state = crate::run::RunState::load_under(run, home)?;
1156            ensure!(state.id == *run, "merge run identity changed");
1157            ensure!(
1158                crate::git::same_checkout(&state.repo, &task.repo)?,
1159                "merge targets another repository"
1160            );
1161            let expected = format!("https://github.com/{repo}/pull/{number}");
1162            ensure!(
1163                state
1164                    .pr
1165                    .as_ref()
1166                    .is_some_and(|pr| pr.url.eq_ignore_ascii_case(&expected)),
1167                "merge targets another task or repository"
1168            );
1169        }
1170        _ => bail!("use a task/run effect command with --decision; routed approvals use decide"),
1171    }
1172    let request = serde_json::to_string(&command)?;
1173    let mut decision = inquiry.decision.context("inquiry is informational")?;
1174    if decision.request.is_some()
1175        && decision.status != Status::Resolved
1176        && let Operation::Resume { run } = &command
1177    {
1178        ensure!(
1179            decision.request.as_deref() == Some(&request),
1180            "decision already binds a different request"
1181        );
1182        // Queued also includes successfully published resumes. Reconcile under
1183        // the execution claim before permitting any retry, even if the run has
1184        // since returned to a resumable state. Only proven non-publication may
1185        // enter the retry path below.
1186        reconcile_resume_claimed(queue, home, &outbox, id, run)?;
1187        decision = outbox
1188            .get(id)?
1189            .decision
1190            .context("inquiry is informational")?;
1191        ensure!(
1192            decision.status == Status::Resolved || decision.retry_safe,
1193            "previous resume remains queued or executing; it will not be replayed"
1194        );
1195    }
1196    if decision.status == Status::Resolved {
1197        ensure!(
1198            decision.request.as_deref() == Some(&request),
1199            "decision resolved for a different request"
1200        );
1201        return Ok(format!(
1202            "decision {id} is already resolved; inspect its outcome history"
1203        ));
1204    }
1205    if let Operation::RerunChecks { run, request, .. } = &command {
1206        // Reject correctable input before binding the decision to this exact
1207        // command. Execution revalidates these reads before taking its lock.
1208        rerun_preflight(queue, home, run, request)?;
1209    }
1210    if let Some(action) = &merge {
1211        // Malformed input must not durably bind this decision to a command
1212        // that can never reach its effect service.
1213        action.validate()?;
1214    }
1215    // Keep admission across acceptance and execution: contention and request
1216    // collisions must not bind a fresh decision to an unstartable operation.
1217    let merge_admission = merge
1218        .as_ref()
1219        .map(|action| crate::chat_merge::admit(home, talks, chat, action))
1220        .transpose()?;
1221    if decision.request.is_none() && decision.status == Status::RetryNeeded {
1222        if let Ok(source) = crate::ask::Questions::at(home.join("questions")).get(id) {
1223            ensure!(
1224                !crate::task_chat::awaits_decision(&source),
1225                "a legacy effect still needs its receipt reconciled before another effect is accepted"
1226            );
1227        }
1228    }
1229    {
1230        // A live task cannot accept a repair grant. Do not prevent decisions
1231        // that its active driver is waiting for by taking its execution claim.
1232        let claim = (queue.get(&task.id)?.status != TaskStatus::Running)
1233            .then(|| queue.claim(&task.id))
1234            .transpose();
1235        let _claim = match claim {
1236            Ok(claim) => claim,
1237            Err(error) => {
1238                // Admission could not start this attempt. Retain the exact
1239                // owner request and pre-effect failure just as execution-side
1240                // claim contention does, without publishing any task effect.
1241                let message = format!(
1242                    "{error:#}. No effect began; retry this same request after resolving the cause, or explicitly settle it."
1243                );
1244                outbox.update_decision(id, |d| {
1245                    let safe = d.request.is_none() || d.retry_safe;
1246                    d.accept(&request)?;
1247                    if safe {
1248                        d.fail_before_effect(&message)
1249                    } else {
1250                        // A prior queued/uncertain attempt still needs its own
1251                        // receipt. Contention is not proof that it never ran.
1252                        Ok(false)
1253                    }
1254                })?;
1255                return Err(anyhow::Error::new(BeforeEffect(error)));
1256            }
1257        };
1258        outbox.update_decision(id, |d| d.accept(&request))?;
1259    }
1260    let late_admission = crate::chat_goal::fence(talks, chat, &crate::chat_goal::current_source())
1261        .and_then(|()| admit_goal_operation(queue, home, talks, chat, &command));
1262    if late_admission.is_ok()
1263        && decision.request.is_some()
1264        && matches!(decision.status, Status::InProgress | Status::RetryNeeded)
1265    {
1266        if decision.retry_safe {
1267            outbox.update_decision(id, |d| {
1268                d.retry_unapplied()?;
1269                d.start()
1270            })?;
1271        } else {
1272            let action = merge
1273                .as_ref()
1274                .context("previous effect needs receipt reconciliation; it will not be replayed")?;
1275            ensure!(
1276                merge_receipt(home, chat, action)?.is_some(),
1277                "previous merge has no receipt; inspect the operation before retrying"
1278            );
1279        }
1280        // The shared merge service only checks the forge once this exact
1281        // request has a receipt; it never issues the merge command twice.
1282    } else if late_admission.is_ok() {
1283        outbox.update_decision(id, |d| d.start())?;
1284    }
1285    let local = match late_admission {
1286        // A refusal now says nothing about a prior attempt that may have acted.
1287        Err(error)
1288            if decision.request.is_some()
1289                && !decision.retry_safe
1290                && (matches!(decision.status, Status::InProgress | Status::RetryNeeded)
1291                    || decision
1292                        .history
1293                        .iter()
1294                        .any(|event| event.status == Status::InProgress)) =>
1295        {
1296            return Err(error);
1297        }
1298        Err(error) => Err(anyhow::Error::new(BeforeEffect(error))),
1299        Ok(()) => {
1300            Box::pin(apply_local_decision(
1301                queue,
1302                home,
1303                id,
1304                &request,
1305                &inquiry.task,
1306                &inquiry.repo,
1307                &command,
1308            ))
1309            .await
1310        }
1311    };
1312    let result = if let Err(error) = local {
1313        Err(error)
1314    } else if let Some(message) = local? {
1315        Ok(message)
1316    } else if let Operation::Resume { run } = &command {
1317        // Validation precedes any write: a refusal means nothing began.
1318        crate::resume::validate(home, run)
1319            .map(|_| ())
1320            .map_err(|e| anyhow::Error::new(BeforeEffect(e)))
1321            .and_then(|()| -> Result<String> {
1322                let pinned =
1323                    crate::resume::pin_queued(queue, run, None, Some(id)).map_err(|error| {
1324                        if error.is::<crate::resume::BeforeQueueWrite>() {
1325                            anyhow::Error::new(BeforeEffect(error))
1326                        } else {
1327                            error
1328                        }
1329                    })?;
1330                if !pinned {
1331                    return Err(anyhow::Error::new(BeforeEffect(anyhow::anyhow!(
1332                        "no queued task owns this run"
1333                    ))));
1334                }
1335                Ok(format!(
1336                    "resume queued for {run}; execution start remains unconfirmed"
1337                ))
1338            })
1339    } else if let Operation::Abandon { run } = &command {
1340        crate::driver::abandon_decision(home, run, id, &request)
1341            .map_err(|error| {
1342                if error.is::<crate::driver::BeforeAbandonWrite>() {
1343                    anyhow::Error::new(BeforeEffect(error))
1344                } else {
1345                    error
1346                }
1347            })
1348            .map(|()| format!("abandoned run {run}"))
1349    } else if let Some(admission) = merge_admission {
1350        crate::chat_merge::merge_admitted(home, merge.as_ref().unwrap().clone(), admission)
1351            .await
1352            .map_err(|error| {
1353                if error.is::<crate::chat_merge::BeforeMergeWrite>() {
1354                    anyhow::Error::new(BeforeEffect(error))
1355                } else {
1356                    error
1357                }
1358            })
1359    } else {
1360        Box::pin(execute(queue, home, talks, chat, command)).await
1361    };
1362    match result {
1363        Ok(message) => {
1364            if let Some(action) = &merge {
1365                if let Some(receipt) = merge_receipt(home, chat, action)? {
1366                    if receipt["status"] == "merged" {
1367                        outbox.update_decision(id, |d| d.applied(&message))?;
1368                    } else if receipt["status"] != "pending" {
1369                        outbox.update_decision(id, |d| {
1370                            d.fail(&format!(
1371                                "{message}; reuse this same request ID to reconcile only"
1372                            ))
1373                        })?;
1374                    }
1375                }
1376            } else if !deferred {
1377                outbox.update_decision(id, |d| {
1378                    d.applied(&format!("typed command completed: {message}"))
1379                })?;
1380            }
1381            if deferred
1382                && outbox
1383                    .get(id)?
1384                    .decision
1385                    .as_ref()
1386                    .is_some_and(|d| d.status == Status::InProgress)
1387            {
1388                outbox.update_decision(id, |d| d.queued())?;
1389            }
1390            // Resume has only been queued. Its execution is confirmed by a
1391            // later scheduler projection, never by this command's return.
1392            Ok(message)
1393        }
1394        Err(error) => {
1395            let message = if error.is::<BeforeEffect>() {
1396                format!(
1397                    "{error:#}. No effect began; retry this same request after resolving the cause, or explicitly settle it."
1398                )
1399            } else {
1400                format!(
1401                    "Operation failed or has an uncertain result: {error:#}. Inspect its receipt before retrying."
1402                )
1403            };
1404            outbox.update_decision(id, |d| {
1405                if error.is::<BeforeEffect>() {
1406                    d.fail_before_effect(&message)
1407                } else {
1408                    d.fail(&message)
1409                }
1410            })?;
1411            Err(error)
1412        }
1413    }
1414}
1415
1416#[derive(Debug, thiserror::Error)]
1417#[error("effect did not start: {0:#}")]
1418struct BeforeEffect(anyhow::Error);
1419
1420/// Commit a task-local effect and its exact receipt under one queue claim.
1421/// The inquiry projection may lag this write, but restart never has to infer
1422/// completion from the task's current status or repeat the operation.
1423async fn apply_local_decision(
1424    queue: &Queue,
1425    home: &Path,
1426    id: &str,
1427    request: &str,
1428    owner: &str,
1429    repo: &Path,
1430    command: &Operation,
1431) -> Result<Option<String>> {
1432    let target = match command {
1433        Operation::Done { task, .. }
1434        | Operation::Reopen { task, .. }
1435        | Operation::Hold { task, .. }
1436        | Operation::Release { task }
1437        | Operation::Retry { task, .. } => task,
1438        _ => return Ok(None),
1439    };
1440    let prepare = async {
1441        let (_claim, mut task) = claimed(queue, target)?;
1442        let expected = task.clone();
1443        ensure!(
1444            task.id == owner && task.repo == repo,
1445            "decision ownership changed"
1446        );
1447        if let Some(prior) = task.decision_effects.get(id) {
1448            ensure!(prior == request, "decision receipt binds another command");
1449            let message = format!("task {}: decision {id} already applied", task.id);
1450            return Ok((_claim, task, message, true, None, expected));
1451        }
1452        let mut close_guard = None;
1453        let message = match command {
1454            Operation::Done {
1455                reason,
1456                result,
1457                discard,
1458                ..
1459            } => {
1460                let (guards, context) = crate::task_completion::admit_close(
1461                    &task,
1462                    home,
1463                    crate::queue::CompletionActor::Chat(
1464                        crate::task_inquiry::Outbox::at(home)
1465                            .get(id)?
1466                            .delivered_to
1467                            .context("decision has no chat")?,
1468                    ),
1469                    reason.clone(),
1470                    result.clone(),
1471                    *discard,
1472                )
1473                .await?;
1474                if !*discard && task.investigation {
1475                    task.record_investigation_result(result.as_deref())?;
1476                }
1477                close_guard = Some(guards);
1478                task.succeed(context);
1479                crate::task_completion::describe(&task)
1480            }
1481            Operation::Reopen { reason, .. } => {
1482                let (guards, context) = crate::task_completion::admit_reopen(
1483                    &task,
1484                    home,
1485                    crate::queue::CompletionActor::Chat(
1486                        crate::task_inquiry::Outbox::at(home)
1487                            .get(id)?
1488                            .delivered_to
1489                            .context("decision has no chat")?,
1490                    ),
1491                    reason,
1492                )
1493                .await?;
1494                close_guard = Some(guards);
1495                task.reopen(context)?;
1496                describe(&task, "reopened on hold")
1497            }
1498            Operation::Hold { reason, .. } => {
1499                check_hold_release(&task, "hold")?;
1500                let reason = reason.trim();
1501                task.hold_manual((!reason.is_empty()).then(|| reason.to_owned()));
1502                describe(&task, "held")
1503            }
1504            Operation::Release { .. } => {
1505                check_hold_release(&task, "release")?;
1506                task.release_operator("chat", Some(id));
1507                describe(&task, "released")
1508            }
1509            Operation::Retry {
1510                title, instruction, ..
1511            } => {
1512                ensure!(
1513                    !instruction.trim().is_empty(),
1514                    "the new instruction is empty"
1515                );
1516                let title = title
1517                    .clone()
1518                    .unwrap_or_else(|| crate::queue::title_from(instruction, 72));
1519                task.edit(title, instruction.clone())?;
1520                task.release_operator("chat", Some(id));
1521                describe(&task, "retry queued for")
1522            }
1523            _ => unreachable!("task-local operation checked above"),
1524        };
1525        task.decision_effects
1526            .insert(id.to_owned(), request.to_owned());
1527        Ok::<_, anyhow::Error>((_claim, task, message, false, close_guard, expected))
1528    };
1529    let (_claim, mut task, message, already_applied, close_guard, expected) =
1530        prepare.await.map_err(BeforeEffect)?;
1531    if !already_applied {
1532        if close_guard.is_some() {
1533            queue.commit_completion(&mut task, &expected)?;
1534        } else {
1535            queue.put(&mut task)?;
1536        }
1537    }
1538    if matches!(command, Operation::Done { .. }) {
1539        crate::daemon::supersede_prior_runs(&task, home);
1540    }
1541    Ok(Some(message))
1542}
1543
1544/// Explicit owner-requested reconciliation executes nothing. Under the task
1545/// claim, prove that the exact intended condition already holds; otherwise keep
1546/// uncertainty visible. External effects require their own receipts instead.
1547fn reconcile_task_decision(queue: &Queue, home: &Path, chat: &str, id: &str) -> Result<()> {
1548    let outbox = crate::task_inquiry::Outbox::at(home);
1549    let inquiry = outbox.get(id)?;
1550    ensure!(
1551        inquiry.delivered_to.as_deref() == Some(chat)
1552            || (inquiry.task.is_empty() && inquiry.delivered_to.is_none()),
1553        "decision belongs to another chat"
1554    );
1555    let decision = inquiry.decision.context("inquiry is informational")?;
1556    if decision.status == crate::task_decision::Status::Resolved {
1557        return Ok(());
1558    }
1559    if decision
1560        .request
1561        .as_ref()
1562        .is_none_or(|request| request.starts_with("decision: "))
1563    {
1564        let source = crate::ask::Questions::at(home.join("questions")).read_history(id)?;
1565        crate::task_chat::sync_effect_receipt(home, queue, &source);
1566        ensure!(
1567            outbox
1568                .get(id)?
1569                .decision
1570                .is_some_and(|d| d.status == crate::task_decision::Status::Resolved),
1571            "source effect remains unconfirmed; no operation was replayed"
1572        );
1573        return Ok(());
1574    }
1575    let request = decision
1576        .request
1577        .context("decision has no accepted operation to reconcile")?;
1578    let command: Operation = serde_json::from_str(&request)?;
1579    if let Operation::Resume { run } = &command {
1580        reconcile_resume_decision(queue, home, &outbox, id, run)?;
1581        ensure!(
1582            outbox.get(id)?.decision.is_some_and(|d| {
1583                d.status == crate::task_decision::Status::Resolved || d.retry_safe
1584            }),
1585            "resume remains queued or executing; no operation was replayed"
1586        );
1587        return Ok(());
1588    }
1589    let (_claim, task) = claimed(queue, &inquiry.task)?;
1590    ensure!(task.repo == inquiry.repo, "decision repository changed");
1591    if let Some(receipt) = task.decision_effects.get(id) {
1592        ensure!(
1593            receipt == &request,
1594            "decision receipt binds another command"
1595        );
1596        return outbox.update_decision(id, |d| {
1597            d.applied("exact task command receipt confirmed; no operation replayed")
1598        });
1599    }
1600    let matches = match command {
1601        Operation::Hold {
1602            task: target,
1603            reason,
1604        } => {
1605            queue.resolve_id(&target)? == task.id
1606                && task.status == TaskStatus::Held
1607                && task.hold_reason.as_deref() == Some(reason.trim())
1608        }
1609        Operation::Release { task: target } => {
1610            queue.resolve_id(&target)? == task.id
1611                && task.status == TaskStatus::Queued
1612                && !task.operator_held()
1613        }
1614        Operation::Done { task: target, .. } => {
1615            queue.resolve_id(&target)? == task.id && task.status == TaskStatus::Done
1616        }
1617        Operation::Retry {
1618            task: target,
1619            title,
1620            instruction,
1621        } => {
1622            queue.resolve_id(&target)? == task.id
1623                && task.instruction == instruction
1624                && title.as_ref().is_none_or(|title| *title == task.title)
1625                && task.status == TaskStatus::Queued
1626        }
1627        Operation::Abandon { run } => abandonment_receipt(home, &task, id, &run, &request)?,
1628        _ => anyhow::bail!(
1629            "external effects require their authoritative receipt; no operation was replayed"
1630        ),
1631    };
1632    ensure!(
1633        matches,
1634        "intended task condition is not confirmed; no operation was replayed"
1635    );
1636    outbox.update_decision(id, |d| d.applied("owner-requested reconciliation: exact intended task condition confirmed under its claim; no effect remains necessary"))
1637}
1638
1639/// Read the exact request's committed execution pass or durable pin supersession.
1640/// A transient task status alone never proves either outcome.
1641pub(crate) fn resume_started(home: &Path, task: &Task, inquiry: &str, run: &str) -> Result<bool> {
1642    ensure!(
1643        crate::run::is_run_id(run) && task.runs.iter().any(|id| id == run),
1644        "resume run ownership changed"
1645    );
1646    let state = crate::run::RunState::load_under(run, home)?;
1647    ensure!(state.id == run, "resume run identity changed");
1648    ensure!(
1649        crate::git::same_checkout(&state.repo, &task.repo)?,
1650        "resume run repository changed"
1651    );
1652    if task
1653        .superseded_resumes
1654        .get(inquiry)
1655        .is_some_and(|target| target == run)
1656    {
1657        return Ok(true);
1658    }
1659    Ok(state.decision_starts.get(inquiry).is_some_and(|index| {
1660        state
1661            .passes
1662            .get(*index)
1663            .is_some_and(|pass| pass.index == *index)
1664    }))
1665}
1666
1667/// Publication writes the pin and actions_applied marker atomically. Fence the
1668/// publisher and scheduler before treating their absence as pre-effect proof.
1669/// A published pin may already be consumed, so its absence alone is not proof.
1670fn reconcile_resume_decision(
1671    queue: &Queue,
1672    home: &Path,
1673    outbox: &crate::task_inquiry::Outbox,
1674    id: &str,
1675    run: &str,
1676) -> Result<()> {
1677    let Ok(_execution) = outbox.execution_claim(id) else {
1678        return Ok(());
1679    };
1680    reconcile_resume_claimed(queue, home, outbox, id, run)
1681}
1682
1683/// The caller holds this inquiry's execution claim, including on resubmission.
1684fn reconcile_resume_claimed(
1685    queue: &Queue,
1686    home: &Path,
1687    outbox: &crate::task_inquiry::Outbox,
1688    id: &str,
1689    run: &str,
1690) -> Result<()> {
1691    let inquiry = outbox.get(id)?;
1692    let Ok(_claim) = queue.claim(&inquiry.task) else {
1693        return Ok(());
1694    };
1695    let task = queue.get(&inquiry.task)?;
1696    ensure!(task.repo == inquiry.repo, "resume task repository changed");
1697    let decision = inquiry.decision.context("inquiry is informational")?;
1698    if decision.status == crate::task_decision::Status::Resolved {
1699        return Ok(());
1700    }
1701    if resume_started(home, &task, id, run)? {
1702        outbox.update_decision(id, |d| {
1703            d.applied("exact resume execution-start or supersession receipt confirmed")
1704        })?;
1705    } else if !task.action_applied(id)
1706        && !task.dispatched_resumes.contains_key(id)
1707        && !task.superseded_resumes.contains_key(id)
1708        && !task
1709            .resume_override
1710            .as_ref()
1711            .is_some_and(|pin| pin.question_id == id)
1712    {
1713        outbox.update_decision(id, |d| {
1714            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.")
1715        })?;
1716    }
1717    Ok(())
1718}
1719
1720fn abandonment_receipt(
1721    home: &Path,
1722    task: &Task,
1723    id: &str,
1724    run: &str,
1725    request: &str,
1726) -> Result<bool> {
1727    ensure!(
1728        task.runs.iter().any(|own| own == run),
1729        "abandon run ownership changed"
1730    );
1731    let state = crate::run::RunState::load_under(run, home)?;
1732    ensure!(state.id == run, "abandon run identity changed");
1733    ensure!(
1734        crate::git::same_checkout(&state.repo, &task.repo)?,
1735        "abandon run repository changed"
1736    );
1737    Ok(state
1738        .abandonment_receipts
1739        .get(id)
1740        .is_some_and(|receipt| receipt == request))
1741}
1742
1743fn merge_receipt(
1744    home: &Path,
1745    chat: &str,
1746    action: &crate::chat_merge::Request,
1747) -> Result<Option<serde_json::Value>> {
1748    ensure!(
1749        crate::ask::valid_asset_name(chat) && crate::ask::valid_asset_name(&action.request),
1750        "invalid merge receipt identity"
1751    );
1752    let path = home
1753        .join("chat-controls")
1754        .join(chat)
1755        .join(format!("{}.json", action.request));
1756    let bytes = match std::fs::read(path) {
1757        Ok(bytes) => bytes,
1758        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
1759        Err(error) => return Err(error.into()),
1760    };
1761    let receipt: serde_json::Value = serde_json::from_slice(&bytes)?;
1762    ensure!(
1763        receipt["action"] == serde_json::to_value(action)?,
1764        "merge receipt names another operation"
1765    );
1766    Ok(Some(receipt))
1767}
1768
1769#[derive(Debug, PartialEq, Eq)]
1770struct ApprovalEvidence {
1771    target: crate::merge_decision::Target,
1772    terminal: bool,
1773    successor: Option<(String, String)>,
1774}
1775
1776impl ApprovalEvidence {
1777    fn obsolete_reason(&self, state: &str, head: &str) -> Option<String> {
1778        if self.terminal
1779            && let Some(reason) = obsolete_pr_reason(state, head, &self.target)
1780        {
1781            return Some(reason);
1782        }
1783        let (question, successor_head) = self.successor.as_ref()?;
1784        if state == "OPEN" && head == successor_head && head != self.target.head {
1785            return Some(format!(
1786                "Obsolete: approval for {} at {} was retired in favor of inquiry {question} at {head}",
1787                self.target.pr, self.target.head
1788            ));
1789        }
1790        None
1791    }
1792}
1793
1794/// Read the exact source target and whether no effect can remain.
1795fn approval_target(
1796    home: &Path,
1797    queue: &Queue,
1798    inquiry: &crate::task_inquiry::Inquiry,
1799) -> Option<ApprovalEvidence> {
1800    use crate::task_decision::Status;
1801    let decision = inquiry.decision.as_ref()?;
1802    if decision.status == Status::Resolved || inquiry.task.is_empty() {
1803        return None;
1804    }
1805    let task = queue.get(&inquiry.task).ok()?;
1806    if task.id != inquiry.task || task.repo != inquiry.repo {
1807        return None;
1808    }
1809    let run_id = inquiry.run.as_ref()?;
1810    if !task.execution_runs().contains(run_id) {
1811        return None;
1812    }
1813    let q = crate::ask::Questions::at(home.join("questions"))
1814        .read_history(&inquiry.id)
1815        .ok()?;
1816    if inquiry.key != format!("question:{}", q.id)
1817        || q.node != crate::land::APPROVAL_NODE
1818        || q.run != *run_id
1819        || q.legacy_foreground
1820        || q.routed_task.as_ref().is_some_and(|id| id != &task.id)
1821        || crate::task_chat::task_of(&q, &queue.list()).as_ref() != Some(&task.id)
1822    {
1823        return None;
1824    }
1825    let no_reply = q.answer.is_none()
1826        || (q.resolution().as_deref() == Some(crate::land::APPROVE)
1827            && crate::task_chat::migration_sources(home)
1828                .is_ok_and(|ids| ids.is_some_and(|ids| ids.contains(&q.id)))
1829            && crate::task_chat::source_reply_needs_confirmation(home, &q));
1830    let target = q.merge_target.clone()?;
1831    let run = crate::run::RunState::load_under(run_id, home).ok()?;
1832    if run.id != *run_id
1833        || run.repo != task.repo
1834        || !task.assignment_accepts(&run)
1835        || run
1836            .origin
1837            .as_ref()
1838            .and_then(|o| o.task.as_ref())
1839            .is_some_and(|id| id != &task.id)
1840        || target.head.is_empty()
1841        || !run.pr.as_ref().is_some_and(|pr| pr.url == target.pr)
1842        || run.pr_publication_pending
1843    {
1844        return None;
1845    }
1846    let safe_retry = decision.retry_safe
1847        && decision.request.as_deref() == Some("decision: merge")
1848        && q.resolution().as_deref() == Some(crate::land::APPROVE)
1849        && decision.source_answer_at.is_some()
1850        && decision.source_answer_at == q.answered_at;
1851    let unstarted = ((decision.request.is_none() && no_reply) || safe_retry)
1852        && !task.blocked_by.contains(&q.id)
1853        && task.status != TaskStatus::Held;
1854    let terminal = unstarted
1855        && task.status == TaskStatus::Done
1856        && matches!(
1857            run.status,
1858            crate::run::RunStatus::Merged | crate::run::RunStatus::Ready
1859        );
1860    let successor = if unstarted && q.status == crate::ask::QuestionStatus::Abandoned {
1861        superseding_approval(home, inquiry, &run, &target)
1862    } else {
1863        None
1864    };
1865    Some(ApprovalEvidence {
1866        target,
1867        terminal,
1868        successor,
1869    })
1870}
1871
1872fn superseding_approval(
1873    home: &Path,
1874    old: &crate::task_inquiry::Inquiry,
1875    run: &crate::run::RunState,
1876    target: &crate::merge_decision::Target,
1877) -> Option<(String, String)> {
1878    let binding = run.land_approval.as_ref()?;
1879    if binding.question == old.id || binding.head == target.head {
1880        return None;
1881    }
1882    let q = crate::ask::Questions::at(home.join("questions"))
1883        .read_history(&binding.question)
1884        .ok()?;
1885    if q.run != run.id
1886        || q.node != crate::land::APPROVAL_NODE
1887        || !q.status.open()
1888        || q.routed_task.as_ref().is_some_and(|task| task != &old.task)
1889        || !q
1890            .merge_target
1891            .as_ref()
1892            .is_some_and(|next| next.pr == target.pr && next.head == binding.head)
1893    {
1894        return None;
1895    }
1896    let next = crate::task_inquiry::Outbox::at(home).get(&q.id).ok()?;
1897    if next.task != old.task
1898        || next.repo != old.repo
1899        || next.run != old.run
1900        || next.key != format!("question:{}", q.id)
1901        || next
1902            .decision
1903            .as_ref()
1904            .is_none_or(|d| d.status == crate::task_decision::Status::Resolved)
1905    {
1906        return None;
1907    }
1908    Some((binding.question.clone(), binding.head.clone()))
1909}
1910
1911/// Finite retrospective scan. Forge observations are made before taking any
1912/// execution or queue claim, and never authorize a command.
1913pub(crate) async fn retire_obsolete_decisions(queue: &Queue, home: &Path) -> Result<()> {
1914    retire_obsolete_with(queue, home, |repo, pr| async move {
1915        observe_decision_pr(&repo, &pr).await
1916    })
1917    .await
1918}
1919
1920#[derive(serde::Serialize, serde::Deserialize)]
1921struct DecisionCursor {
1922    cursor: String,
1923    high_water: String,
1924}
1925
1926async fn retire_obsolete_with<F, Fut>(queue: &Queue, home: &Path, mut observe: F) -> Result<()>
1927where
1928    F: FnMut(std::path::PathBuf, String) -> Fut,
1929    Fut: Future<Output = Option<(String, String)>>,
1930{
1931    let outbox = crate::task_inquiry::Outbox::at(home);
1932    let (mut items, _) = outbox.list_readable()?;
1933    items.retain(|i| {
1934        i.decision
1935            .as_ref()
1936            .is_some_and(|d| d.status != crate::task_decision::Status::Resolved)
1937    });
1938    items.sort_by(|a, b| a.id.cmp(&b.id));
1939    let cursor_path = home.join("decision-reconcile-cursor");
1940    let Some(last) = items.last() else {
1941        return Ok(());
1942    };
1943    let fresh = || DecisionCursor {
1944        cursor: String::new(),
1945        high_water: last.id.clone(),
1946    };
1947    let mut cycle = std::fs::read(&cursor_path)
1948        .ok()
1949        .and_then(|body| serde_json::from_slice::<DecisionCursor>(&body).ok())
1950        .filter(|c| c.cursor <= c.high_water)
1951        .unwrap_or_else(fresh);
1952    let range = |cycle: &DecisionCursor| {
1953        items.partition_point(|i| i.id <= cycle.cursor)
1954            ..items.partition_point(|i| i.id <= cycle.high_water)
1955    };
1956    if range(&cycle).is_empty() {
1957        cycle = fresh();
1958    }
1959    let range = range(&cycle);
1960    let mut observations = std::collections::BTreeMap::new();
1961    for inquiry in items[range].iter().take(32) {
1962        if let Some(evidence) = approval_target(home, queue, inquiry) {
1963            let target = evidence.target;
1964            let key = (inquiry.repo.clone(), target.pr.clone());
1965            if !observations.contains_key(&key) {
1966                if observations.len() == 5 {
1967                    break;
1968                }
1969                let result = observe(key.0.clone(), key.1.clone()).await;
1970                observations.insert(key.clone(), result);
1971            }
1972            if let Ok(_execution) = outbox.execution_claim(&inquiry.id)
1973                && let Ok(_claim) = queue.claim(&inquiry.task)
1974                && let Ok(_task_write) = queue.lock_task(&inquiry.task)
1975                && let Some(run) = &inquiry.run
1976                && let Ok(_owner) = crate::pr_head::owner_lock(home, run)
1977            {
1978                let questions = crate::ask::Questions::at(home.join("questions"));
1979                if let Err(error) = questions.try_inspect_history(&inquiry.id, || {
1980                    let current = outbox.get(&inquiry.id)?;
1981                    if current != *inquiry {
1982                        return Ok(());
1983                    }
1984                    let Some(current_evidence) = approval_target(home, queue, &current) else {
1985                        return Ok(());
1986                    };
1987                    if current_evidence.target != target {
1988                        return Ok(());
1989                    }
1990                    let observed = observations.get(&key).and_then(Option::as_ref);
1991                    let observation = target_observation(&target, observed);
1992                    let reason = observed
1993                        .and_then(|(state, head)| current_evidence.obsolete_reason(state, head));
1994                    outbox.try_update_decision(&inquiry.id, |d| {
1995                        if current.decision.as_ref() != Some(d) {
1996                            return Ok(false);
1997                        }
1998                        let changed = d.observe(observation);
1999                        if let Some(reason) = reason {
2000                            return Ok(d.retire_target(&reason)? || changed);
2001                        }
2002                        Ok(changed)
2003                    })
2004                }) {
2005                    tracing::debug!("decision {} reconciliation deferred: {error:#}", inquiry.id);
2006                }
2007            }
2008        }
2009        let temporary = cursor_path.with_extension("tmp");
2010        cycle.cursor.clone_from(&inquiry.id);
2011        std::fs::write(&temporary, serde_json::to_vec(&cycle)?)?;
2012        std::fs::rename(temporary, &cursor_path)?;
2013    }
2014    Ok(())
2015}
2016
2017async fn observe_decision_pr(repo: &Path, pr: &str) -> Option<(String, String)> {
2018    let mut command = tokio::process::Command::new("gh");
2019    command
2020        .args(["pr", "view", pr, "--json", "url,state,headRefOid"])
2021        .current_dir(repo)
2022        .env_remove("GH_REPO")
2023        .stdin(std::process::Stdio::null())
2024        .kill_on_drop(true);
2025    let output = tokio::time::timeout(std::time::Duration::from_secs(5), command.output())
2026        .await
2027        .ok()?
2028        .ok()?;
2029    if !output.status.success() {
2030        return None;
2031    }
2032    let snapshot: serde_json::Value = serde_json::from_slice(&output.stdout).ok()?;
2033    let head = snapshot["headRefOid"].as_str()?;
2034    if snapshot["url"].as_str()? != pr || head.is_empty() {
2035        return None;
2036    }
2037    Some((snapshot["state"].as_str()?.to_owned(), head.to_owned()))
2038}
2039
2040fn target_observation(
2041    target: &crate::merge_decision::Target,
2042    observed: Option<&(String, String)>,
2043) -> crate::task_decision::TargetObservation {
2044    use crate::task_decision::{TargetObservation, TargetState};
2045    let state = match observed.map(|(state, _)| state.as_str()) {
2046        Some("OPEN") => TargetState::Open,
2047        Some("MERGED") => TargetState::Merged,
2048        Some("CLOSED") => TargetState::Closed,
2049        _ => TargetState::Unknown,
2050    };
2051    TargetObservation {
2052        pr: target.pr.clone(),
2053        target_head: target.head.clone(),
2054        head: observed.map(|(_, head)| head.clone()),
2055        state,
2056    }
2057}
2058
2059fn obsolete_pr_reason(
2060    state: &str,
2061    head: &str,
2062    target: &crate::merge_decision::Target,
2063) -> Option<String> {
2064    let outcome = match state {
2065        "MERGED" if head == target.head => "merged at the requested head",
2066        "MERGED" => "merged at a different head",
2067        _ => return None,
2068    };
2069    Some(format!(
2070        "Obsolete: {} is {outcome} (observed head {head}); no approval effect remains. This does not confirm application of a request.",
2071        target.pr
2072    ))
2073}
2074
2075#[cfg(test)]
2076#[test]
2077fn obsolete_pr_requires_terminal_forge_state() {
2078    let target = crate::merge_decision::Target {
2079        pr: "https://github.com/example/project/pull/42".into(),
2080        head: "old-head".into(),
2081        language: "en".into(),
2082    };
2083    assert!(obsolete_pr_reason("OPEN", "new-head", &target).is_none());
2084    assert!(obsolete_pr_reason("UNKNOWN", "old-head", &target).is_none());
2085    assert!(
2086        obsolete_pr_reason("MERGED", "old-head", &target)
2087            .unwrap()
2088            .contains("requested head")
2089    );
2090    assert!(
2091        obsolete_pr_reason("MERGED", "new-head", &target)
2092            .unwrap()
2093            .contains("different head")
2094    );
2095    assert!(obsolete_pr_reason("CLOSED", "old-head", &target).is_none());
2096}
2097
2098#[cfg(test)]
2099#[tokio::test]
2100async fn obsolete_approval_needs_original_run_and_unaccepted_source() {
2101    use crate::{
2102        ask::{Question, Questions},
2103        queue::Source,
2104        run::{RunState, RunStatus},
2105    };
2106    let tmp = tempfile::tempdir().unwrap();
2107    let home = tmp.path();
2108    let queue = Queue::at(home.join("queue"));
2109    let mut task = Task::new("work".into(), "work".into(), home.into(), Source::Human);
2110    task.status = TaskStatus::Done;
2111    queue.put(&mut task).unwrap();
2112    let mut run = RunState::new(
2113        home.into(),
2114        "main".into(),
2115        "base".into(),
2116        "work".into(),
2117        crate::config::Config::default(),
2118    );
2119    run.reserve_under(home).unwrap();
2120    let mut q = Question::new(
2121        run.id.clone(),
2122        crate::land::APPROVAL_NODE.into(),
2123        "land".into(),
2124        "Merge?".into(),
2125        String::new(),
2126        vec!["merge".into()],
2127    );
2128    let target = crate::merge_decision::Target {
2129        pr: "https://github.com/example/project/pull/42".into(),
2130        head: "old-head".into(),
2131        language: "en".into(),
2132    };
2133    q.merge_target = Some(target.clone());
2134    Questions::at(home.join("questions")).put(&mut q).unwrap();
2135    task.runs.push(run.id.clone());
2136    queue.put(&mut task).unwrap();
2137    let mut inquiry = crate::task_chat::live_record(home, &task, &q);
2138    assert!(approval_target(home, &queue, &inquiry).is_none());
2139    run.status = RunStatus::Merged;
2140    run.pr = Some(crate::run::PrRecord {
2141        url: target.pr.clone(),
2142        number: 42,
2143        state: "merged".into(),
2144        checks: "green".into(),
2145        round: 1,
2146        rounds: 1,
2147        red_at_merge: vec![],
2148    });
2149    run.save_under(home).unwrap();
2150    assert_eq!(
2151        approval_target(home, &queue, &inquiry),
2152        Some(ApprovalEvidence {
2153            target: target.clone(),
2154            terminal: true,
2155            successor: None
2156        })
2157    );
2158    let outbox = crate::task_inquiry::Outbox::at(home);
2159    let id = inquiry.id.clone();
2160    outbox.enqueue(inquiry.clone()).unwrap();
2161    retire_obsolete_with(&queue, home, |_, _| async { None })
2162        .await
2163        .unwrap();
2164    let observed = outbox.get(&id).unwrap().decision.unwrap();
2165    assert_eq!(
2166        observed.attention(false),
2167        crate::task_decision::Attention::ReceiptCheck
2168    );
2169    assert_ne!(observed.status, crate::task_decision::Status::Resolved);
2170    retire_obsolete_with(&queue, home, |_, _| async {
2171        Some(("CLOSED".into(), "old-head".into()))
2172    })
2173    .await
2174    .unwrap();
2175    let closed = outbox.get(&id).unwrap().decision.unwrap();
2176    assert_eq!(
2177        closed.attention(false),
2178        crate::task_decision::Attention::StaleTarget
2179    );
2180    assert!(!closed.source_retired);
2181    retire_obsolete_with(&queue, home, |_, _| async {
2182        Some(("OPEN".into(), "old-head".into()))
2183    })
2184    .await
2185    .unwrap();
2186    let reopened = outbox.get(&id).unwrap().decision.unwrap();
2187    assert_eq!(
2188        reopened.attention(false),
2189        crate::task_decision::Attention::OwnerChoice
2190    );
2191    assert!(!reopened.source_retired);
2192    retire_obsolete_with(&queue, home, |_, _| async {
2193        Some(("OPEN".into(), "new-head".into()))
2194    })
2195    .await
2196    .unwrap();
2197    let observed = outbox.get(&id).unwrap().decision.unwrap();
2198    assert_eq!(
2199        observed.attention(false),
2200        crate::task_decision::Attention::StaleTarget
2201    );
2202    assert_ne!(observed.status, crate::task_decision::Status::Resolved);
2203    let claim = outbox.execution_claim(&id).unwrap();
2204    retire_obsolete_with(&queue, home, |_, _| async {
2205        Some(("MERGED".into(), "new-head".into()))
2206    })
2207    .await
2208    .unwrap();
2209    assert_eq!(outbox.get(&id).unwrap().decision.unwrap(), observed);
2210    drop(claim);
2211    let question_lock = home.join("questions").join(format!("{id}.lock"));
2212    let leftover = std::fs::File::create(&question_lock).unwrap();
2213    retire_obsolete_with(&queue, home, |_, _| async {
2214        Some(("MERGED".into(), "new-head".into()))
2215    })
2216    .await
2217    .unwrap();
2218    assert_eq!(outbox.get(&id).unwrap().decision.unwrap(), observed);
2219    leftover
2220        .set_modified(std::time::SystemTime::now() - std::time::Duration::from_secs(60))
2221        .unwrap();
2222    drop(leftover);
2223    retire_obsolete_with(&Queue::at(home.join("queue")), home, |_, _| async {
2224        Some(("MERGED".into(), "new-head".into()))
2225    })
2226    .await
2227    .unwrap();
2228    let retired = outbox.get(&id).unwrap().decision.unwrap();
2229    assert_eq!(
2230        retired.closure,
2231        Some(crate::task_decision::Closure::Obsolete)
2232    );
2233    assert!(retired.source_retired);
2234    assert!(!question_lock.exists());
2235    assert!(
2236        Questions::at(home.join("questions"))
2237            .read_history(&q.id)
2238            .unwrap()
2239            .answer
2240            .is_none()
2241    );
2242    let questions = crate::ask::Questions::at(home.join("questions"));
2243    assert!(
2244        questions
2245            .update(&q.id, |q| q
2246                .answer(crate::ask::Answer::Choice("merge".into())))
2247            .is_err()
2248    );
2249    retire_obsolete_with(&queue, home, |_, _| async {
2250        panic!("resolved inquiry was queried again")
2251    })
2252    .await
2253    .unwrap();
2254    assert_eq!(outbox.get(&id).unwrap().decision.unwrap(), retired);
2255    inquiry
2256        .decision
2257        .as_mut()
2258        .unwrap()
2259        .accept("decision: merge")
2260        .unwrap();
2261    assert_eq!(
2262        approval_target(home, &queue, &inquiry),
2263        Some(ApprovalEvidence {
2264            target: target.clone(),
2265            terminal: false,
2266            successor: None
2267        })
2268    );
2269    let replacement = ApprovalEvidence {
2270        target: target.clone(),
2271        terminal: false,
2272        successor: Some(("successor".into(), "new-head".into())),
2273    };
2274    assert!(replacement.obsolete_reason("OPEN", "other-head").is_none());
2275    assert!(replacement.obsolete_reason("UNKNOWN", "new-head").is_none());
2276    assert!(
2277        replacement
2278            .obsolete_reason("OPEN", "new-head")
2279            .unwrap()
2280            .contains("successor")
2281    );
2282    // A finite high-water pass shares the same PR observation and resumes
2283    // from disk. One accepted effect and one missing target stay unresolved.
2284    let mut legacy = None;
2285    for index in 0..34 {
2286        let mut source = q.clone();
2287        source.id = format!("approval-{index:02}");
2288        if index == 1 {
2289            source
2290                .answer(crate::ask::Answer::Choice("merge".into()))
2291                .unwrap();
2292            legacy = Some(source.id.clone());
2293        }
2294        if index == 33 {
2295            source.merge_target = None;
2296        }
2297        questions.put(&mut source).unwrap();
2298        let mut record = crate::task_chat::live_record(home, &task, &source);
2299        if index == 0 {
2300            record
2301                .decision
2302                .as_mut()
2303                .unwrap()
2304                .accept("decision: merge")
2305                .unwrap();
2306        }
2307        if index == 1 {
2308            record
2309                .decision
2310                .as_mut()
2311                .unwrap()
2312                .fail("historical response has no receipt")
2313                .unwrap();
2314        }
2315        outbox.enqueue(record).unwrap();
2316    }
2317    let journal = home.join("notifications/task-chat-migration-v1");
2318    std::fs::create_dir_all(&journal).unwrap();
2319    std::fs::write(
2320        journal.join("state.json"),
2321        serde_json::to_vec(&serde_json::json!({
2322            "schema": 1, "pending": [], "sources": [legacy.unwrap()]
2323        }))
2324        .unwrap(),
2325    )
2326    .unwrap();
2327    let calls = std::cell::Cell::new(0);
2328    let observe = |_, _| {
2329        calls.set(calls.get() + 1);
2330        async { Some(("MERGED".into(), "old-head".into())) }
2331    };
2332    retire_obsolete_with(&queue, home, observe).await.unwrap();
2333    assert_eq!(calls.get(), 1);
2334    assert_eq!(
2335        outbox
2336            .list_readable()
2337            .unwrap()
2338            .0
2339            .iter()
2340            .filter(|i| i
2341                .decision
2342                .as_ref()
2343                .is_some_and(|d| d.status != crate::task_decision::Status::Resolved))
2344            .count(),
2345        3
2346    );
2347    retire_obsolete_with(&Queue::at(home.join("queue")), home, observe)
2348        .await
2349        .unwrap();
2350    assert_eq!(calls.get(), 2);
2351    let pending = outbox
2352        .list_readable()
2353        .unwrap()
2354        .0
2355        .into_iter()
2356        .filter(|i| {
2357            i.decision
2358                .as_ref()
2359                .is_some_and(|d| d.status != crate::task_decision::Status::Resolved)
2360        })
2361        .map(|i| i.id)
2362        .collect::<std::collections::BTreeSet<_>>();
2363    assert_eq!(
2364        pending,
2365        ["approval-00".into(), "approval-33".into()]
2366            .into_iter()
2367            .collect()
2368    );
2369    let legacy = questions.read_history("approval-01").unwrap();
2370    assert_eq!(legacy.resolution().as_deref(), Some("merge"));
2371    assert!(questions.held_reply("approval-01"));
2372    assert_eq!(
2373        outbox.get("approval-01").unwrap().decision.unwrap().closure,
2374        Some(crate::task_decision::Closure::Obsolete)
2375    );
2376}
2377
2378/// Repair the decision projection from independently durable command receipts.
2379/// This starts no workers and retries no operation.
2380pub fn reconcile_decisions(queue: &Queue, home: &Path) -> Result<()> {
2381    let outbox = crate::task_inquiry::Outbox::at(home);
2382    let (inquiries, unreadable) = outbox.list_readable()?;
2383    let mut errors = Vec::new();
2384    if unreadable != 0 {
2385        errors.push(format!("{unreadable} unreadable inquiry record(s)"));
2386    }
2387    for inquiry in inquiries {
2388        let id = inquiry.id.clone();
2389        let task_id = inquiry.task.clone();
2390        let before = inquiry.decision.clone();
2391        if let Err(error) = reconcile_inquiry(queue, home, &outbox, inquiry) {
2392            let message = format!(
2393                "Decision receipt reconciliation failed: {error:#}. Inspect this inquiry's receipt before retrying."
2394            );
2395            tracing::warn!("decision {id}: {message}");
2396            // Reacquire the consumer fence and compare the entire lifecycle:
2397            // an intervening retry, receipt or settlement owns its new state.
2398            if let Ok(_execution) = outbox.execution_claim(&id)
2399                && let Ok(_claim) = queue.claim(&task_id)
2400                && let Err(error) = outbox.try_update_decision(&id, |d| {
2401                    if before.as_ref() != Some(d)
2402                        || d.status == crate::task_decision::Status::Resolved
2403                    {
2404                        return Ok(false);
2405                    }
2406                    if d.retry_safe {
2407                        return d.fail_before_effect(&message);
2408                    }
2409                    d.fail(&message)
2410                })
2411            {
2412                tracing::warn!(
2413                    "decision {id} reconciliation error persistence deferred: {error:#}"
2414                );
2415            }
2416            errors.push(format!("{id}: {message}"));
2417        }
2418    }
2419    ensure!(
2420        errors.is_empty(),
2421        "{} decision reconciliation problem(s): {}",
2422        errors.len(),
2423        errors.join("; ")
2424    );
2425    Ok(())
2426}
2427
2428fn reconcile_inquiry(
2429    queue: &Queue,
2430    home: &Path,
2431    outbox: &crate::task_inquiry::Outbox,
2432    inquiry: crate::task_inquiry::Inquiry,
2433) -> Result<()> {
2434    use crate::task_decision::Status;
2435    let Some(decision) = inquiry.decision else {
2436        return Ok(());
2437    };
2438    if decision.status == Status::Resolved {
2439        return Ok(());
2440    }
2441    let Some(request) = decision.request else {
2442        return Ok(());
2443    };
2444    let Ok(command) = serde_json::from_str::<Operation>(&request) else {
2445        return Ok(());
2446    };
2447    if let Operation::Resume { run } = &command {
2448        return reconcile_resume_decision(queue, home, outbox, &inquiry.id, run);
2449    }
2450    let Ok(_execution) = outbox.execution_claim(&inquiry.id) else {
2451        return Ok(());
2452    };
2453    let Ok(_claim) = queue.claim(&inquiry.task) else {
2454        return Ok(());
2455    };
2456    let current = outbox.get(&inquiry.id)?;
2457    let Some(decision) = current.decision else {
2458        return Ok(());
2459    };
2460    if decision.status == Status::Resolved || decision.request.as_ref() != Some(&request) {
2461        return Ok(());
2462    }
2463    let task = queue.get(&inquiry.task)?;
2464    ensure!(task.repo == inquiry.repo, "decision repository changed");
2465    if let Some(receipt) = task.decision_effects.get(&inquiry.id) {
2466        ensure!(
2467            receipt == &request,
2468            "decision receipt binds another command"
2469        );
2470        outbox.update_decision(&inquiry.id, |d| {
2471            d.applied("exact task command receipt confirmed after restart")
2472        })?;
2473        return Ok(());
2474    }
2475    let mut pending_external = false;
2476    let receipt = match command {
2477        Operation::Abandon { run } => {
2478            abandonment_receipt(home, &task, &inquiry.id, &run, &request)?
2479                .then(|| format!("run {run}: exact abandonment receipt committed"))
2480        }
2481        Operation::RerunChecks {
2482            request,
2483            run,
2484            head,
2485            workflows,
2486        } => {
2487            let chat = inquiry.delivered_to.as_deref().unwrap_or_default();
2488            let path = home
2489                .join("chat-controls")
2490                .join(chat)
2491                .join(format!("{request}.json"));
2492            let state = crate::run::RunState::load_under(&run, home)?;
2493            let action = serde_json::json!({
2494                "run": run, "repo": state.repo,
2495                "pr": state.pr.as_ref().map(|pr| pr.url.as_str()),
2496                "head": head, "runs": workflows,
2497            });
2498            std::fs::read(path)
2499                .ok()
2500                .and_then(|bytes| serde_json::from_slice::<serde_json::Value>(&bytes).ok())
2501                .filter(|receipt| receipt["status"] == "applied" && receipt["action"] == action)
2502                .map(|_| format!("chat-controls/{chat}/{request}.json: applied"))
2503        }
2504        Operation::MergePr {
2505            repo,
2506            number,
2507            head,
2508            request,
2509        } => {
2510            let action = crate::chat_merge::Request {
2511                repo,
2512                number,
2513                head,
2514                request,
2515            };
2516            let chat = inquiry
2517                .delivered_to
2518                .as_deref()
2519                .context("merge decision has no chat")?;
2520            let receipt = merge_receipt(home, chat, &action)?;
2521            pending_external = receipt
2522                .as_ref()
2523                .is_some_and(|receipt| receipt["status"] == "pending");
2524            if let Some(receipt) = &receipt
2525                && receipt["status"] != "merged"
2526                && receipt["status"] != "pending"
2527            {
2528                outbox.update_decision(&inquiry.id, |d| d.fail(&format!("Merge outcome requires reconciliation: {}. Reuse the same request ID to check only.", receipt["detail"])))?;
2529            }
2530            receipt
2531                .filter(|receipt| receipt["status"] == "merged")
2532                .map(|receipt| format!("confirmed merge receipt: {}", receipt["detail"]))
2533        }
2534        _ => None,
2535    };
2536    if let Some(receipt) = receipt {
2537        outbox.update_decision(&inquiry.id, |d| d.applied(&receipt))?;
2538    } else if decision.status == Status::InProgress
2539        && !pending_external
2540        && outbox
2541            .get(&inquiry.id)?
2542            .decision
2543            .as_ref()
2544            .is_some_and(|d| d.status == Status::InProgress)
2545    {
2546        let talks = Talks::at(home.join("talks"));
2547        let chat = inquiry
2548            .delivered_to
2549            .as_deref()
2550            .context("executing decision has no chat")?;
2551        if !talks.turn_held(chat) && !crate::chat_worker::turn_worker_active(&talks, chat) {
2552            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."))?;
2553        }
2554    }
2555    Ok(())
2556}
2557
2558/// Record the owner's choice for a decision from an open standing chat. The
2559/// chat agent interprets the owner's request directly, a merge included; no
2560/// quote, consent phrase or task ownership is required. See [`record_decision`].
2561pub fn decide(
2562    talks: &Talks,
2563    home: &Path,
2564    talk: &str,
2565    question: &str,
2566    choice: &str,
2567) -> Result<crate::ask::Question> {
2568    authorize(talks, talk, crate::queue::CHAT_NODE)?;
2569    record_decision(home, question, choice, None)
2570}
2571
2572/// Answer an open decision whose answer the machinery consumes
2573/// ([`crate::task_chat::awaits_decision`]: a merge or release approval, the
2574/// posting gate, triage, a divergence reconcile, a structured choice action).
2575/// The question must still be open and `choice` one of its offered choices;
2576/// the consumer behind it keeps its own state and transition checks.
2577fn record_decision(
2578    home: &Path,
2579    question: &str,
2580    choice: &str,
2581    title: Option<&str>,
2582) -> Result<crate::ask::Question> {
2583    use crate::ask::{Answer, Questions};
2584    let questions = Questions::at(home.join("questions"));
2585    let id = questions.resolve_id(question)?;
2586    let q = questions.get(&id)?;
2587    let queue = Queue::at(home.join("queue"));
2588    let _claims = decision_claims(&queue, &q)?;
2589    for task in queue.list() {
2590        if q.run == task.id
2591            || task.runs.contains(&q.run)
2592            || q.routed_task.as_deref() == Some(&task.id)
2593        {
2594            ensure!(
2595                !task.stale_question(&q),
2596                "question predates task repository reassignment; inspect the current task and release it for fresh execution"
2597            );
2598        }
2599    }
2600    ensure!(
2601        crate::task_chat::awaits_decision(&q),
2602        "question {} is not a decision the machinery waits on; answer it with `magi answer`",
2603        q.short()
2604    );
2605    let (q, ()) = questions.update(&q.id, |r| {
2606        if crate::task_chat::saved_reply_requires_confirmation(home, r) {
2607            ensure!(
2608                crate::task_inquiry::Outbox::at(home)
2609                    .get(&r.id)?
2610                    .decision
2611                    .is_some_and(
2612                        |decision| decision.status != crate::task_decision::Status::Resolved
2613                    ),
2614                "saved decision is settled; no effect remains necessary"
2615            );
2616            r.status = crate::ask::QuestionStatus::Open;
2617            r.answer = None;
2618            r.answered_at = None;
2619            r.answer_authority = None;
2620        }
2621        ensure!(
2622            r.status.open(),
2623            "question {} is already {}",
2624            r.short(),
2625            r.status.as_str()
2626        );
2627        let reply = r.resolve_reply(choice)?.to_owned();
2628        ensure!(
2629            crate::land::approval(Some(&reply)) != crate::land::Approval::Merge || r.merge_target.is_some()
2630                || !(r.node == crate::land::APPROVAL_NODE || (r.node == crate::bump::NOTICE_NODE && r.seat == "release-watch")),
2631            "approval has no recorded PR/head; recover its target or discuss a non-merge operation in chat"
2632        );
2633        let replacement =
2634            r.node == crate::github_text::ASK_NODE && reply == crate::github_text::USE_MY_TEXT;
2635        ensure!(
2636            replacement || title.is_none(),
2637            "--title is only valid for a publication decision's `use my text` choice"
2638        );
2639        let title = if replacement {
2640            let title =
2641                title.context("use my text needs --title with the literal replacement title")?;
2642            ensure!(
2643                !title.trim().is_empty(),
2644                "replacement title must not be empty"
2645            );
2646            Some(title.to_owned())
2647        } else {
2648            None
2649        };
2650        let answer = if r.free_text() {
2651            Answer::Text(reply)
2652        } else {
2653            Answer::Choice(reply)
2654        };
2655        r.publication_title = title;
2656        r.answer(answer)?;
2657        Ok(())
2658    })?;
2659    Ok(q)
2660}
2661
2662/// Fence idle built-in triage answers with grant admission and worker writes.
2663/// Live drivers must remain answerable (grant admission refuses them). Other
2664/// question consumers keep their own claims, including synchronous dismissal.
2665/// Every grant also rechecks answered-but-unsettled effects before acceptance.
2666pub(crate) fn decision_claims(
2667    queue: &Queue,
2668    q: &crate::ask::Question,
2669) -> Result<Vec<crate::queue::Claim>> {
2670    let mut owners: Vec<_> = queue
2671        .list()
2672        .into_iter()
2673        .filter(|task| {
2674            q.run == task.id
2675                || task.runs.contains(&q.run)
2676                || q.routed_task.as_deref() == Some(&task.id)
2677        })
2678        .map(|task| task.id)
2679        .collect();
2680    owners.sort();
2681    let mut claims = Vec::new();
2682    if matches!(
2683        q.node.as_str(),
2684        crate::triage::NODE | crate::triage::DEPS_NODE
2685    ) {
2686        for id in &owners {
2687            if queue.get(id)?.status != TaskStatus::Running {
2688                claims.push(queue.claim(id)?);
2689            }
2690        }
2691    }
2692    for id in owners {
2693        ensure!(
2694            !crate::repair_budget::reconcile::superseded_question(&queue.get(&id)?, q),
2695            "question was superseded by explicit repair receipt recovery; inspect the reconciliation receipt"
2696        );
2697    }
2698    Ok(claims)
2699}
2700
2701/// The conversation this process speaks for, or why it may not act.
2702pub fn authorize(talks: &Talks, run: &str, node: &str) -> Result<Talk> {
2703    if node != crate::queue::CHAT_NODE || run.trim().is_empty() {
2704        bail!("task control requires MAGI_NODE=chat and MAGI_RUN from a standing chat");
2705    }
2706    let talk = talks.get(run)?;
2707    if talk.id != run || !talk.status.open() {
2708        bail!("task control requires the exact id of an open conversation");
2709    }
2710    Ok(talk)
2711}
2712
2713/// The task that recorded `run` (a full run id).
2714fn run_task(queue: &Queue, run: &str) -> Result<Task> {
2715    ensure!(
2716        crate::run::is_run_id(run),
2717        "an execution command needs the full run id"
2718    );
2719    queue
2720        .list()
2721        .into_iter()
2722        .find(|t| t.runs.iter().any(|r| r == run))
2723        .with_context(|| format!("run {run} belongs to no task"))
2724}
2725
2726/// Claim a task from a full or unambiguous-prefix id and read it under the
2727/// claim, never from a lookup made before it.
2728fn claimed(queue: &Queue, reference: &str) -> Result<(crate::queue::Claim, Task)> {
2729    let id = queue.resolve_id(reference)?;
2730    let claim = queue
2731        .claim(&id)
2732        .with_context(|| format!("task {id} is claimed by a running daemon"))?;
2733    let task = queue.get(&id)?;
2734    Ok((claim, task))
2735}
2736
2737fn claimed_for_chat(
2738    queue: &Queue,
2739    reference: &str,
2740    talks: &Talks,
2741    chat: &str,
2742) -> Result<(crate::queue::Claim, Task)> {
2743    let claimed = claimed(queue, reference)?;
2744    if let crate::chat_goal::Source::Goal { id, generation } = crate::chat_goal::current_source() {
2745        let talk = talks.get(chat)?;
2746        let goal = talk
2747            .goals
2748            .iter()
2749            .find(|goal| goal.id == id)
2750            .context("unknown goal")?;
2751        goal.admit(generation)?;
2752        let task = &claimed.1;
2753        ensure!(
2754            goal.tasks.contains(&task.id),
2755            "effect targets a task outside this goal"
2756        );
2757        crate::chat_goal::require_repo(
2758            "task",
2759            &task.id,
2760            &task.repo,
2761            goal.effective_repo(&talk.repo),
2762        )?;
2763    }
2764    Ok(claimed)
2765}
2766
2767fn check_hold_release(task: &Task, operation: &str) -> Result<()> {
2768    match task.status {
2769        TaskStatus::Queued
2770        | TaskStatus::Held
2771        | TaskStatus::Failed
2772        | TaskStatus::Blocked
2773        | TaskStatus::Parked => Ok(()),
2774        TaskStatus::Done => bail!(
2775            "cannot {operation} task {} (done): completed work must not be restarted; create a new task instead",
2776            task.id
2777        ),
2778        TaskStatus::Running => bail!(
2779            "cannot {operation} task {} (running): its run may still be active; use resume or abandon for the existing run instead",
2780            task.id
2781        ),
2782    }
2783}
2784
2785/// Mark a task complete as a terminal caller, using the audited close transition.
2786pub async fn done(
2787    queue: &Queue,
2788    home: &Path,
2789    reference: &str,
2790    reason: Option<String>,
2791    discard: bool,
2792) -> Result<Task> {
2793    crate::task_completion::close(
2794        queue,
2795        home,
2796        reference,
2797        crate::queue::CompletionActor::Cli,
2798        reason,
2799        discard,
2800    )
2801    .await
2802}
2803
2804/// Change priority under the same claim and state check as the terminal route.
2805pub fn set_priority(queue: &Queue, reference: &str, priority: i32) -> Result<Task> {
2806    priority_claimed(queue, claimed(queue, reference)?, priority)
2807}
2808
2809fn priority_claimed(
2810    queue: &Queue,
2811    (_claim, mut task): (crate::queue::Claim, Task),
2812    priority: i32,
2813) -> Result<Task> {
2814    task.set_priority(priority)?;
2815    queue.put(&mut task)?;
2816    Ok(task)
2817}
2818
2819/// Hold a task for the owner.
2820pub fn hold(queue: &Queue, reference: &str, reason: &str) -> Result<Task> {
2821    hold_claimed(queue, claimed(queue, reference)?, reason)
2822}
2823
2824fn hold_claimed(
2825    queue: &Queue,
2826    (_claim, mut task): (crate::queue::Claim, Task),
2827    reason: &str,
2828) -> Result<Task> {
2829    check_hold_release(&task, "hold")?;
2830    let reason = reason.trim();
2831    task.hold_manual((!reason.is_empty()).then(|| reason.to_owned()));
2832    queue.put(&mut task)?;
2833    Ok(task)
2834}
2835
2836/// Release a task (the same transition as `magi task release`: the attempt
2837/// count restarts, the history stays). An operator hold is released too: the
2838/// owner asked for it.
2839pub fn release(queue: &Queue, reference: &str) -> Result<Task> {
2840    release_claimed(queue, claimed(queue, reference)?)
2841}
2842
2843fn release_claimed(queue: &Queue, (_claim, mut task): (crate::queue::Claim, Task)) -> Result<Task> {
2844    check_hold_release(&task, "release")?;
2845    crate::base_sync_recovery::ensure_generic_release(queue, &task)?;
2846    let run = task.execution_runs().last().cloned();
2847    let preserved = match run {
2848        Some(run) => crate::repair_budget::queue_resumption(queue, &mut task, &run)?,
2849        None => false,
2850    };
2851    if !preserved {
2852        task.release_operator("chat", None);
2853    }
2854    queue.put(&mut task)?;
2855    Ok(task)
2856}
2857
2858/// Change a queued or held task's instruction and queue it again, in one
2859/// save under one claim. Only what [`Task::edit`] allows can be retried; the
2860/// attempt count follows [`Task::release`] (restarts), while runs, passes and
2861/// the resumption history are kept.
2862pub fn retry(
2863    queue: &Queue,
2864    reference: &str,
2865    title: Option<String>,
2866    instruction: &str,
2867) -> Result<Task> {
2868    retry_claimed(queue, claimed(queue, reference)?, title, instruction)
2869}
2870
2871fn retry_claimed(
2872    queue: &Queue,
2873    (_claim, mut task): (crate::queue::Claim, Task),
2874    title: Option<String>,
2875    instruction: &str,
2876) -> Result<Task> {
2877    ensure!(
2878        !instruction.trim().is_empty(),
2879        "the new instruction is empty"
2880    );
2881    if let Some(state) = crate::base_sync_recovery::held_run(queue, &task)
2882        && state
2883            .base_sync_recovery
2884            .stop
2885            .as_ref()
2886            .is_some_and(|stop| stop.kind == crate::base_sync_recovery::StopKind::Conflict)
2887    {
2888        anyhow::bail!(
2889            "retry cannot authorize editing a retained base-sync stop. {}",
2890            state.base_sync_next_action()
2891        );
2892    }
2893    crate::base_sync_recovery::ensure_generic_release(queue, &task)?;
2894    let title = title.unwrap_or_else(|| crate::queue::title_from(instruction, 72));
2895    task.edit(title, instruction.to_owned())?;
2896    task.release_operator("chat", None);
2897    queue.put(&mut task)?;
2898    Ok(task)
2899}
2900
2901/// Resume a stopped, blocked or parked run (its task's latest). Only queues
2902/// the pinned resume; returns the owning task.
2903pub fn resume(queue: &Queue, home: &Path, run: &str) -> Result<Task> {
2904    let task = run_task(queue, run)?;
2905    ensure!(
2906        task.execution_runs().last().map(String::as_str) == Some(run),
2907        "only the task's latest run can be resumed"
2908    );
2909    crate::resume::validate(home, run)?;
2910    ensure!(
2911        crate::resume::pin_queued(queue, run, None, None)?,
2912        "no queued task owns run {run}"
2913    );
2914    queue.get(&task.id)
2915}
2916
2917// These reads and input checks cannot start an effect. Keep them shared by
2918// decision acceptance and execution so invalid input never pins a new request.
2919fn rerun_preflight(
2920    queue: &Queue,
2921    home: &Path,
2922    run: &str,
2923    request: &str,
2924) -> Result<crate::run::RunState> {
2925    run_task(queue, run)?;
2926    let state = crate::run::RunState::load_under(run, home)?;
2927    ensure!(state.pr.is_some(), "the run recorded no pull request");
2928    ensure!(
2929        crate::ask::valid_asset_name(request),
2930        "request must be a safe filename of at most 64 bytes"
2931    );
2932    Ok(state)
2933}
2934
2935/// チャットのリクエスト単位で受付記録を残し、共通遷移でチェックを再実行する。
2936pub async fn rerun_checks(
2937    queue: &Queue,
2938    home: &Path,
2939    talk: &str,
2940    run: &str,
2941    request: &str,
2942    head: &str,
2943    workflows: &[String],
2944) -> Result<Vec<String>> {
2945    let state = rerun_preflight(queue, home, run, request).map_err(BeforeEffect)?;
2946    let dir = home.join("chat-controls").join(talk);
2947    std::fs::create_dir_all(&dir)?;
2948    let lock = std::fs::OpenOptions::new()
2949        .create(true)
2950        .truncate(false)
2951        .write(true)
2952        .open(dir.join(format!("{request}.lock")))?;
2953    crate::pr_head::try_lock_file(&lock).map_err(|error| BeforeEffect(error.into()))?;
2954    let path = dir.join(format!("{request}.json"));
2955    let pr = &state
2956        .pr
2957        .as_ref()
2958        .context("the run recorded no pull request")?
2959        .url;
2960    let action = serde_json::json!({
2961        "run": run, "repo": state.repo, "pr": pr, "head": head, "runs": workflows
2962    });
2963    if path.exists() {
2964        let prior: serde_json::Value = serde_json::from_slice(&std::fs::read(&path)?)?;
2965        if prior["action"] != action {
2966            return Err(BeforeEffect(anyhow::anyhow!(
2967                "request ID already binds a different operation"
2968            ))
2969            .into());
2970        }
2971        ensure!(
2972            prior["status"] == "applied",
2973            "previous request has an uncertain result; inspect its receipt before a new request"
2974        );
2975        return Ok(workflows.to_vec());
2976    }
2977    let record = |status: &str| -> Result<()> {
2978        let tmp = path.with_extension("tmp");
2979        std::fs::write(
2980            &tmp,
2981            serde_json::to_vec(&serde_json::json!({
2982                "action": action, "status": status
2983            }))?,
2984        )?;
2985        std::fs::rename(tmp, &path)?;
2986        Ok(())
2987    };
2988    let operation = format!("chat:{talk}:{request}");
2989    let started = std::sync::atomic::AtomicBool::new(false);
2990    crate::daemon::rerun_checks_once(home, &operation, &state.repo, pr, head, workflows, || {
2991        // Once a receipt exists, failure must remain uncertain even if the
2992        // external command has not returned yet.
2993        started.store(true, std::sync::atomic::Ordering::SeqCst);
2994        record("started")
2995    })
2996    .await
2997    .map_err(|error| {
2998        if started.load(std::sync::atomic::Ordering::SeqCst) {
2999            error
3000        } else {
3001            anyhow::Error::new(BeforeEffect(error))
3002        }
3003    })?;
3004    record("applied")?;
3005    Ok(workflows.to_vec())
3006}
3007
3008/// Abandon a recorded run whose driver is proven gone. No confirmation phrase
3009/// is needed; an unknown or live driver is refused by
3010/// [`crate::driver::abandon_proven_dead`], so a working driver is never broken.
3011pub fn abandon(queue: &Queue, home: &Path, run: &str) -> Result<()> {
3012    run_task(queue, run)?;
3013    crate::driver::abandon_proven_dead(home, run)
3014}
3015
3016/// One line a person or agent can read after a successful command.
3017pub fn describe(task: &Task, what: &str) -> String {
3018    let status = match task.status {
3019        TaskStatus::Queued => "queued",
3020        _ => task.status.as_str(),
3021    };
3022    format!("{what} {} {} ({status})", task.short(), task.title)
3023}
3024
3025#[cfg(test)]
3026mod tests {
3027    use super::*;
3028    use crate::queue::Source;
3029    use jiff::Timestamp;
3030
3031    fn talk(talks: &Talks, id: &str) -> Talk {
3032        let mut t: Talk = serde_json::from_value(serde_json::json!({
3033            "schema":1,"id":id,"repo":".","agent":"worker","status":"open","turns":[],
3034            "created_at":Timestamp::now(),"updated_at":Timestamp::now(),
3035            "seat":crate::agent::SeatState::new("talk","worker",1)
3036        }))
3037        .unwrap();
3038        talks.put(&mut t).unwrap();
3039        t
3040    }
3041
3042    fn filed(queue: &Queue, talk: &str, text: &str) -> Task {
3043        let mut t = Task::new(
3044            text.into(),
3045            text.into(),
3046            ".".into(),
3047            Source::Agent {
3048                run: talk.into(),
3049                node: crate::queue::CHAT_NODE.into(),
3050            },
3051        );
3052        queue.put(&mut t).unwrap();
3053        t
3054    }
3055
3056    #[tokio::test]
3057    async fn direct_chat_completion_supersedes_the_earlier_blocked_run() {
3058        use crate::run::{RunState, RunStatus};
3059
3060        let dir = tempfile::tempdir().unwrap();
3061        let home = dir.path();
3062        let talks = Talks::at(home.join("talks"));
3063        let queue = Queue::at(home.join("queue"));
3064        let talk = talk(&talks, "talk-a");
3065        let mut task = filed(&queue, &talk.id, "deliver");
3066        for status in [RunStatus::Blocked, RunStatus::Merged] {
3067            let mut run = RunState::new(
3068                task.repo.clone(),
3069                "main".into(),
3070                "base".into(),
3071                task.instruction.clone(),
3072                crate::config::Config::default(),
3073            );
3074            run.status = status;
3075            if status == RunStatus::Merged {
3076                run.merge = Some(crate::run::MergeOutcome {
3077                    mode: crate::config::MergeMode::Pr,
3078                    ok: true,
3079                    detail: "merged".into(),
3080                    empty: false,
3081                });
3082            }
3083            run.driver_exited = true;
3084            run.reserve_under(home).unwrap();
3085            task.link_run(&run.id);
3086        }
3087        queue.put(&mut task).unwrap();
3088        execute(
3089            &queue,
3090            home,
3091            &talks,
3092            &talk.id,
3093            Operation::Done {
3094                task: task.id.clone(),
3095                reason: None,
3096                result: None,
3097                discard: false,
3098            },
3099        )
3100        .await
3101        .unwrap();
3102        assert_eq!(
3103            RunState::load_under(&task.runs[0], home).unwrap().status,
3104            RunStatus::Superseded
3105        );
3106    }
3107
3108    #[test]
3109    fn ownerless_import_reconciliation_requires_effect_evidence_not_saved_consent() {
3110        use crate::ask::{Answer, Question, Questions};
3111        let home = tempfile::tempdir().unwrap();
3112        let home = home.path();
3113        let queue = Queue::at(home.join("queue"));
3114        let talks = Talks::at(home.join("talks"));
3115        let questions = Questions::at(home.join("questions"));
3116        let mut q = Question::new(
3117            String::new(),
3118            crate::bump::NOTICE_NODE.into(),
3119            "release-watch".into(),
3120            "Historical release hold".into(),
3121            String::new(),
3122            vec!["hold".into()],
3123        );
3124        q.answer(Answer::Choice("hold".into())).unwrap();
3125        q.answer_delivered = true;
3126        questions.put(&mut q).unwrap();
3127        let source = std::fs::read(questions.path_of(&q.id)).unwrap();
3128        crate::task_chat::sweep(&queue, &talks, &questions, home);
3129        assert!(reconcile_task_decision(&queue, home, "authorized-chat", &q.id).is_err());
3130        let outbox = crate::task_inquiry::Outbox::at(home);
3131        assert_eq!(
3132            outbox.get(&q.id).unwrap().decision.unwrap().status,
3133            crate::task_decision::Status::RetryNeeded
3134        );
3135        let dir = home.join("release-watch-receipts");
3136        std::fs::create_dir_all(&dir).unwrap();
3137        std::fs::write(
3138            dir.join(format!("{}.json", q.id)),
3139            serde_json::to_vec(&crate::release_watch::WatchState {
3140                applied: vec![q.id.clone()],
3141                ..Default::default()
3142            })
3143            .unwrap(),
3144        )
3145        .unwrap();
3146        for _ in 0..2 {
3147            reconcile_task_decision(&queue, home, "authorized-chat", &q.id).unwrap();
3148        }
3149        let decision = outbox.get(&q.id).unwrap().decision.unwrap();
3150        assert_eq!(decision.status, crate::task_decision::Status::Resolved);
3151        assert!(decision.request.is_none());
3152        assert!(decision.source_answer_at.is_none());
3153        assert_eq!(std::fs::read(questions.path_of(&q.id)).unwrap(), source);
3154        assert!(queue.list().is_empty());
3155        assert!(talks.list().is_empty());
3156    }
3157
3158    #[test]
3159    fn receipt_reconciliation_error_is_visible_after_restart() {
3160        use crate::task_decision::{Attention, Status};
3161        let tmp = tempfile::tempdir().unwrap();
3162        let home = tmp.path();
3163        let queue = Queue::at(home.join("queue"));
3164        let task = filed(&queue, "talk-a", "work");
3165        let outbox = crate::task_inquiry::Outbox::at(home);
3166        let inquiry = outbox
3167            .file(&task, None, "merge".into(), "Merge?", "")
3168            .unwrap();
3169        let request = serde_json::to_string(&Operation::MergePr {
3170            repo: "example/project".into(),
3171            number: 42,
3172            head: "head".into(),
3173            request: "request-a".into(),
3174        })
3175        .unwrap();
3176        outbox
3177            .update_decision(&inquiry.id, |d| {
3178                d.accept(&request)?;
3179                d.start()
3180            })
3181            .unwrap();
3182        // No delivered chat: receipt ownership cannot be established.
3183        assert!(reconcile_decisions(&queue, home).is_err());
3184        let failed = outbox.get(&inquiry.id).unwrap().decision.unwrap();
3185        assert_eq!(failed.status, Status::RetryNeeded);
3186        assert_eq!(failed.attention(false), Attention::ReceiptCheck);
3187        assert!(
3188            failed
3189                .error
3190                .as_deref()
3191                .unwrap()
3192                .contains("merge decision has no chat")
3193        );
3194        assert_eq!(failed.request.as_deref(), Some(request.as_str()));
3195        assert!(!failed.retry_safe);
3196        assert!(reconcile_decisions(&queue, home).is_err());
3197        assert_eq!(outbox.get(&inquiry.id).unwrap().decision.unwrap(), failed);
3198    }
3199
3200    #[test]
3201    fn resume_recovery_waits_for_the_inquiry_publisher() {
3202        let tmp = tempfile::tempdir().unwrap();
3203        let queue = Queue::at(tmp.path().join("queue"));
3204        let mut task = filed(&queue, "talk-a", "work");
3205        let mut state = crate::run::RunState::new(
3206            task.repo.clone(),
3207            "main".into(),
3208            "base".into(),
3209            "work".into(),
3210            crate::config::Config::default(),
3211        );
3212        state.status = crate::run::RunStatus::Blocked;
3213        state.driver_exited = true;
3214        state.save_under(tmp.path()).unwrap();
3215        task.runs.push(state.id.clone());
3216        queue.put(&mut task).unwrap();
3217        let outbox = crate::task_inquiry::Outbox::at(tmp.path());
3218        let inquiry = outbox
3219            .file(
3220                &task,
3221                Some(state.id.clone()),
3222                "resume".into(),
3223                "Resume?",
3224                "",
3225            )
3226            .unwrap();
3227        let request = serde_json::to_string(&Operation::Resume {
3228            run: state.id.clone(),
3229        })
3230        .unwrap();
3231        outbox
3232            .update_decision(&inquiry.id, |d| {
3233                d.accept(&request)?;
3234                d.start()
3235            })
3236            .unwrap();
3237        let before = outbox.get(&inquiry.id).unwrap().decision.unwrap();
3238        let publisher = outbox.execution_claim(&inquiry.id).unwrap();
3239        reconcile_decisions(&queue, tmp.path()).unwrap();
3240        assert_eq!(outbox.get(&inquiry.id).unwrap().decision.unwrap(), before);
3241        drop(publisher);
3242        reconcile_decisions(&queue, tmp.path()).unwrap();
3243        let recovered = outbox.get(&inquiry.id).unwrap().decision.unwrap();
3244        assert_eq!(recovered.status, crate::task_decision::Status::RetryNeeded);
3245        assert!(recovered.retry_safe);
3246    }
3247
3248    #[tokio::test]
3249    async fn resume_receipt_matches_checkout_root_not_filing_directory() {
3250        use crate::task_decision::Status;
3251        let tmp = tempfile::tempdir().unwrap();
3252        let home = tmp.path();
3253        let repo = home.join("checkout");
3254        let subdir = repo.join("src");
3255        let foreign = home.join("foreign");
3256        std::fs::create_dir_all(&subdir).unwrap();
3257        std::fs::create_dir(&foreign).unwrap();
3258        for checkout in [&repo, &foreign] {
3259            crate::git::git(checkout, &["init", "-q"]).await.unwrap();
3260        }
3261        let queue = Queue::at(home.join("queue"));
3262        let mut task = Task::new("work".into(), "work".into(), subdir, Source::Human);
3263        let mut state = crate::run::RunState::new(
3264            repo,
3265            "main".into(),
3266            "base".into(),
3267            "work".into(),
3268            crate::config::Config::default(),
3269        );
3270        state.reserve_under(home).unwrap();
3271        task.runs.push(state.id.clone());
3272        queue.put(&mut task).unwrap();
3273        let outbox = crate::task_inquiry::Outbox::at(home);
3274        let inquiry = outbox
3275            .file(
3276                &task,
3277                Some(state.id.clone()),
3278                "resume".into(),
3279                "Resume?",
3280                "",
3281            )
3282            .unwrap();
3283        let request = serde_json::to_string(&Operation::Resume {
3284            run: state.id.clone(),
3285        })
3286        .unwrap();
3287        outbox
3288            .update_decision(&inquiry.id, |d| {
3289                d.accept(&request)?;
3290                d.start()
3291            })
3292            .unwrap();
3293        task.dispatched_resumes
3294            .insert(inquiry.id.clone(), state.id.clone());
3295        queue.put(&mut task).unwrap();
3296        reconcile_decisions(&queue, home).unwrap();
3297        assert_eq!(
3298            outbox.get(&inquiry.id).unwrap().decision.unwrap().status,
3299            Status::InProgress
3300        );
3301
3302        state.carry_dispatched_resumes(&task);
3303        state.begin_pass();
3304        state.save_under(home).unwrap();
3305        let mut reassigned = task.clone();
3306        reassigned.repo = foreign;
3307        assert!(resume_started(home, &reassigned, &inquiry.id, &state.id).is_err());
3308        reconcile_decisions(&queue, home).unwrap();
3309        assert_eq!(
3310            outbox.get(&inquiry.id).unwrap().decision.unwrap().status,
3311            Status::Resolved
3312        );
3313    }
3314
3315    #[test]
3316    fn only_the_chat_seat_of_an_open_talk_is_authorized() {
3317        let tmp = tempfile::tempdir().unwrap();
3318        let talks = Talks::at(tmp.path().join("talks"));
3319        let t = talk(&talks, "talk-a");
3320        assert!(authorize(&talks, &t.id, "chat").is_ok());
3321        assert!(authorize(&talks, &t.id, "deputy").is_err());
3322        assert!(authorize(&talks, &t.id, "").is_err());
3323        assert!(authorize(&talks, "", "chat").is_err());
3324        assert!(
3325            authorize(&talks, "talk-", "chat").is_err(),
3326            "prefix is not an id"
3327        );
3328    }
3329
3330    #[test]
3331    fn tasks_of_any_origin_are_controlled_on_request() {
3332        let tmp = tempfile::tempdir().unwrap();
3333        let queue = Queue::at(tmp.path().join("queue"));
3334        let theirs = filed(&queue, "talk-b", "theirs");
3335        let mut hand = Task::new("h".into(), "h".into(), ".".into(), Source::Human);
3336        hand.hold_manual(Some("operator".into()));
3337        queue.put(&mut hand).unwrap();
3338        // Another chat's task and an operator-held human task are the owner's
3339        // work too: the request goes through without any ownership scope.
3340        assert_eq!(
3341            hold(&queue, &theirs.id, "wait").unwrap().status,
3342            TaskStatus::Held
3343        );
3344        assert_eq!(
3345            release(&queue, &hand.id).unwrap().status,
3346            TaskStatus::Queued
3347        );
3348        let again = retry(&queue, &theirs.id, None, "new").unwrap();
3349        assert_eq!(again.instruction, "new");
3350        assert_eq!(again.status, TaskStatus::Queued);
3351    }
3352
3353    #[test]
3354    fn hold_then_release_keeps_history_and_restarts_attempts() {
3355        let tmp = tempfile::tempdir().unwrap();
3356        let queue = Queue::at(tmp.path().join("queue"));
3357        let mut t = filed(&queue, "talk-a", "work");
3358        t.attempts = 3;
3359        t.runs.push("20260101-000000-aaaa".into());
3360        queue.put(&mut t).unwrap();
3361        let held = hold(&queue, &t.id, "owner asked").unwrap();
3362        assert_eq!(held.status, TaskStatus::Held);
3363        assert_eq!(held.hold_reason.as_deref(), Some("owner asked"));
3364        let back = release(&queue, &t.id).unwrap();
3365        assert_eq!(back.status, TaskStatus::Queued);
3366        assert_eq!(back.attempts, 0);
3367        assert_eq!(back.runs, t.runs);
3368        assert!(back.resumption.is_some());
3369    }
3370
3371    #[test]
3372    fn hold_and_release_refuse_done_and_running_without_saving() {
3373        let tmp = tempfile::tempdir().unwrap();
3374        let queue = Queue::at(tmp.path().join("queue"));
3375        for status in [TaskStatus::Done, TaskStatus::Running] {
3376            let mut t = filed(&queue, "talk-a", "work");
3377            t.start("20260101-000000-aaaa".into());
3378            if status == TaskStatus::Done {
3379                t.succeed(crate::queue::CompletionContext::new(
3380                    crate::queue::CompletionActor::Cli,
3381                    None,
3382                    tmp.path(),
3383                    &t,
3384                ));
3385            }
3386            queue.put(&mut t).unwrap();
3387            let before = std::fs::read(queue.path_of(&t.id)).unwrap();
3388            for operation in ["hold", "release"] {
3389                let error = if operation == "hold" {
3390                    hold(&queue, &t.id, "owner asked")
3391                } else {
3392                    release(&queue, &t.id)
3393                }
3394                .unwrap_err()
3395                .to_string();
3396                assert!(error.contains(operation), "{error}");
3397                assert!(error.contains(&t.id), "{error}");
3398                assert!(error.contains(status.as_str()), "{error}");
3399                let guidance = if status == TaskStatus::Done {
3400                    "create a new task"
3401                } else {
3402                    "use resume or abandon"
3403                };
3404                assert!(error.contains(guidance), "{error}");
3405                assert_eq!(std::fs::read(queue.path_of(&t.id)).unwrap(), before);
3406            }
3407        }
3408    }
3409
3410    #[test]
3411    fn hold_and_release_allow_unfinished_inactive_tasks() {
3412        let tmp = tempfile::tempdir().unwrap();
3413        let queue = Queue::at(tmp.path().join("queue"));
3414        for status in [
3415            TaskStatus::Queued,
3416            TaskStatus::Held,
3417            TaskStatus::Failed,
3418            TaskStatus::Blocked,
3419            TaskStatus::Parked,
3420        ] {
3421            for operation in ["hold", "release"] {
3422                let mut t = filed(&queue, "talk-a", "work");
3423                t.status = status;
3424                t.hold_reason = Some("old reason".into());
3425                t.attempts = 3;
3426                t.runs.push("20260101-000000-aaaa".into());
3427                queue.put(&mut t).unwrap();
3428                let changed = if operation == "hold" {
3429                    let held = hold(&queue, &t.id, " new reason ").unwrap();
3430                    assert_eq!(held.status, TaskStatus::Held);
3431                    assert_eq!(held.hold_reason.as_deref(), Some("new reason"));
3432                    assert_eq!(held.attempts, t.attempts);
3433                    held
3434                } else {
3435                    let released = release(&queue, &t.id).unwrap();
3436                    assert_eq!(released.status, TaskStatus::Queued);
3437                    assert_eq!(released.attempts, 0);
3438                    assert_eq!(released.resumption.as_ref().unwrap().source, "chat");
3439                    released
3440                };
3441                assert_eq!(changed.runs, t.runs);
3442                assert_eq!(queue.get(&t.id).unwrap().status, changed.status);
3443            }
3444        }
3445    }
3446
3447    #[test]
3448    fn retry_edits_and_requeues_in_one_save() {
3449        let tmp = tempfile::tempdir().unwrap();
3450        let queue = Queue::at(tmp.path().join("queue"));
3451        let mut t = filed(&queue, "talk-a", "old text");
3452        t.runs.push("20260101-000000-aaaa".into());
3453        t.attempts = 2;
3454        t.hold_manual(Some("stopped".into()));
3455        queue.put(&mut t).unwrap();
3456        let again = retry(&queue, &t.id, None, "new text").unwrap();
3457        assert_eq!(again.instruction, "new text");
3458        assert_eq!(again.status, TaskStatus::Queued);
3459        assert_eq!(again.attempts, 0);
3460        assert_eq!(again.runs, t.runs, "run history is kept");
3461        assert_eq!(again.resumption.as_ref().unwrap().source, "chat");
3462        assert_eq!(again.resumption.as_ref().unwrap().instruction, "new text");
3463        // A running task cannot be edited: nothing is changed.
3464        let mut running = filed(&queue, "talk-a", "busy");
3465        running.start("20260101-000000-bbbb".into());
3466        queue.put(&mut running).unwrap();
3467        assert!(retry(&queue, &running.id, None, "x").is_err());
3468        assert_eq!(queue.get(&running.id).unwrap().instruction, "busy");
3469        assert!(retry(&queue, &t.id, None, "  ").is_err());
3470    }
3471
3472    #[test]
3473    fn execution_commands_need_the_full_id_of_a_recorded_run() {
3474        let tmp = tempfile::tempdir().unwrap();
3475        let queue = Queue::at(tmp.path().join("queue"));
3476        let mut t = filed(&queue, "talk-b", "work");
3477        t.runs.push("20260101-000000-aaaa".into());
3478        queue.put(&mut t).unwrap();
3479        assert_eq!(
3480            run_task(&queue, "20260101-000000-aaaa").unwrap().id,
3481            t.id,
3482            "any chat may address another chat's run"
3483        );
3484        assert!(run_task(&queue, "aaaa").is_err());
3485        assert!(run_task(&queue, "20260101-000000-bbbb").is_err());
3486        assert!(resume(&queue, tmp.path(), "aaaa").is_err());
3487    }
3488
3489    #[test]
3490    fn abandon_needs_no_phrase_but_refuses_unrecorded_and_unknown_runs() {
3491        let tmp = tempfile::tempdir().unwrap();
3492        let queue = Queue::at(tmp.path().join("queue"));
3493        let mut t = filed(&queue, "talk-b", "work");
3494        t.runs.push("20260101-000000-aaaa".into());
3495        queue.put(&mut t).unwrap();
3496        // A run no task recorded is refused before liveness is judged.
3497        assert!(abandon(&queue, tmp.path(), "20260101-000000-bbbb").is_err());
3498        // A recorded run whose driver is not proven dead (here: no state to
3499        // judge at all) is never abandoned.
3500        assert!(abandon(&queue, tmp.path(), "20260101-000000-aaaa").is_err());
3501    }
3502}
3503
3504#[cfg(test)]
3505mod goal_admission_tests {
3506    use super::*;
3507
3508    #[tokio::test]
3509    async fn goal_effects_require_current_generation_scope_and_no_new_owner_input() {
3510        let tmp = tempfile::tempdir().unwrap();
3511        let talks = Talks::at(tmp.path().join("talks"));
3512        let queue = Queue::at(tmp.path().join("queue"));
3513        let target = tmp.path().join("target");
3514        std::fs::create_dir(&target).unwrap();
3515        crate::git::git(&target, &["init", "-q"]).await.unwrap();
3516        let mut talk = crate::talk::seeded_for_test("goal-effect", tmp.path().into());
3517        talk.turns.push(
3518            serde_json::from_value(serde_json::json!({
3519                "sender": "operator", "who": "operator", "body": "Follow this task through",
3520                "at": jiff::Timestamp::now()
3521            }))
3522            .unwrap(),
3523        );
3524        talks.put(&mut talk).unwrap();
3525        let mut task = Task::new(
3526            "work".into(),
3527            "work".into(),
3528            target.clone(),
3529            crate::queue::Source::Agent {
3530                run: talk.id.clone(),
3531                node: crate::queue::CHAT_NODE.into(),
3532            },
3533        );
3534        queue.put(&mut task).unwrap();
3535        let mut unrelated = Task::new(
3536            "other".into(),
3537            "other".into(),
3538            target.clone(),
3539            crate::queue::Source::Agent {
3540                run: talk.id.clone(),
3541                node: crate::queue::CHAT_NODE.into(),
3542            },
3543        );
3544        queue.put(&mut unrelated).unwrap();
3545        crate::chat_goal::apply(
3546            &queue,
3547            tmp.path(),
3548            &talks,
3549            &talk.id,
3550            &crate::chat_goal::Source::Input { turn: 0 },
3551            crate::chat_goal::Command::Establish {
3552                id: "g".into(),
3553                purpose: "Deliver this task".into(),
3554                scope: "This task only".into(),
3555                condition: "Verified delivery".into(),
3556                completion: crate::chat_goal::Completion::TasksDone,
3557                repo: Some(target),
3558                tasks: vec![task.id.clone()],
3559                runs: vec![],
3560                watches: vec![],
3561            },
3562        )
3563        .await
3564        .unwrap();
3565        talks
3566            .mutate(&talk.id, |talk| {
3567                let boundary = talk.turns.len();
3568                let goal = &mut talk.goals[0];
3569                goal.wake = 1;
3570                goal.started = Some(1);
3571                goal.launch_turns = Some(boundary);
3572                Ok(())
3573            })
3574            .unwrap();
3575        let source = crate::chat_goal::Source::Goal {
3576            id: "g".into(),
3577            generation: 1,
3578        };
3579        assert!(
3580            execute_authenticated(
3581                &queue,
3582                tmp.path(),
3583                &talks,
3584                &talk.id,
3585                source.clone(),
3586                Operation::Priority {
3587                    task: unrelated.id.clone(),
3588                    priority: 8
3589                }
3590            )
3591            .await
3592            .is_err()
3593        );
3594        execute_authenticated(
3595            &queue,
3596            tmp.path(),
3597            &talks,
3598            &talk.id,
3599            source.clone(),
3600            Operation::Priority {
3601                task: task.id.clone(),
3602                priority: 3,
3603            },
3604        )
3605        .await
3606        .unwrap();
3607        let hold = Operation::Hold {
3608            task: task.id.clone(),
3609            reason: "pause".into(),
3610        };
3611        crate::chat_goal::with_source(source.clone(), async {
3612            // Reassignment publishes under this same claim, between the first
3613            // admission and the mutation's claim acquisition.
3614            admit_goal_operation(&queue, tmp.path(), &talks, &talk.id, &hold).unwrap();
3615            let original = task.repo.clone();
3616            {
3617                let claim = queue.claim(&task.id).unwrap();
3618                task = queue.get(&task.id).unwrap();
3619                task.repo = talk.repo.clone();
3620                queue.put(&mut task).unwrap();
3621                drop(claim);
3622            }
3623            let result = claimed_for_chat(&queue, &task.id, &talks, &talk.id)
3624                .and_then(|claimed| hold_claimed(&queue, claimed, "pause"));
3625            assert!(result.unwrap_err().to_string().contains(&task.id));
3626            assert_eq!(queue.get(&task.id).unwrap().status, TaskStatus::Queued);
3627            task.repo = original;
3628            queue.put(&mut task).unwrap();
3629        })
3630        .await;
3631        let error = execute_authenticated(
3632            &queue,
3633            tmp.path(),
3634            &talks,
3635            &talk.id,
3636            source.clone(),
3637            Operation::Done {
3638                task: task.id.clone(),
3639                reason: Some("discard unfinished work".into()),
3640                result: None,
3641                discard: true,
3642            },
3643        )
3644        .await
3645        .unwrap_err();
3646        assert!(
3647            error.to_string().contains("explicit owner turn"),
3648            "{error:#}"
3649        );
3650        assert_eq!(queue.get(&task.id).unwrap().status, TaskStatus::Queued);
3651        assert!(queue.get(&task.id).unwrap().completion_history.is_empty());
3652        assert!(
3653            execute_authenticated(
3654                &queue,
3655                tmp.path(),
3656                &talks,
3657                &talk.id,
3658                source.clone(),
3659                Operation::Done {
3660                    task: unrelated.id.clone(),
3661                    reason: None,
3662                    result: None,
3663                    discard: false,
3664                },
3665            )
3666            .await
3667            .is_err()
3668        );
3669        // Goal task completion requires a confirmed landing or investigation findings.
3670        // Mark as an investigation so the subsequent reopen check in this test has no
3671        // merged run blocking reopen.
3672        queue
3673            .modify(&task.id, |t| {
3674                t.investigation = true;
3675                true
3676            })
3677            .unwrap();
3678        execute_authenticated(
3679            &queue,
3680            tmp.path(),
3681            &talks,
3682            &talk.id,
3683            source.clone(),
3684            Operation::Done {
3685                task: task.id.clone(),
3686                reason: Some("goal work finished".into()),
3687                result: Some("goal findings recorded".into()),
3688                discard: false,
3689            },
3690        )
3691        .await
3692        .unwrap();
3693        let error = execute_authenticated(
3694            &queue,
3695            tmp.path(),
3696            &talks,
3697            &talk.id,
3698            source.clone(),
3699            Operation::Reopen {
3700                task: task.id.clone(),
3701                reason: "recover unfinished work".into(),
3702            },
3703        )
3704        .await
3705        .unwrap_err();
3706        assert!(
3707            error.to_string().contains("explicit owner turn"),
3708            "{error:#}"
3709        );
3710        assert_eq!(queue.get(&task.id).unwrap().status, TaskStatus::Done);
3711        execute_authenticated(
3712            &queue,
3713            tmp.path(),
3714            &talks,
3715            &talk.id,
3716            crate::chat_goal::Source::Input { turn: 0 },
3717            Operation::Reopen {
3718                task: task.id.clone(),
3719                reason: "recover unfinished work".into(),
3720            },
3721        )
3722        .await
3723        .unwrap();
3724        assert_eq!(queue.get(&task.id).unwrap().status, TaskStatus::Held);
3725        talks
3726            .mutate(&talk.id, |talk| {
3727                talk.turns.push(serde_json::from_value(serde_json::json!({
3728                    "sender": "operator", "who": "operator", "body": "Stop",
3729                    "at": jiff::Timestamp::now()
3730                }))?);
3731                Ok(())
3732            })
3733            .unwrap();
3734        assert!(
3735            execute_authenticated(
3736                &queue,
3737                tmp.path(),
3738                &talks,
3739                &talk.id,
3740                source.clone(),
3741                Operation::Priority {
3742                    task: task.id.clone(),
3743                    priority: 9
3744                }
3745            )
3746            .await
3747            .is_err()
3748        );
3749        talks
3750            .mutate(&talk.id, |talk| {
3751                talk.turns.pop();
3752                talk.goals[0].state = crate::chat_goal::State::Stopped;
3753                talk.goals[0].wake = 2;
3754                talk.goals[0].started = None;
3755                Ok(())
3756            })
3757            .unwrap();
3758        assert!(
3759            execute_authenticated(
3760                &queue,
3761                tmp.path(),
3762                &talks,
3763                &talk.id,
3764                source,
3765                Operation::Priority {
3766                    task: task.id.clone(),
3767                    priority: 9
3768                }
3769            )
3770            .await
3771            .is_err()
3772        );
3773        assert_eq!(queue.get(&task.id).unwrap().priority, 3);
3774    }
3775
3776    #[tokio::test]
3777    async fn land_sync_recovery_chat_control_requires_explicit_owner_input() {
3778        let tmp = tempfile::tempdir().unwrap();
3779        let home = tmp.path();
3780        let queue = Queue::at(home.join("queue"));
3781        let talks = Talks::at(home.join("talks"));
3782        let repo = home.join("repo");
3783        std::fs::create_dir(&repo).unwrap();
3784        let mut config = crate::config::Config::default();
3785        config.agents.push(crate::config::AgentSpec {
3786            id: "fixture".into(),
3787            kind: crate::config::AgentKind::Command,
3788            model: None,
3789            command: vec!["true".into()],
3790            extra_args: vec![],
3791            env: Default::default(),
3792            prompt_delivery: None,
3793            max_turn_secs: None,
3794        });
3795        let talk = crate::talk::begin(&talks, &config, repo, Some("fixture")).unwrap();
3796
3797        let make_op = || Operation::RecoverLandSync {
3798            run: "20261127-125940-3ce0".into(),
3799            head: "a".repeat(40),
3800            request: "req-chat-guard".into(),
3801        };
3802
3803        // Automatic turn without owner input must be refused.
3804        let err = execute_authenticated(
3805            &queue,
3806            home,
3807            &talks,
3808            &talk.id,
3809            crate::chat_goal::Source::Automatic,
3810            make_op(),
3811        )
3812        .await
3813        .unwrap_err();
3814        assert!(
3815            err.to_string()
3816                .contains("recover-land-sync requires explicit owner input"),
3817            "{err:#}"
3818        );
3819
3820        // Standing automatic recovery turn covering a real held task must refuse RecoverLandSync
3821        // as outside the standing allowlist.
3822        let mut task = crate::queue::Task::new(
3823            "held".into(),
3824            "held work".into(),
3825            home.join("repo"),
3826            crate::queue::Source::Agent {
3827                run: talk.id.clone(),
3828                node: crate::queue::CHAT_NODE.into(),
3829            },
3830        );
3831        task.hold_machine(Some("landing base synchronization budget exhausted".into()));
3832        queue.put(&mut task).unwrap();
3833        let input: crate::talk::Turn = serde_json::from_value(serde_json::json!({
3834            "sender": "magi",
3835            "who": "operator",
3836            "body": "report",
3837            "at": jiff::Timestamp::now(),
3838            "messages": [{
3839                "sender": "magi",
3840                "body": "report",
3841                "at": jiff::Timestamp::now(),
3842                "attachments": [],
3843                "recovery_event": standing::Event::task(&task)
3844            }]
3845        }))
3846        .unwrap();
3847        let standing_source = standing::capture(
3848            true,
3849            home,
3850            &talk,
3851            Some(&input),
3852            crate::chat_goal::Source::Automatic,
3853        );
3854        let err = execute_authenticated(
3855            &queue,
3856            home,
3857            &talks,
3858            &talk.id,
3859            standing_source,
3860            Operation::Standing {
3861                task: task.id.clone(),
3862                evidence: "auto".into(),
3863                command: Box::new(make_op()),
3864            },
3865        )
3866        .await
3867        .unwrap_err();
3868        assert!(
3869            err.to_string()
3870                .contains("outside the standing recovery allowlist"),
3871            "{err:#}"
3872        );
3873    }
3874}