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    if let Some(id) = task.filed_by_chat().map(str::to_owned) {
915        task.chat = Some(id);
916        task.chat_reservation = crate::queue::ChatReservation::Established;
917    }
918    task
919}
920
921fn file_task(queue: &Queue, filing: Filing) -> Result<Task> {
922    let attach = filing.attach.clone();
923    let mut task = build_task(filing, false);
924    if attach.is_empty() {
925        queue.put(&mut task)?;
926    } else {
927        queue.attach_and_put(&mut task, &attach)?;
928    }
929    Ok(task)
930}
931
932/// A goal turn cannot redirect existing effects to unrelated work.
933fn admit_goal_operation(
934    queue: &Queue,
935    home: &Path,
936    talks: &Talks,
937    talk_id: &str,
938    operation: &Operation,
939) -> Result<()> {
940    let crate::chat_goal::Source::Goal { id, generation } = crate::chat_goal::current_source()
941    else {
942        return Ok(());
943    };
944    let talk = talks.get(talk_id)?;
945    let goal = talk
946        .goals
947        .iter()
948        .find(|goal| goal.id == id)
949        .context("unknown goal")?;
950    goal.admit(generation)?;
951    ensure!(
952        !goal.owner_input.is_empty(),
953        "this goal was registered under standing authorization; fresh owner input is required with the setting off"
954    );
955    let repo = goal.effective_repo(&talk.repo);
956    let task_allowed = |reference: &str| -> Result<()> {
957        let id = queue.resolve_id(reference)?;
958        ensure!(
959            goal.tasks.contains(&id),
960            "effect targets a task outside this goal"
961        );
962        crate::chat_goal::task_record(queue, &id, repo)?;
963        Ok(())
964    };
965    let run_allowed = |run: &str| -> Result<()> {
966        ensure!(
967            goal.runs.iter().any(|id| id == run)
968                || goal
969                    .tasks
970                    .iter()
971                    .any(|id| crate::chat_goal::task_record(queue, id, repo)
972                        .is_ok_and(|task| task.execution_runs().iter().any(|id| id == run))),
973            "effect targets an execution outside this goal"
974        );
975        crate::chat_goal::run_record(home, run, repo)?;
976        Ok(())
977    };
978    match operation {
979        Operation::Standing { .. } => bail!("standing authorization is disabled for this turn"),
980        Operation::Goal { .. } => {}
981        Operation::Add { filing } => {
982            crate::chat_goal::require_repo("filing", talk_id, &filing.repo, repo)?;
983            ensure!(
984                matches!(&filing.source, crate::queue::Source::Agent { run, node }
985                    if run == talk_id && node == crate::queue::CHAT_NODE),
986                "goal filing must retain this conversation's provenance"
987            );
988        }
989        Operation::SetImmediate { .. } => {
990            bail!(
991                "automatic goal turns cannot change immediate settings; explicit owner input is required"
992            )
993        }
994        Operation::AddImmediate { .. } => {
995            bail!(
996                "automatic goal turns cannot file immediate tasks; explicit owner input is required"
997            )
998        }
999        Operation::Done { discard: true, .. } | Operation::Reopen { .. } => {
1000            anyhow::bail!("task discard and reopen require an explicit owner turn");
1001        }
1002        Operation::Done {
1003            task,
1004            discard: false,
1005            ..
1006        }
1007        | Operation::Priority { task, .. }
1008        | Operation::Hold { task, .. }
1009        | Operation::Release { task }
1010        | Operation::Retry { task, .. }
1011        | Operation::ReconcileRetention { task, .. } => task_allowed(task)?,
1012        Operation::GrantRepair { request } => {
1013            task_allowed(&request.task)?;
1014            run_allowed(&request.run)?;
1015        }
1016        Operation::ReconcileRepairGrant { request } => {
1017            task_allowed(&request.task)?;
1018            run_allowed(&request.run)?;
1019        }
1020        Operation::AdoptInstruction { .. } => {
1021            bail!(
1022                "automatic goal turns cannot adopt a revised instruction; explicit owner input is required"
1023            )
1024        }
1025        Operation::RecoverLandSync { .. } => {
1026            bail!(
1027                "automatic goal turns cannot authorize landing base-sync recovery; explicit owner input is required"
1028            )
1029        }
1030        Operation::Resume { run }
1031        | Operation::SyncBaseOnly { run }
1032        | Operation::RecoverBase { run, .. }
1033        | Operation::Abandon { run }
1034        | Operation::RerunChecks { run, .. } => run_allowed(run)?,
1035        Operation::ForDecision { inquiry, .. }
1036        | Operation::ReconcileDecision { inquiry }
1037        | Operation::SettleDecision { inquiry, .. } => {
1038            let record = crate::task_inquiry::Outbox::at(home).get(inquiry)?;
1039            crate::chat_goal::require_repo("inquiry", inquiry, &record.repo, repo)?;
1040            task_allowed(&record.task)?;
1041            if let Some(run) = record.run {
1042                run_allowed(&run)?;
1043            }
1044        }
1045        Operation::Decide { question, .. }
1046        | Operation::Answer { question, .. }
1047        | Operation::ReplyOther { question, .. } => {
1048            let questions = crate::ask::Questions::at(home.join("questions"));
1049            let question = questions.get_for_effects(&questions.resolve_id(question)?)?;
1050            if question.run_names_task() {
1051                task_allowed(&question.run)?;
1052            } else {
1053                run_allowed(&question.run)?;
1054            }
1055        }
1056        Operation::MergePr {
1057            repo: slug, number, ..
1058        } => {
1059            let expected = format!("https://github.com/{slug}/pull/{number}");
1060            let mut found = false;
1061            let mut inspect = |run: &str| -> Result<()> {
1062                let state = crate::chat_goal::run_record(home, run, repo)?;
1063                found |= state
1064                    .pr
1065                    .as_ref()
1066                    .is_some_and(|pr| pr.url.eq_ignore_ascii_case(&expected));
1067                Ok(())
1068            };
1069            for run in &goal.runs {
1070                inspect(run)?;
1071            }
1072            for task in &goal.tasks {
1073                for run in crate::chat_goal::task_record(queue, task, repo)?.execution_runs() {
1074                    inspect(run)?;
1075                }
1076            }
1077            ensure!(found, "merge targets a pull request outside this goal");
1078        }
1079        Operation::Reassign { .. } => bail!("automatic goal turns cannot change repository scope"),
1080    }
1081    Ok(())
1082}
1083
1084/// Run one typed operation on behalf of the owner, retaining failures and
1085/// uncertainty. A repeated command never blindly replays a possibly applied
1086/// external effect. The underlying operation retains its existing claims and
1087/// receipts; this journal is its user-visible lifecycle, not a second worker.
1088async fn execute_decision(
1089    queue: &Queue,
1090    home: &Path,
1091    talks: &Talks,
1092    chat: &str,
1093    id: &str,
1094    command: Operation,
1095) -> Result<String> {
1096    use crate::task_decision::Status;
1097    admit_goal_operation(queue, home, talks, chat, &command)?;
1098    let outbox = crate::task_inquiry::Outbox::at(home);
1099    let _execution = outbox.execution_claim(id)?;
1100    let inquiry = outbox.get(id)?;
1101    ensure!(
1102        inquiry.delivered_to.as_deref() == Some(chat),
1103        "decision belongs to another chat"
1104    );
1105    let task = queue.get(&inquiry.task)?;
1106    ensure!(task.repo == inquiry.repo, "decision repository changed");
1107    let deferred = matches!(
1108        command,
1109        Operation::Resume { .. } | Operation::MergePr { .. }
1110    );
1111    let merge = match &command {
1112        Operation::MergePr {
1113            repo,
1114            number,
1115            head,
1116            request,
1117        } => Some(crate::chat_merge::Request {
1118            repo: repo.clone(),
1119            number: *number,
1120            head: head.clone(),
1121            request: request.clone(),
1122        }),
1123        _ => None,
1124    };
1125    match &command {
1126        Operation::Done { task: target, .. }
1127        | Operation::Reopen { task: target, .. }
1128        | Operation::Hold { task: target, .. }
1129        | Operation::Release { task: target }
1130        | Operation::Retry { task: target, .. } => {
1131            ensure!(
1132                queue.resolve_id(target)? == task.id,
1133                "command targets another task"
1134            );
1135        }
1136        Operation::Resume { run }
1137        | Operation::Abandon { run }
1138        | Operation::RerunChecks { run, .. } => {
1139            ensure!(
1140                task.runs.contains(run) && inquiry.run.as_ref().is_none_or(|own| own == run),
1141                "command targets another execution"
1142            );
1143            ensure!(
1144                queue
1145                    .list()
1146                    .iter()
1147                    .filter(|owner| owner.runs.contains(run))
1148                    .count()
1149                    == 1,
1150                "execution ownership is ambiguous"
1151            );
1152        }
1153        Operation::MergePr { repo, number, .. } => {
1154            let run = inquiry
1155                .run
1156                .as_ref()
1157                .or_else(|| task.runs.last())
1158                .context("task has no execution for this merge")?;
1159            let state = crate::run::RunState::load_under(run, home)?;
1160            ensure!(state.id == *run, "merge run identity changed");
1161            ensure!(
1162                crate::git::same_checkout(&state.repo, &task.repo)?,
1163                "merge targets another repository"
1164            );
1165            let expected = format!("https://github.com/{repo}/pull/{number}");
1166            ensure!(
1167                state
1168                    .pr
1169                    .as_ref()
1170                    .is_some_and(|pr| pr.url.eq_ignore_ascii_case(&expected)),
1171                "merge targets another task or repository"
1172            );
1173        }
1174        _ => bail!("use a task/run effect command with --decision; routed approvals use decide"),
1175    }
1176    let request = serde_json::to_string(&command)?;
1177    let mut decision = inquiry.decision.context("inquiry is informational")?;
1178    if decision.request.is_some()
1179        && decision.status != Status::Resolved
1180        && let Operation::Resume { run } = &command
1181    {
1182        ensure!(
1183            decision.request.as_deref() == Some(&request),
1184            "decision already binds a different request"
1185        );
1186        // Queued also includes successfully published resumes. Reconcile under
1187        // the execution claim before permitting any retry, even if the run has
1188        // since returned to a resumable state. Only proven non-publication may
1189        // enter the retry path below.
1190        reconcile_resume_claimed(queue, home, &outbox, id, run)?;
1191        decision = outbox
1192            .get(id)?
1193            .decision
1194            .context("inquiry is informational")?;
1195        ensure!(
1196            decision.status == Status::Resolved || decision.retry_safe,
1197            "previous resume remains queued or executing; it will not be replayed"
1198        );
1199    }
1200    if decision.status == Status::Resolved {
1201        ensure!(
1202            decision.request.as_deref() == Some(&request),
1203            "decision resolved for a different request"
1204        );
1205        return Ok(format!(
1206            "decision {id} is already resolved; inspect its outcome history"
1207        ));
1208    }
1209    if let Operation::RerunChecks { run, request, .. } = &command {
1210        // Reject correctable input before binding the decision to this exact
1211        // command. Execution revalidates these reads before taking its lock.
1212        rerun_preflight(queue, home, run, request)?;
1213    }
1214    if let Some(action) = &merge {
1215        // Malformed input must not durably bind this decision to a command
1216        // that can never reach its effect service.
1217        action.validate()?;
1218    }
1219    // Keep admission across acceptance and execution: contention and request
1220    // collisions must not bind a fresh decision to an unstartable operation.
1221    let merge_admission = merge
1222        .as_ref()
1223        .map(|action| crate::chat_merge::admit(home, talks, chat, action))
1224        .transpose()?;
1225    if decision.request.is_none() && decision.status == Status::RetryNeeded {
1226        if let Ok(source) = crate::ask::Questions::at(home.join("questions")).get(id) {
1227            ensure!(
1228                !crate::task_chat::awaits_decision(&source),
1229                "a legacy effect still needs its receipt reconciled before another effect is accepted"
1230            );
1231        }
1232    }
1233    {
1234        // A live task cannot accept a repair grant. Do not prevent decisions
1235        // that its active driver is waiting for by taking its execution claim.
1236        let claim = (queue.get(&task.id)?.status != TaskStatus::Running)
1237            .then(|| queue.claim(&task.id))
1238            .transpose();
1239        let _claim = match claim {
1240            Ok(claim) => claim,
1241            Err(error) => {
1242                // Admission could not start this attempt. Retain the exact
1243                // owner request and pre-effect failure just as execution-side
1244                // claim contention does, without publishing any task effect.
1245                let message = format!(
1246                    "{error:#}. No effect began; retry this same request after resolving the cause, or explicitly settle it."
1247                );
1248                outbox.update_decision(id, |d| {
1249                    let safe = d.request.is_none() || d.retry_safe;
1250                    d.accept(&request)?;
1251                    if safe {
1252                        d.fail_before_effect(&message)
1253                    } else {
1254                        // A prior queued/uncertain attempt still needs its own
1255                        // receipt. Contention is not proof that it never ran.
1256                        Ok(false)
1257                    }
1258                })?;
1259                return Err(anyhow::Error::new(BeforeEffect(error)));
1260            }
1261        };
1262        outbox.update_decision(id, |d| d.accept(&request))?;
1263    }
1264    let late_admission = crate::chat_goal::fence(talks, chat, &crate::chat_goal::current_source())
1265        .and_then(|()| admit_goal_operation(queue, home, talks, chat, &command));
1266    if late_admission.is_ok()
1267        && decision.request.is_some()
1268        && matches!(decision.status, Status::InProgress | Status::RetryNeeded)
1269    {
1270        if decision.retry_safe {
1271            outbox.update_decision(id, |d| {
1272                d.retry_unapplied()?;
1273                d.start()
1274            })?;
1275        } else {
1276            let action = merge
1277                .as_ref()
1278                .context("previous effect needs receipt reconciliation; it will not be replayed")?;
1279            ensure!(
1280                merge_receipt(home, chat, action)?.is_some(),
1281                "previous merge has no receipt; inspect the operation before retrying"
1282            );
1283        }
1284        // The shared merge service only checks the forge once this exact
1285        // request has a receipt; it never issues the merge command twice.
1286    } else if late_admission.is_ok() {
1287        outbox.update_decision(id, |d| d.start())?;
1288    }
1289    let local = match late_admission {
1290        // A refusal now says nothing about a prior attempt that may have acted.
1291        Err(error)
1292            if decision.request.is_some()
1293                && !decision.retry_safe
1294                && (matches!(decision.status, Status::InProgress | Status::RetryNeeded)
1295                    || decision
1296                        .history
1297                        .iter()
1298                        .any(|event| event.status == Status::InProgress)) =>
1299        {
1300            return Err(error);
1301        }
1302        Err(error) => Err(anyhow::Error::new(BeforeEffect(error))),
1303        Ok(()) => {
1304            Box::pin(apply_local_decision(
1305                queue,
1306                home,
1307                id,
1308                &request,
1309                &inquiry.task,
1310                &inquiry.repo,
1311                &command,
1312            ))
1313            .await
1314        }
1315    };
1316    let result = if let Err(error) = local {
1317        Err(error)
1318    } else if let Some(message) = local? {
1319        Ok(message)
1320    } else if let Operation::Resume { run } = &command {
1321        // Validation precedes any write: a refusal means nothing began.
1322        crate::resume::validate(home, run)
1323            .map(|_| ())
1324            .map_err(|e| anyhow::Error::new(BeforeEffect(e)))
1325            .and_then(|()| -> Result<String> {
1326                let pinned =
1327                    crate::resume::pin_queued(queue, run, None, Some(id)).map_err(|error| {
1328                        if error.is::<crate::resume::BeforeQueueWrite>() {
1329                            anyhow::Error::new(BeforeEffect(error))
1330                        } else {
1331                            error
1332                        }
1333                    })?;
1334                if !pinned {
1335                    return Err(anyhow::Error::new(BeforeEffect(anyhow::anyhow!(
1336                        "no queued task owns this run"
1337                    ))));
1338                }
1339                Ok(format!(
1340                    "resume queued for {run}; execution start remains unconfirmed"
1341                ))
1342            })
1343    } else if let Operation::Abandon { run } = &command {
1344        crate::driver::abandon_decision(home, run, id, &request)
1345            .map_err(|error| {
1346                if error.is::<crate::driver::BeforeAbandonWrite>() {
1347                    anyhow::Error::new(BeforeEffect(error))
1348                } else {
1349                    error
1350                }
1351            })
1352            .map(|()| format!("abandoned run {run}"))
1353    } else if let Some(admission) = merge_admission {
1354        crate::chat_merge::merge_admitted(home, merge.as_ref().unwrap().clone(), admission)
1355            .await
1356            .map_err(|error| {
1357                if error.is::<crate::chat_merge::BeforeMergeWrite>() {
1358                    anyhow::Error::new(BeforeEffect(error))
1359                } else {
1360                    error
1361                }
1362            })
1363    } else {
1364        Box::pin(execute(queue, home, talks, chat, command)).await
1365    };
1366    match result {
1367        Ok(message) => {
1368            if let Some(action) = &merge {
1369                if let Some(receipt) = merge_receipt(home, chat, action)? {
1370                    if receipt["status"] == "merged" {
1371                        outbox.update_decision(id, |d| d.applied(&message))?;
1372                    } else if receipt["status"] != "pending" {
1373                        outbox.update_decision(id, |d| {
1374                            d.fail(&format!(
1375                                "{message}; reuse this same request ID to reconcile only"
1376                            ))
1377                        })?;
1378                    }
1379                }
1380            } else if !deferred {
1381                outbox.update_decision(id, |d| {
1382                    d.applied(&format!("typed command completed: {message}"))
1383                })?;
1384            }
1385            if deferred
1386                && outbox
1387                    .get(id)?
1388                    .decision
1389                    .as_ref()
1390                    .is_some_and(|d| d.status == Status::InProgress)
1391            {
1392                outbox.update_decision(id, |d| d.queued())?;
1393            }
1394            // Resume has only been queued. Its execution is confirmed by a
1395            // later scheduler projection, never by this command's return.
1396            Ok(message)
1397        }
1398        Err(error) => {
1399            let message = if error.is::<BeforeEffect>() {
1400                format!(
1401                    "{error:#}. No effect began; retry this same request after resolving the cause, or explicitly settle it."
1402                )
1403            } else {
1404                format!(
1405                    "Operation failed or has an uncertain result: {error:#}. Inspect its receipt before retrying."
1406                )
1407            };
1408            outbox.update_decision(id, |d| {
1409                if error.is::<BeforeEffect>() {
1410                    d.fail_before_effect(&message)
1411                } else {
1412                    d.fail(&message)
1413                }
1414            })?;
1415            Err(error)
1416        }
1417    }
1418}
1419
1420#[derive(Debug, thiserror::Error)]
1421#[error("effect did not start: {0:#}")]
1422struct BeforeEffect(anyhow::Error);
1423
1424/// Commit a task-local effect and its exact receipt under one queue claim.
1425/// The inquiry projection may lag this write, but restart never has to infer
1426/// completion from the task's current status or repeat the operation.
1427async fn apply_local_decision(
1428    queue: &Queue,
1429    home: &Path,
1430    id: &str,
1431    request: &str,
1432    owner: &str,
1433    repo: &Path,
1434    command: &Operation,
1435) -> Result<Option<String>> {
1436    let target = match command {
1437        Operation::Done { task, .. }
1438        | Operation::Reopen { task, .. }
1439        | Operation::Hold { task, .. }
1440        | Operation::Release { task }
1441        | Operation::Retry { task, .. } => task,
1442        _ => return Ok(None),
1443    };
1444    let prepare = async {
1445        let (_claim, mut task) = claimed(queue, target)?;
1446        let expected = task.clone();
1447        ensure!(
1448            task.id == owner && task.repo == repo,
1449            "decision ownership changed"
1450        );
1451        if let Some(prior) = task.decision_effects.get(id) {
1452            ensure!(prior == request, "decision receipt binds another command");
1453            let message = format!("task {}: decision {id} already applied", task.id);
1454            return Ok((_claim, task, message, true, None, expected));
1455        }
1456        let mut close_guard = None;
1457        let message = match command {
1458            Operation::Done {
1459                reason,
1460                result,
1461                discard,
1462                ..
1463            } => {
1464                let (guards, context) = crate::task_completion::admit_close(
1465                    &task,
1466                    home,
1467                    crate::queue::CompletionActor::Chat(
1468                        crate::task_inquiry::Outbox::at(home)
1469                            .get(id)?
1470                            .delivered_to
1471                            .context("decision has no chat")?,
1472                    ),
1473                    reason.clone(),
1474                    result.clone(),
1475                    *discard,
1476                )
1477                .await?;
1478                if !*discard && task.investigation {
1479                    task.record_investigation_result(result.as_deref())?;
1480                }
1481                close_guard = Some(guards);
1482                task.succeed(context);
1483                crate::task_completion::describe(&task)
1484            }
1485            Operation::Reopen { reason, .. } => {
1486                let (guards, context) = crate::task_completion::admit_reopen(
1487                    &task,
1488                    home,
1489                    crate::queue::CompletionActor::Chat(
1490                        crate::task_inquiry::Outbox::at(home)
1491                            .get(id)?
1492                            .delivered_to
1493                            .context("decision has no chat")?,
1494                    ),
1495                    reason,
1496                )
1497                .await?;
1498                close_guard = Some(guards);
1499                task.reopen(context)?;
1500                describe(&task, "reopened on hold")
1501            }
1502            Operation::Hold { reason, .. } => {
1503                check_hold_release(&task, "hold")?;
1504                let reason = reason.trim();
1505                task.hold_manual((!reason.is_empty()).then(|| reason.to_owned()));
1506                describe(&task, "held")
1507            }
1508            Operation::Release { .. } => {
1509                check_hold_release(&task, "release")?;
1510                task.release_operator("chat", Some(id));
1511                describe(&task, "released")
1512            }
1513            Operation::Retry {
1514                title, instruction, ..
1515            } => {
1516                ensure!(
1517                    !instruction.trim().is_empty(),
1518                    "the new instruction is empty"
1519                );
1520                let title = title
1521                    .clone()
1522                    .unwrap_or_else(|| crate::queue::title_from(instruction, 72));
1523                task.edit(title, instruction.clone())?;
1524                task.release_operator("chat", Some(id));
1525                describe(&task, "retry queued for")
1526            }
1527            _ => unreachable!("task-local operation checked above"),
1528        };
1529        task.decision_effects
1530            .insert(id.to_owned(), request.to_owned());
1531        Ok::<_, anyhow::Error>((_claim, task, message, false, close_guard, expected))
1532    };
1533    let (_claim, mut task, message, already_applied, close_guard, expected) =
1534        prepare.await.map_err(BeforeEffect)?;
1535    if !already_applied {
1536        if close_guard.is_some() {
1537            queue.commit_completion(&mut task, &expected)?;
1538        } else {
1539            queue.put(&mut task)?;
1540        }
1541    }
1542    if matches!(command, Operation::Done { .. }) {
1543        crate::daemon::supersede_prior_runs(&task, home);
1544    }
1545    Ok(Some(message))
1546}
1547
1548/// Explicit owner-requested reconciliation executes nothing. Under the task
1549/// claim, prove that the exact intended condition already holds; otherwise keep
1550/// uncertainty visible. External effects require their own receipts instead.
1551fn reconcile_task_decision(queue: &Queue, home: &Path, chat: &str, id: &str) -> Result<()> {
1552    let outbox = crate::task_inquiry::Outbox::at(home);
1553    let inquiry = outbox.get(id)?;
1554    ensure!(
1555        inquiry.delivered_to.as_deref() == Some(chat)
1556            || (inquiry.task.is_empty() && inquiry.delivered_to.is_none()),
1557        "decision belongs to another chat"
1558    );
1559    let decision = inquiry.decision.context("inquiry is informational")?;
1560    if decision.status == crate::task_decision::Status::Resolved {
1561        return Ok(());
1562    }
1563    if decision
1564        .request
1565        .as_ref()
1566        .is_none_or(|request| request.starts_with("decision: "))
1567    {
1568        let source = crate::ask::Questions::at(home.join("questions")).read_history(id)?;
1569        crate::task_chat::sync_effect_receipt(home, queue, &source);
1570        ensure!(
1571            outbox
1572                .get(id)?
1573                .decision
1574                .is_some_and(|d| d.status == crate::task_decision::Status::Resolved),
1575            "source effect remains unconfirmed; no operation was replayed"
1576        );
1577        return Ok(());
1578    }
1579    let request = decision
1580        .request
1581        .context("decision has no accepted operation to reconcile")?;
1582    let command: Operation = serde_json::from_str(&request)?;
1583    if let Operation::Resume { run } = &command {
1584        reconcile_resume_decision(queue, home, &outbox, id, run)?;
1585        ensure!(
1586            outbox.get(id)?.decision.is_some_and(|d| {
1587                d.status == crate::task_decision::Status::Resolved || d.retry_safe
1588            }),
1589            "resume remains queued or executing; no operation was replayed"
1590        );
1591        return Ok(());
1592    }
1593    let (_claim, task) = claimed(queue, &inquiry.task)?;
1594    ensure!(task.repo == inquiry.repo, "decision repository changed");
1595    if let Some(receipt) = task.decision_effects.get(id) {
1596        ensure!(
1597            receipt == &request,
1598            "decision receipt binds another command"
1599        );
1600        return outbox.update_decision(id, |d| {
1601            d.applied("exact task command receipt confirmed; no operation replayed")
1602        });
1603    }
1604    let matches = match command {
1605        Operation::Hold {
1606            task: target,
1607            reason,
1608        } => {
1609            queue.resolve_id(&target)? == task.id
1610                && task.status == TaskStatus::Held
1611                && task.hold_reason.as_deref() == Some(reason.trim())
1612        }
1613        Operation::Release { task: target } => {
1614            queue.resolve_id(&target)? == task.id
1615                && task.status == TaskStatus::Queued
1616                && !task.operator_held()
1617        }
1618        Operation::Done { task: target, .. } => {
1619            queue.resolve_id(&target)? == task.id && task.status == TaskStatus::Done
1620        }
1621        Operation::Retry {
1622            task: target,
1623            title,
1624            instruction,
1625        } => {
1626            queue.resolve_id(&target)? == task.id
1627                && task.instruction == instruction
1628                && title.as_ref().is_none_or(|title| *title == task.title)
1629                && task.status == TaskStatus::Queued
1630        }
1631        Operation::Abandon { run } => abandonment_receipt(home, &task, id, &run, &request)?,
1632        _ => anyhow::bail!(
1633            "external effects require their authoritative receipt; no operation was replayed"
1634        ),
1635    };
1636    ensure!(
1637        matches,
1638        "intended task condition is not confirmed; no operation was replayed"
1639    );
1640    outbox.update_decision(id, |d| d.applied("owner-requested reconciliation: exact intended task condition confirmed under its claim; no effect remains necessary"))
1641}
1642
1643/// Read the exact request's committed execution pass or durable pin supersession.
1644/// A transient task status alone never proves either outcome.
1645pub(crate) fn resume_started(home: &Path, task: &Task, inquiry: &str, run: &str) -> Result<bool> {
1646    ensure!(
1647        crate::run::is_run_id(run) && task.runs.iter().any(|id| id == run),
1648        "resume run ownership changed"
1649    );
1650    let state = crate::run::RunState::load_under(run, home)?;
1651    ensure!(state.id == run, "resume run identity changed");
1652    ensure!(
1653        crate::git::same_checkout(&state.repo, &task.repo)?,
1654        "resume run repository changed"
1655    );
1656    if task
1657        .superseded_resumes
1658        .get(inquiry)
1659        .is_some_and(|target| target == run)
1660    {
1661        return Ok(true);
1662    }
1663    Ok(state.decision_starts.get(inquiry).is_some_and(|index| {
1664        state
1665            .passes
1666            .get(*index)
1667            .is_some_and(|pass| pass.index == *index)
1668    }))
1669}
1670
1671/// Publication writes the pin and actions_applied marker atomically. Fence the
1672/// publisher and scheduler before treating their absence as pre-effect proof.
1673/// A published pin may already be consumed, so its absence alone is not proof.
1674fn reconcile_resume_decision(
1675    queue: &Queue,
1676    home: &Path,
1677    outbox: &crate::task_inquiry::Outbox,
1678    id: &str,
1679    run: &str,
1680) -> Result<()> {
1681    let Ok(_execution) = outbox.execution_claim(id) else {
1682        return Ok(());
1683    };
1684    reconcile_resume_claimed(queue, home, outbox, id, run)
1685}
1686
1687/// The caller holds this inquiry's execution claim, including on resubmission.
1688fn reconcile_resume_claimed(
1689    queue: &Queue,
1690    home: &Path,
1691    outbox: &crate::task_inquiry::Outbox,
1692    id: &str,
1693    run: &str,
1694) -> Result<()> {
1695    let inquiry = outbox.get(id)?;
1696    let Ok(_claim) = queue.claim(&inquiry.task) else {
1697        return Ok(());
1698    };
1699    let task = queue.get(&inquiry.task)?;
1700    ensure!(task.repo == inquiry.repo, "resume task repository changed");
1701    let decision = inquiry.decision.context("inquiry is informational")?;
1702    if decision.status == crate::task_decision::Status::Resolved {
1703        return Ok(());
1704    }
1705    if resume_started(home, &task, id, run)? {
1706        outbox.update_decision(id, |d| {
1707            d.applied("exact resume execution-start or supersession receipt confirmed")
1708        })?;
1709    } else if !task.action_applied(id)
1710        && !task.dispatched_resumes.contains_key(id)
1711        && !task.superseded_resumes.contains_key(id)
1712        && !task
1713            .resume_override
1714            .as_ref()
1715            .is_some_and(|pin| pin.question_id == id)
1716    {
1717        outbox.update_decision(id, |d| {
1718            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.")
1719        })?;
1720    }
1721    Ok(())
1722}
1723
1724fn abandonment_receipt(
1725    home: &Path,
1726    task: &Task,
1727    id: &str,
1728    run: &str,
1729    request: &str,
1730) -> Result<bool> {
1731    ensure!(
1732        task.runs.iter().any(|own| own == run),
1733        "abandon run ownership changed"
1734    );
1735    let state = crate::run::RunState::load_under(run, home)?;
1736    ensure!(state.id == run, "abandon run identity changed");
1737    ensure!(
1738        crate::git::same_checkout(&state.repo, &task.repo)?,
1739        "abandon run repository changed"
1740    );
1741    Ok(state
1742        .abandonment_receipts
1743        .get(id)
1744        .is_some_and(|receipt| receipt == request))
1745}
1746
1747fn merge_receipt(
1748    home: &Path,
1749    chat: &str,
1750    action: &crate::chat_merge::Request,
1751) -> Result<Option<serde_json::Value>> {
1752    ensure!(
1753        crate::ask::valid_asset_name(chat) && crate::ask::valid_asset_name(&action.request),
1754        "invalid merge receipt identity"
1755    );
1756    let path = home
1757        .join("chat-controls")
1758        .join(chat)
1759        .join(format!("{}.json", action.request));
1760    let bytes = match std::fs::read(path) {
1761        Ok(bytes) => bytes,
1762        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
1763        Err(error) => return Err(error.into()),
1764    };
1765    let receipt: serde_json::Value = serde_json::from_slice(&bytes)?;
1766    ensure!(
1767        receipt["action"] == serde_json::to_value(action)?,
1768        "merge receipt names another operation"
1769    );
1770    Ok(Some(receipt))
1771}
1772
1773#[derive(Debug, PartialEq, Eq)]
1774struct ApprovalEvidence {
1775    target: crate::merge_decision::Target,
1776    terminal: bool,
1777    successor: Option<(String, String)>,
1778}
1779
1780impl ApprovalEvidence {
1781    fn obsolete_reason(&self, state: &str, head: &str) -> Option<String> {
1782        if self.terminal
1783            && let Some(reason) = obsolete_pr_reason(state, head, &self.target)
1784        {
1785            return Some(reason);
1786        }
1787        let (question, successor_head) = self.successor.as_ref()?;
1788        if state == "OPEN" && head == successor_head && head != self.target.head {
1789            return Some(format!(
1790                "Obsolete: approval for {} at {} was retired in favor of inquiry {question} at {head}",
1791                self.target.pr, self.target.head
1792            ));
1793        }
1794        None
1795    }
1796}
1797
1798/// Read the exact source target and whether no effect can remain.
1799fn approval_target(
1800    home: &Path,
1801    queue: &Queue,
1802    inquiry: &crate::task_inquiry::Inquiry,
1803) -> Option<ApprovalEvidence> {
1804    use crate::task_decision::Status;
1805    let decision = inquiry.decision.as_ref()?;
1806    if decision.status == Status::Resolved || inquiry.task.is_empty() {
1807        return None;
1808    }
1809    let task = queue.get(&inquiry.task).ok()?;
1810    if task.id != inquiry.task || task.repo != inquiry.repo {
1811        return None;
1812    }
1813    let run_id = inquiry.run.as_ref()?;
1814    if !task.execution_runs().contains(run_id) {
1815        return None;
1816    }
1817    let q = crate::ask::Questions::at(home.join("questions"))
1818        .read_history(&inquiry.id)
1819        .ok()?;
1820    if inquiry.key != format!("question:{}", q.id)
1821        || q.node != crate::land::APPROVAL_NODE
1822        || q.run != *run_id
1823        || q.legacy_foreground
1824        || q.routed_task.as_ref().is_some_and(|id| id != &task.id)
1825        || crate::task_chat::task_of(&q, &queue.list()).as_ref() != Some(&task.id)
1826    {
1827        return None;
1828    }
1829    let no_reply = q.answer.is_none()
1830        || (q.resolution().as_deref() == Some(crate::land::APPROVE)
1831            && crate::task_chat::migration_sources(home)
1832                .is_ok_and(|ids| ids.is_some_and(|ids| ids.contains(&q.id)))
1833            && crate::task_chat::source_reply_needs_confirmation(home, &q));
1834    let target = q.merge_target.clone()?;
1835    let run = crate::run::RunState::load_under(run_id, home).ok()?;
1836    if run.id != *run_id
1837        || run.repo != task.repo
1838        || !task.assignment_accepts(&run)
1839        || run
1840            .origin
1841            .as_ref()
1842            .and_then(|o| o.task.as_ref())
1843            .is_some_and(|id| id != &task.id)
1844        || target.head.is_empty()
1845        || !run.pr.as_ref().is_some_and(|pr| pr.url == target.pr)
1846        || run.pr_publication_pending
1847    {
1848        return None;
1849    }
1850    let safe_retry = decision.retry_safe
1851        && decision.request.as_deref() == Some("decision: merge")
1852        && q.resolution().as_deref() == Some(crate::land::APPROVE)
1853        && decision.source_answer_at.is_some()
1854        && decision.source_answer_at == q.answered_at;
1855    let unstarted = ((decision.request.is_none() && no_reply) || safe_retry)
1856        && !task.blocked_by.contains(&q.id)
1857        && task.status != TaskStatus::Held;
1858    let terminal = unstarted
1859        && task.status == TaskStatus::Done
1860        && matches!(
1861            run.status,
1862            crate::run::RunStatus::Merged | crate::run::RunStatus::Ready
1863        );
1864    let successor = if unstarted && q.status == crate::ask::QuestionStatus::Abandoned {
1865        superseding_approval(home, inquiry, &run, &target)
1866    } else {
1867        None
1868    };
1869    Some(ApprovalEvidence {
1870        target,
1871        terminal,
1872        successor,
1873    })
1874}
1875
1876fn superseding_approval(
1877    home: &Path,
1878    old: &crate::task_inquiry::Inquiry,
1879    run: &crate::run::RunState,
1880    target: &crate::merge_decision::Target,
1881) -> Option<(String, String)> {
1882    let binding = run.land_approval.as_ref()?;
1883    if binding.question == old.id || binding.head == target.head {
1884        return None;
1885    }
1886    let q = crate::ask::Questions::at(home.join("questions"))
1887        .read_history(&binding.question)
1888        .ok()?;
1889    if q.run != run.id
1890        || q.node != crate::land::APPROVAL_NODE
1891        || !q.status.open()
1892        || q.routed_task.as_ref().is_some_and(|task| task != &old.task)
1893        || !q
1894            .merge_target
1895            .as_ref()
1896            .is_some_and(|next| next.pr == target.pr && next.head == binding.head)
1897    {
1898        return None;
1899    }
1900    let next = crate::task_inquiry::Outbox::at(home).get(&q.id).ok()?;
1901    if next.task != old.task
1902        || next.repo != old.repo
1903        || next.run != old.run
1904        || next.key != format!("question:{}", q.id)
1905        || next
1906            .decision
1907            .as_ref()
1908            .is_none_or(|d| d.status == crate::task_decision::Status::Resolved)
1909    {
1910        return None;
1911    }
1912    Some((binding.question.clone(), binding.head.clone()))
1913}
1914
1915/// Finite retrospective scan. Forge observations are made before taking any
1916/// execution or queue claim, and never authorize a command.
1917pub(crate) async fn retire_obsolete_decisions(queue: &Queue, home: &Path) -> Result<()> {
1918    retire_obsolete_with(queue, home, |repo, pr| async move {
1919        observe_decision_pr(&repo, &pr).await
1920    })
1921    .await
1922}
1923
1924#[derive(serde::Serialize, serde::Deserialize)]
1925struct DecisionCursor {
1926    cursor: String,
1927    high_water: String,
1928}
1929
1930async fn retire_obsolete_with<F, Fut>(queue: &Queue, home: &Path, mut observe: F) -> Result<()>
1931where
1932    F: FnMut(std::path::PathBuf, String) -> Fut,
1933    Fut: Future<Output = Option<(String, String)>>,
1934{
1935    let outbox = crate::task_inquiry::Outbox::at(home);
1936    let (mut items, _) = outbox.list_readable()?;
1937    items.retain(|i| {
1938        i.decision
1939            .as_ref()
1940            .is_some_and(|d| d.status != crate::task_decision::Status::Resolved)
1941    });
1942    items.sort_by(|a, b| a.id.cmp(&b.id));
1943    let cursor_path = home.join("decision-reconcile-cursor");
1944    let Some(last) = items.last() else {
1945        return Ok(());
1946    };
1947    let fresh = || DecisionCursor {
1948        cursor: String::new(),
1949        high_water: last.id.clone(),
1950    };
1951    let mut cycle = std::fs::read(&cursor_path)
1952        .ok()
1953        .and_then(|body| serde_json::from_slice::<DecisionCursor>(&body).ok())
1954        .filter(|c| c.cursor <= c.high_water)
1955        .unwrap_or_else(fresh);
1956    let range = |cycle: &DecisionCursor| {
1957        items.partition_point(|i| i.id <= cycle.cursor)
1958            ..items.partition_point(|i| i.id <= cycle.high_water)
1959    };
1960    if range(&cycle).is_empty() {
1961        cycle = fresh();
1962    }
1963    let range = range(&cycle);
1964    let mut observations = std::collections::BTreeMap::new();
1965    for inquiry in items[range].iter().take(32) {
1966        if let Some(evidence) = approval_target(home, queue, inquiry) {
1967            let target = evidence.target;
1968            let key = (inquiry.repo.clone(), target.pr.clone());
1969            if !observations.contains_key(&key) {
1970                if observations.len() == 5 {
1971                    break;
1972                }
1973                let result = observe(key.0.clone(), key.1.clone()).await;
1974                observations.insert(key.clone(), result);
1975            }
1976            if let Ok(_execution) = outbox.execution_claim(&inquiry.id)
1977                && let Ok(_claim) = queue.claim(&inquiry.task)
1978                && let Ok(_task_write) = queue.lock_task(&inquiry.task)
1979                && let Some(run) = &inquiry.run
1980                && let Ok(_owner) = crate::pr_head::owner_lock(home, run)
1981            {
1982                let questions = crate::ask::Questions::at(home.join("questions"));
1983                if let Err(error) = questions.try_inspect_history(&inquiry.id, || {
1984                    let current = outbox.get(&inquiry.id)?;
1985                    if current != *inquiry {
1986                        return Ok(());
1987                    }
1988                    let Some(current_evidence) = approval_target(home, queue, &current) else {
1989                        return Ok(());
1990                    };
1991                    if current_evidence.target != target {
1992                        return Ok(());
1993                    }
1994                    let observed = observations.get(&key).and_then(Option::as_ref);
1995                    let observation = target_observation(&target, observed);
1996                    let reason = observed
1997                        .and_then(|(state, head)| current_evidence.obsolete_reason(state, head));
1998                    outbox.try_update_decision(&inquiry.id, |d| {
1999                        if current.decision.as_ref() != Some(d) {
2000                            return Ok(false);
2001                        }
2002                        let changed = d.observe(observation);
2003                        if let Some(reason) = reason {
2004                            return Ok(d.retire_target(&reason)? || changed);
2005                        }
2006                        Ok(changed)
2007                    })
2008                }) {
2009                    tracing::debug!("decision {} reconciliation deferred: {error:#}", inquiry.id);
2010                }
2011            }
2012        }
2013        let temporary = cursor_path.with_extension("tmp");
2014        cycle.cursor.clone_from(&inquiry.id);
2015        std::fs::write(&temporary, serde_json::to_vec(&cycle)?)?;
2016        std::fs::rename(temporary, &cursor_path)?;
2017    }
2018    Ok(())
2019}
2020
2021async fn observe_decision_pr(repo: &Path, pr: &str) -> Option<(String, String)> {
2022    let mut command = tokio::process::Command::new("gh");
2023    command
2024        .args(["pr", "view", pr, "--json", "url,state,headRefOid"])
2025        .current_dir(repo)
2026        .env_remove("GH_REPO")
2027        .stdin(std::process::Stdio::null())
2028        .kill_on_drop(true);
2029    let output = tokio::time::timeout(std::time::Duration::from_secs(5), command.output())
2030        .await
2031        .ok()?
2032        .ok()?;
2033    if !output.status.success() {
2034        return None;
2035    }
2036    let snapshot: serde_json::Value = serde_json::from_slice(&output.stdout).ok()?;
2037    let head = snapshot["headRefOid"].as_str()?;
2038    if snapshot["url"].as_str()? != pr || head.is_empty() {
2039        return None;
2040    }
2041    Some((snapshot["state"].as_str()?.to_owned(), head.to_owned()))
2042}
2043
2044fn target_observation(
2045    target: &crate::merge_decision::Target,
2046    observed: Option<&(String, String)>,
2047) -> crate::task_decision::TargetObservation {
2048    use crate::task_decision::{TargetObservation, TargetState};
2049    let state = match observed.map(|(state, _)| state.as_str()) {
2050        Some("OPEN") => TargetState::Open,
2051        Some("MERGED") => TargetState::Merged,
2052        Some("CLOSED") => TargetState::Closed,
2053        _ => TargetState::Unknown,
2054    };
2055    TargetObservation {
2056        pr: target.pr.clone(),
2057        target_head: target.head.clone(),
2058        head: observed.map(|(_, head)| head.clone()),
2059        state,
2060    }
2061}
2062
2063fn obsolete_pr_reason(
2064    state: &str,
2065    head: &str,
2066    target: &crate::merge_decision::Target,
2067) -> Option<String> {
2068    let outcome = match state {
2069        "MERGED" if head == target.head => "merged at the requested head",
2070        "MERGED" => "merged at a different head",
2071        _ => return None,
2072    };
2073    Some(format!(
2074        "Obsolete: {} is {outcome} (observed head {head}); no approval effect remains. This does not confirm application of a request.",
2075        target.pr
2076    ))
2077}
2078
2079#[cfg(test)]
2080#[test]
2081fn obsolete_pr_requires_terminal_forge_state() {
2082    let target = crate::merge_decision::Target {
2083        pr: "https://github.com/example/project/pull/42".into(),
2084        head: "old-head".into(),
2085        language: "en".into(),
2086    };
2087    assert!(obsolete_pr_reason("OPEN", "new-head", &target).is_none());
2088    assert!(obsolete_pr_reason("UNKNOWN", "old-head", &target).is_none());
2089    assert!(
2090        obsolete_pr_reason("MERGED", "old-head", &target)
2091            .unwrap()
2092            .contains("requested head")
2093    );
2094    assert!(
2095        obsolete_pr_reason("MERGED", "new-head", &target)
2096            .unwrap()
2097            .contains("different head")
2098    );
2099    assert!(obsolete_pr_reason("CLOSED", "old-head", &target).is_none());
2100}
2101
2102#[cfg(test)]
2103#[tokio::test]
2104async fn obsolete_approval_needs_original_run_and_unaccepted_source() {
2105    use crate::{
2106        ask::{Question, Questions},
2107        queue::Source,
2108        run::{RunState, RunStatus},
2109    };
2110    let tmp = tempfile::tempdir().unwrap();
2111    let home = tmp.path();
2112    let queue = Queue::at(home.join("queue"));
2113    let mut task = Task::new("work".into(), "work".into(), home.into(), Source::Human);
2114    task.status = TaskStatus::Done;
2115    queue.put(&mut task).unwrap();
2116    let mut run = RunState::new(
2117        home.into(),
2118        "main".into(),
2119        "base".into(),
2120        "work".into(),
2121        crate::config::Config::default(),
2122    );
2123    run.reserve_under(home).unwrap();
2124    let mut q = Question::new(
2125        run.id.clone(),
2126        crate::land::APPROVAL_NODE.into(),
2127        "land".into(),
2128        "Merge?".into(),
2129        String::new(),
2130        vec!["merge".into()],
2131    );
2132    let target = crate::merge_decision::Target {
2133        pr: "https://github.com/example/project/pull/42".into(),
2134        head: "old-head".into(),
2135        language: "en".into(),
2136    };
2137    q.merge_target = Some(target.clone());
2138    Questions::at(home.join("questions")).put(&mut q).unwrap();
2139    task.runs.push(run.id.clone());
2140    queue.put(&mut task).unwrap();
2141    let mut inquiry = crate::task_chat::live_record(home, &task, &q);
2142    assert!(approval_target(home, &queue, &inquiry).is_none());
2143    run.status = RunStatus::Merged;
2144    run.pr = Some(crate::run::PrRecord {
2145        url: target.pr.clone(),
2146        number: 42,
2147        state: "merged".into(),
2148        checks: "green".into(),
2149        round: 1,
2150        rounds: 1,
2151        red_at_merge: vec![],
2152    });
2153    run.save_under(home).unwrap();
2154    assert_eq!(
2155        approval_target(home, &queue, &inquiry),
2156        Some(ApprovalEvidence {
2157            target: target.clone(),
2158            terminal: true,
2159            successor: None
2160        })
2161    );
2162    let outbox = crate::task_inquiry::Outbox::at(home);
2163    let id = inquiry.id.clone();
2164    outbox.enqueue(inquiry.clone()).unwrap();
2165    retire_obsolete_with(&queue, home, |_, _| async { None })
2166        .await
2167        .unwrap();
2168    let observed = outbox.get(&id).unwrap().decision.unwrap();
2169    assert_eq!(
2170        observed.attention(false),
2171        crate::task_decision::Attention::ReceiptCheck
2172    );
2173    assert_ne!(observed.status, crate::task_decision::Status::Resolved);
2174    retire_obsolete_with(&queue, home, |_, _| async {
2175        Some(("CLOSED".into(), "old-head".into()))
2176    })
2177    .await
2178    .unwrap();
2179    let closed = outbox.get(&id).unwrap().decision.unwrap();
2180    assert_eq!(
2181        closed.attention(false),
2182        crate::task_decision::Attention::StaleTarget
2183    );
2184    assert!(!closed.source_retired);
2185    retire_obsolete_with(&queue, home, |_, _| async {
2186        Some(("OPEN".into(), "old-head".into()))
2187    })
2188    .await
2189    .unwrap();
2190    let reopened = outbox.get(&id).unwrap().decision.unwrap();
2191    assert_eq!(
2192        reopened.attention(false),
2193        crate::task_decision::Attention::OwnerChoice
2194    );
2195    assert!(!reopened.source_retired);
2196    retire_obsolete_with(&queue, home, |_, _| async {
2197        Some(("OPEN".into(), "new-head".into()))
2198    })
2199    .await
2200    .unwrap();
2201    let observed = outbox.get(&id).unwrap().decision.unwrap();
2202    assert_eq!(
2203        observed.attention(false),
2204        crate::task_decision::Attention::StaleTarget
2205    );
2206    assert_ne!(observed.status, crate::task_decision::Status::Resolved);
2207    let claim = outbox.execution_claim(&id).unwrap();
2208    retire_obsolete_with(&queue, home, |_, _| async {
2209        Some(("MERGED".into(), "new-head".into()))
2210    })
2211    .await
2212    .unwrap();
2213    assert_eq!(outbox.get(&id).unwrap().decision.unwrap(), observed);
2214    drop(claim);
2215    let question_lock = home.join("questions").join(format!("{id}.lock"));
2216    let leftover = std::fs::File::create(&question_lock).unwrap();
2217    retire_obsolete_with(&queue, home, |_, _| async {
2218        Some(("MERGED".into(), "new-head".into()))
2219    })
2220    .await
2221    .unwrap();
2222    assert_eq!(outbox.get(&id).unwrap().decision.unwrap(), observed);
2223    leftover
2224        .set_modified(std::time::SystemTime::now() - std::time::Duration::from_secs(60))
2225        .unwrap();
2226    drop(leftover);
2227    retire_obsolete_with(&Queue::at(home.join("queue")), home, |_, _| async {
2228        Some(("MERGED".into(), "new-head".into()))
2229    })
2230    .await
2231    .unwrap();
2232    let retired = outbox.get(&id).unwrap().decision.unwrap();
2233    assert_eq!(
2234        retired.closure,
2235        Some(crate::task_decision::Closure::Obsolete)
2236    );
2237    assert!(retired.source_retired);
2238    assert!(!question_lock.exists());
2239    assert!(
2240        Questions::at(home.join("questions"))
2241            .read_history(&q.id)
2242            .unwrap()
2243            .answer
2244            .is_none()
2245    );
2246    let questions = crate::ask::Questions::at(home.join("questions"));
2247    assert!(
2248        questions
2249            .update(&q.id, |q| q
2250                .answer(crate::ask::Answer::Choice("merge".into())))
2251            .is_err()
2252    );
2253    retire_obsolete_with(&queue, home, |_, _| async {
2254        panic!("resolved inquiry was queried again")
2255    })
2256    .await
2257    .unwrap();
2258    assert_eq!(outbox.get(&id).unwrap().decision.unwrap(), retired);
2259    inquiry
2260        .decision
2261        .as_mut()
2262        .unwrap()
2263        .accept("decision: merge")
2264        .unwrap();
2265    assert_eq!(
2266        approval_target(home, &queue, &inquiry),
2267        Some(ApprovalEvidence {
2268            target: target.clone(),
2269            terminal: false,
2270            successor: None
2271        })
2272    );
2273    let replacement = ApprovalEvidence {
2274        target: target.clone(),
2275        terminal: false,
2276        successor: Some(("successor".into(), "new-head".into())),
2277    };
2278    assert!(replacement.obsolete_reason("OPEN", "other-head").is_none());
2279    assert!(replacement.obsolete_reason("UNKNOWN", "new-head").is_none());
2280    assert!(
2281        replacement
2282            .obsolete_reason("OPEN", "new-head")
2283            .unwrap()
2284            .contains("successor")
2285    );
2286    // A finite high-water pass shares the same PR observation and resumes
2287    // from disk. One accepted effect and one missing target stay unresolved.
2288    let mut legacy = None;
2289    for index in 0..34 {
2290        let mut source = q.clone();
2291        source.id = format!("approval-{index:02}");
2292        if index == 1 {
2293            source
2294                .answer(crate::ask::Answer::Choice("merge".into()))
2295                .unwrap();
2296            legacy = Some(source.id.clone());
2297        }
2298        if index == 33 {
2299            source.merge_target = None;
2300        }
2301        questions.put(&mut source).unwrap();
2302        let mut record = crate::task_chat::live_record(home, &task, &source);
2303        if index == 0 {
2304            record
2305                .decision
2306                .as_mut()
2307                .unwrap()
2308                .accept("decision: merge")
2309                .unwrap();
2310        }
2311        if index == 1 {
2312            record
2313                .decision
2314                .as_mut()
2315                .unwrap()
2316                .fail("historical response has no receipt")
2317                .unwrap();
2318        }
2319        outbox.enqueue(record).unwrap();
2320    }
2321    let journal = home.join("notifications/task-chat-migration-v1");
2322    std::fs::create_dir_all(&journal).unwrap();
2323    std::fs::write(
2324        journal.join("state.json"),
2325        serde_json::to_vec(&serde_json::json!({
2326            "schema": 1, "pending": [], "sources": [legacy.unwrap()]
2327        }))
2328        .unwrap(),
2329    )
2330    .unwrap();
2331    let calls = std::cell::Cell::new(0);
2332    let observe = |_, _| {
2333        calls.set(calls.get() + 1);
2334        async { Some(("MERGED".into(), "old-head".into())) }
2335    };
2336    retire_obsolete_with(&queue, home, observe).await.unwrap();
2337    assert_eq!(calls.get(), 1);
2338    assert_eq!(
2339        outbox
2340            .list_readable()
2341            .unwrap()
2342            .0
2343            .iter()
2344            .filter(|i| i
2345                .decision
2346                .as_ref()
2347                .is_some_and(|d| d.status != crate::task_decision::Status::Resolved))
2348            .count(),
2349        3
2350    );
2351    retire_obsolete_with(&Queue::at(home.join("queue")), home, observe)
2352        .await
2353        .unwrap();
2354    assert_eq!(calls.get(), 2);
2355    let pending = outbox
2356        .list_readable()
2357        .unwrap()
2358        .0
2359        .into_iter()
2360        .filter(|i| {
2361            i.decision
2362                .as_ref()
2363                .is_some_and(|d| d.status != crate::task_decision::Status::Resolved)
2364        })
2365        .map(|i| i.id)
2366        .collect::<std::collections::BTreeSet<_>>();
2367    assert_eq!(
2368        pending,
2369        ["approval-00".into(), "approval-33".into()]
2370            .into_iter()
2371            .collect()
2372    );
2373    let legacy = questions.read_history("approval-01").unwrap();
2374    assert_eq!(legacy.resolution().as_deref(), Some("merge"));
2375    assert!(questions.held_reply("approval-01"));
2376    assert_eq!(
2377        outbox.get("approval-01").unwrap().decision.unwrap().closure,
2378        Some(crate::task_decision::Closure::Obsolete)
2379    );
2380}
2381
2382/// Repair the decision projection from independently durable command receipts.
2383/// This starts no workers and retries no operation.
2384pub fn reconcile_decisions(queue: &Queue, home: &Path) -> Result<()> {
2385    let outbox = crate::task_inquiry::Outbox::at(home);
2386    let (inquiries, unreadable) = outbox.list_readable()?;
2387    let mut errors = Vec::new();
2388    if unreadable != 0 {
2389        errors.push(format!("{unreadable} unreadable inquiry record(s)"));
2390    }
2391    for inquiry in inquiries {
2392        let id = inquiry.id.clone();
2393        let task_id = inquiry.task.clone();
2394        let before = inquiry.decision.clone();
2395        if let Err(error) = reconcile_inquiry(queue, home, &outbox, inquiry) {
2396            let message = format!(
2397                "Decision receipt reconciliation failed: {error:#}. Inspect this inquiry's receipt before retrying."
2398            );
2399            tracing::warn!("decision {id}: {message}");
2400            // Reacquire the consumer fence and compare the entire lifecycle:
2401            // an intervening retry, receipt or settlement owns its new state.
2402            if let Ok(_execution) = outbox.execution_claim(&id)
2403                && let Ok(_claim) = queue.claim(&task_id)
2404                && let Err(error) = outbox.try_update_decision(&id, |d| {
2405                    if before.as_ref() != Some(d)
2406                        || d.status == crate::task_decision::Status::Resolved
2407                    {
2408                        return Ok(false);
2409                    }
2410                    if d.retry_safe {
2411                        return d.fail_before_effect(&message);
2412                    }
2413                    d.fail(&message)
2414                })
2415            {
2416                tracing::warn!(
2417                    "decision {id} reconciliation error persistence deferred: {error:#}"
2418                );
2419            }
2420            errors.push(format!("{id}: {message}"));
2421        }
2422    }
2423    ensure!(
2424        errors.is_empty(),
2425        "{} decision reconciliation problem(s): {}",
2426        errors.len(),
2427        errors.join("; ")
2428    );
2429    Ok(())
2430}
2431
2432fn reconcile_inquiry(
2433    queue: &Queue,
2434    home: &Path,
2435    outbox: &crate::task_inquiry::Outbox,
2436    inquiry: crate::task_inquiry::Inquiry,
2437) -> Result<()> {
2438    use crate::task_decision::Status;
2439    let Some(decision) = inquiry.decision else {
2440        return Ok(());
2441    };
2442    if decision.status == Status::Resolved {
2443        return Ok(());
2444    }
2445    let Some(request) = decision.request else {
2446        return Ok(());
2447    };
2448    let Ok(command) = serde_json::from_str::<Operation>(&request) else {
2449        return Ok(());
2450    };
2451    if let Operation::Resume { run } = &command {
2452        return reconcile_resume_decision(queue, home, outbox, &inquiry.id, run);
2453    }
2454    let Ok(_execution) = outbox.execution_claim(&inquiry.id) else {
2455        return Ok(());
2456    };
2457    let Ok(_claim) = queue.claim(&inquiry.task) else {
2458        return Ok(());
2459    };
2460    let current = outbox.get(&inquiry.id)?;
2461    let Some(decision) = current.decision else {
2462        return Ok(());
2463    };
2464    if decision.status == Status::Resolved || decision.request.as_ref() != Some(&request) {
2465        return Ok(());
2466    }
2467    let task = queue.get(&inquiry.task)?;
2468    ensure!(task.repo == inquiry.repo, "decision repository changed");
2469    if let Some(receipt) = task.decision_effects.get(&inquiry.id) {
2470        ensure!(
2471            receipt == &request,
2472            "decision receipt binds another command"
2473        );
2474        outbox.update_decision(&inquiry.id, |d| {
2475            d.applied("exact task command receipt confirmed after restart")
2476        })?;
2477        return Ok(());
2478    }
2479    let mut pending_external = false;
2480    let receipt = match command {
2481        Operation::Abandon { run } => {
2482            abandonment_receipt(home, &task, &inquiry.id, &run, &request)?
2483                .then(|| format!("run {run}: exact abandonment receipt committed"))
2484        }
2485        Operation::RerunChecks {
2486            request,
2487            run,
2488            head,
2489            workflows,
2490        } => {
2491            let chat = inquiry.delivered_to.as_deref().unwrap_or_default();
2492            let path = home
2493                .join("chat-controls")
2494                .join(chat)
2495                .join(format!("{request}.json"));
2496            let state = crate::run::RunState::load_under(&run, home)?;
2497            let action = serde_json::json!({
2498                "run": run, "repo": state.repo,
2499                "pr": state.pr.as_ref().map(|pr| pr.url.as_str()),
2500                "head": head, "runs": workflows,
2501            });
2502            std::fs::read(path)
2503                .ok()
2504                .and_then(|bytes| serde_json::from_slice::<serde_json::Value>(&bytes).ok())
2505                .filter(|receipt| receipt["status"] == "applied" && receipt["action"] == action)
2506                .map(|_| format!("chat-controls/{chat}/{request}.json: applied"))
2507        }
2508        Operation::MergePr {
2509            repo,
2510            number,
2511            head,
2512            request,
2513        } => {
2514            let action = crate::chat_merge::Request {
2515                repo,
2516                number,
2517                head,
2518                request,
2519            };
2520            let chat = inquiry
2521                .delivered_to
2522                .as_deref()
2523                .context("merge decision has no chat")?;
2524            let receipt = merge_receipt(home, chat, &action)?;
2525            pending_external = receipt
2526                .as_ref()
2527                .is_some_and(|receipt| receipt["status"] == "pending");
2528            if let Some(receipt) = &receipt
2529                && receipt["status"] != "merged"
2530                && receipt["status"] != "pending"
2531            {
2532                outbox.update_decision(&inquiry.id, |d| d.fail(&format!("Merge outcome requires reconciliation: {}. Reuse the same request ID to check only.", receipt["detail"])))?;
2533            }
2534            receipt
2535                .filter(|receipt| receipt["status"] == "merged")
2536                .map(|receipt| format!("confirmed merge receipt: {}", receipt["detail"]))
2537        }
2538        _ => None,
2539    };
2540    if let Some(receipt) = receipt {
2541        outbox.update_decision(&inquiry.id, |d| d.applied(&receipt))?;
2542    } else if decision.status == Status::InProgress
2543        && !pending_external
2544        && outbox
2545            .get(&inquiry.id)?
2546            .decision
2547            .as_ref()
2548            .is_some_and(|d| d.status == Status::InProgress)
2549    {
2550        let talks = Talks::at(home.join("talks"));
2551        let chat = inquiry
2552            .delivered_to
2553            .as_deref()
2554            .context("executing decision has no chat")?;
2555        if !talks.turn_held(chat) && !crate::chat_worker::turn_worker_active(&talks, chat) {
2556            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."))?;
2557        }
2558    }
2559    Ok(())
2560}
2561
2562/// Record the owner's choice for a decision from an open standing chat. The
2563/// chat agent interprets the owner's request directly, a merge included; no
2564/// quote, consent phrase or task ownership is required. See [`record_decision`].
2565pub fn decide(
2566    talks: &Talks,
2567    home: &Path,
2568    talk: &str,
2569    question: &str,
2570    choice: &str,
2571) -> Result<crate::ask::Question> {
2572    authorize(talks, talk, crate::queue::CHAT_NODE)?;
2573    record_decision(home, question, choice, None)
2574}
2575
2576/// Answer an open decision whose answer the machinery consumes
2577/// ([`crate::task_chat::awaits_decision`]: a merge or release approval, the
2578/// posting gate, triage, a divergence reconcile, a structured choice action).
2579/// The question must still be open and `choice` one of its offered choices;
2580/// the consumer behind it keeps its own state and transition checks.
2581fn record_decision(
2582    home: &Path,
2583    question: &str,
2584    choice: &str,
2585    title: Option<&str>,
2586) -> Result<crate::ask::Question> {
2587    use crate::ask::{Answer, Questions};
2588    let questions = Questions::at(home.join("questions"));
2589    let id = questions.resolve_id(question)?;
2590    let q = questions.get(&id)?;
2591    let queue = Queue::at(home.join("queue"));
2592    let _claims = decision_claims(&queue, &q)?;
2593    for task in queue.list() {
2594        if q.run == task.id
2595            || task.runs.contains(&q.run)
2596            || q.routed_task.as_deref() == Some(&task.id)
2597        {
2598            ensure!(
2599                !task.stale_question(&q),
2600                "question predates task repository reassignment; inspect the current task and release it for fresh execution"
2601            );
2602        }
2603    }
2604    ensure!(
2605        crate::task_chat::awaits_decision(&q),
2606        "question {} is not a decision the machinery waits on; answer it with `magi answer`",
2607        q.short()
2608    );
2609    let (q, ()) = questions.update(&q.id, |r| {
2610        if crate::task_chat::saved_reply_requires_confirmation(home, r) {
2611            ensure!(
2612                crate::task_inquiry::Outbox::at(home)
2613                    .get(&r.id)?
2614                    .decision
2615                    .is_some_and(
2616                        |decision| decision.status != crate::task_decision::Status::Resolved
2617                    ),
2618                "saved decision is settled; no effect remains necessary"
2619            );
2620            r.status = crate::ask::QuestionStatus::Open;
2621            r.answer = None;
2622            r.answered_at = None;
2623            r.answer_authority = None;
2624        }
2625        ensure!(
2626            r.status.open(),
2627            "question {} is already {}",
2628            r.short(),
2629            r.status.as_str()
2630        );
2631        let reply = r.resolve_reply(choice)?.to_owned();
2632        ensure!(
2633            crate::land::approval(Some(&reply)) != crate::land::Approval::Merge || r.merge_target.is_some()
2634                || !(r.node == crate::land::APPROVAL_NODE || (r.node == crate::bump::NOTICE_NODE && r.seat == "release-watch")),
2635            "approval has no recorded PR/head; recover its target or discuss a non-merge operation in chat"
2636        );
2637        let replacement =
2638            r.node == crate::github_text::ASK_NODE && reply == crate::github_text::USE_MY_TEXT;
2639        ensure!(
2640            replacement || title.is_none(),
2641            "--title is only valid for a publication decision's `use my text` choice"
2642        );
2643        let title = if replacement {
2644            let title =
2645                title.context("use my text needs --title with the literal replacement title")?;
2646            ensure!(
2647                !title.trim().is_empty(),
2648                "replacement title must not be empty"
2649            );
2650            Some(title.to_owned())
2651        } else {
2652            None
2653        };
2654        let answer = if r.free_text() {
2655            Answer::Text(reply)
2656        } else {
2657            Answer::Choice(reply)
2658        };
2659        r.publication_title = title;
2660        r.answer(answer)?;
2661        Ok(())
2662    })?;
2663    Ok(q)
2664}
2665
2666/// Fence idle built-in triage answers with grant admission and worker writes.
2667/// Live drivers must remain answerable (grant admission refuses them). Other
2668/// question consumers keep their own claims, including synchronous dismissal.
2669/// Every grant also rechecks answered-but-unsettled effects before acceptance.
2670pub(crate) fn decision_claims(
2671    queue: &Queue,
2672    q: &crate::ask::Question,
2673) -> Result<Vec<crate::queue::Claim>> {
2674    let mut owners: Vec<_> = queue
2675        .list()
2676        .into_iter()
2677        .filter(|task| {
2678            q.run == task.id
2679                || task.runs.contains(&q.run)
2680                || q.routed_task.as_deref() == Some(&task.id)
2681        })
2682        .map(|task| task.id)
2683        .collect();
2684    owners.sort();
2685    let mut claims = Vec::new();
2686    if matches!(
2687        q.node.as_str(),
2688        crate::triage::NODE | crate::triage::DEPS_NODE
2689    ) {
2690        for id in &owners {
2691            if queue.get(id)?.status != TaskStatus::Running {
2692                claims.push(queue.claim(id)?);
2693            }
2694        }
2695    }
2696    for id in owners {
2697        ensure!(
2698            !crate::repair_budget::reconcile::superseded_question(&queue.get(&id)?, q),
2699            "question was superseded by explicit repair receipt recovery; inspect the reconciliation receipt"
2700        );
2701    }
2702    Ok(claims)
2703}
2704
2705/// The conversation this process speaks for, or why it may not act.
2706pub fn authorize(talks: &Talks, run: &str, node: &str) -> Result<Talk> {
2707    if node != crate::queue::CHAT_NODE || run.trim().is_empty() {
2708        bail!("task control requires MAGI_NODE=chat and MAGI_RUN from a standing chat");
2709    }
2710    let talk = talks.get(run)?;
2711    if talk.id != run || !talk.status.open() {
2712        bail!("task control requires the exact id of an open conversation");
2713    }
2714    Ok(talk)
2715}
2716
2717/// The task that recorded `run` (a full run id).
2718fn run_task(queue: &Queue, run: &str) -> Result<Task> {
2719    ensure!(
2720        crate::run::is_run_id(run),
2721        "an execution command needs the full run id"
2722    );
2723    queue
2724        .list()
2725        .into_iter()
2726        .find(|t| t.runs.iter().any(|r| r == run))
2727        .with_context(|| format!("run {run} belongs to no task"))
2728}
2729
2730/// Claim a task from a full or unambiguous-prefix id and read it under the
2731/// claim, never from a lookup made before it.
2732fn claimed(queue: &Queue, reference: &str) -> Result<(crate::queue::Claim, Task)> {
2733    let id = queue.resolve_id(reference)?;
2734    let claim = queue
2735        .claim(&id)
2736        .with_context(|| format!("task {id} is claimed by a running daemon"))?;
2737    let task = queue.get(&id)?;
2738    Ok((claim, task))
2739}
2740
2741fn claimed_for_chat(
2742    queue: &Queue,
2743    reference: &str,
2744    talks: &Talks,
2745    chat: &str,
2746) -> Result<(crate::queue::Claim, Task)> {
2747    let claimed = claimed(queue, reference)?;
2748    if let crate::chat_goal::Source::Goal { id, generation } = crate::chat_goal::current_source() {
2749        let talk = talks.get(chat)?;
2750        let goal = talk
2751            .goals
2752            .iter()
2753            .find(|goal| goal.id == id)
2754            .context("unknown goal")?;
2755        goal.admit(generation)?;
2756        let task = &claimed.1;
2757        ensure!(
2758            goal.tasks.contains(&task.id),
2759            "effect targets a task outside this goal"
2760        );
2761        crate::chat_goal::require_repo(
2762            "task",
2763            &task.id,
2764            &task.repo,
2765            goal.effective_repo(&talk.repo),
2766        )?;
2767    }
2768    Ok(claimed)
2769}
2770
2771fn check_hold_release(task: &Task, operation: &str) -> Result<()> {
2772    match task.status {
2773        TaskStatus::Queued
2774        | TaskStatus::Held
2775        | TaskStatus::Failed
2776        | TaskStatus::Blocked
2777        | TaskStatus::Parked => Ok(()),
2778        TaskStatus::Done => bail!(
2779            "cannot {operation} task {} (done): completed work must not be restarted; create a new task instead",
2780            task.id
2781        ),
2782        TaskStatus::Running => bail!(
2783            "cannot {operation} task {} (running): its run may still be active; use resume or abandon for the existing run instead",
2784            task.id
2785        ),
2786    }
2787}
2788
2789/// Mark a task complete as a terminal caller, using the audited close transition.
2790pub async fn done(
2791    queue: &Queue,
2792    home: &Path,
2793    reference: &str,
2794    reason: Option<String>,
2795    discard: bool,
2796) -> Result<Task> {
2797    crate::task_completion::close(
2798        queue,
2799        home,
2800        reference,
2801        crate::queue::CompletionActor::Cli,
2802        reason,
2803        discard,
2804    )
2805    .await
2806}
2807
2808/// Change priority under the same claim and state check as the terminal route.
2809pub fn set_priority(queue: &Queue, reference: &str, priority: i32) -> Result<Task> {
2810    priority_claimed(queue, claimed(queue, reference)?, priority)
2811}
2812
2813fn priority_claimed(
2814    queue: &Queue,
2815    (_claim, mut task): (crate::queue::Claim, Task),
2816    priority: i32,
2817) -> Result<Task> {
2818    task.set_priority(priority)?;
2819    queue.put(&mut task)?;
2820    Ok(task)
2821}
2822
2823/// Hold a task for the owner.
2824pub fn hold(queue: &Queue, reference: &str, reason: &str) -> Result<Task> {
2825    hold_claimed(queue, claimed(queue, reference)?, reason)
2826}
2827
2828fn hold_claimed(
2829    queue: &Queue,
2830    (_claim, mut task): (crate::queue::Claim, Task),
2831    reason: &str,
2832) -> Result<Task> {
2833    check_hold_release(&task, "hold")?;
2834    let reason = reason.trim();
2835    task.hold_manual((!reason.is_empty()).then(|| reason.to_owned()));
2836    queue.put(&mut task)?;
2837    Ok(task)
2838}
2839
2840/// Release a task (the same transition as `magi task release`: the attempt
2841/// count restarts, the history stays). An operator hold is released too: the
2842/// owner asked for it.
2843pub fn release(queue: &Queue, reference: &str) -> Result<Task> {
2844    release_claimed(queue, claimed(queue, reference)?)
2845}
2846
2847fn release_claimed(queue: &Queue, (_claim, mut task): (crate::queue::Claim, Task)) -> Result<Task> {
2848    check_hold_release(&task, "release")?;
2849    crate::base_sync_recovery::ensure_generic_release(queue, &task)?;
2850    let run = task.execution_runs().last().cloned();
2851    let preserved = match run {
2852        Some(run) => crate::repair_budget::queue_resumption(queue, &mut task, &run)?,
2853        None => false,
2854    };
2855    if !preserved {
2856        task.release_operator("chat", None);
2857    }
2858    queue.put(&mut task)?;
2859    Ok(task)
2860}
2861
2862/// Change a queued or held task's instruction and queue it again, in one
2863/// save under one claim. Only what [`Task::edit`] allows can be retried; the
2864/// attempt count follows [`Task::release`] (restarts), while runs, passes and
2865/// the resumption history are kept.
2866pub fn retry(
2867    queue: &Queue,
2868    reference: &str,
2869    title: Option<String>,
2870    instruction: &str,
2871) -> Result<Task> {
2872    retry_claimed(queue, claimed(queue, reference)?, title, instruction)
2873}
2874
2875fn retry_claimed(
2876    queue: &Queue,
2877    (_claim, mut task): (crate::queue::Claim, Task),
2878    title: Option<String>,
2879    instruction: &str,
2880) -> Result<Task> {
2881    ensure!(
2882        !instruction.trim().is_empty(),
2883        "the new instruction is empty"
2884    );
2885    if let Some(state) = crate::base_sync_recovery::held_run(queue, &task)
2886        && state
2887            .base_sync_recovery
2888            .stop
2889            .as_ref()
2890            .is_some_and(|stop| stop.kind == crate::base_sync_recovery::StopKind::Conflict)
2891    {
2892        anyhow::bail!(
2893            "retry cannot authorize editing a retained base-sync stop. {}",
2894            state.base_sync_next_action()
2895        );
2896    }
2897    crate::base_sync_recovery::ensure_generic_release(queue, &task)?;
2898    let title = title.unwrap_or_else(|| crate::queue::title_from(instruction, 72));
2899    task.edit(title, instruction.to_owned())?;
2900    task.release_operator("chat", None);
2901    queue.put(&mut task)?;
2902    Ok(task)
2903}
2904
2905/// Resume a stopped, blocked or parked run (its task's latest). Only queues
2906/// the pinned resume; returns the owning task.
2907pub fn resume(queue: &Queue, home: &Path, run: &str) -> Result<Task> {
2908    let task = run_task(queue, run)?;
2909    ensure!(
2910        task.execution_runs().last().map(String::as_str) == Some(run),
2911        "only the task's latest run can be resumed"
2912    );
2913    crate::resume::validate(home, run)?;
2914    ensure!(
2915        crate::resume::pin_queued(queue, run, None, None)?,
2916        "no queued task owns run {run}"
2917    );
2918    queue.get(&task.id)
2919}
2920
2921// These reads and input checks cannot start an effect. Keep them shared by
2922// decision acceptance and execution so invalid input never pins a new request.
2923fn rerun_preflight(
2924    queue: &Queue,
2925    home: &Path,
2926    run: &str,
2927    request: &str,
2928) -> Result<crate::run::RunState> {
2929    run_task(queue, run)?;
2930    let state = crate::run::RunState::load_under(run, home)?;
2931    ensure!(state.pr.is_some(), "the run recorded no pull request");
2932    ensure!(
2933        crate::ask::valid_asset_name(request),
2934        "request must be a safe filename of at most 64 bytes"
2935    );
2936    Ok(state)
2937}
2938
2939/// チャットのリクエスト単位で受付記録を残し、共通遷移でチェックを再実行する。
2940pub async fn rerun_checks(
2941    queue: &Queue,
2942    home: &Path,
2943    talk: &str,
2944    run: &str,
2945    request: &str,
2946    head: &str,
2947    workflows: &[String],
2948) -> Result<Vec<String>> {
2949    let state = rerun_preflight(queue, home, run, request).map_err(BeforeEffect)?;
2950    let dir = home.join("chat-controls").join(talk);
2951    std::fs::create_dir_all(&dir)?;
2952    let lock = std::fs::OpenOptions::new()
2953        .create(true)
2954        .truncate(false)
2955        .write(true)
2956        .open(dir.join(format!("{request}.lock")))?;
2957    crate::pr_head::try_lock_file(&lock).map_err(|error| BeforeEffect(error.into()))?;
2958    let path = dir.join(format!("{request}.json"));
2959    let pr = &state
2960        .pr
2961        .as_ref()
2962        .context("the run recorded no pull request")?
2963        .url;
2964    let action = serde_json::json!({
2965        "run": run, "repo": state.repo, "pr": pr, "head": head, "runs": workflows
2966    });
2967    if path.exists() {
2968        let prior: serde_json::Value = serde_json::from_slice(&std::fs::read(&path)?)?;
2969        if prior["action"] != action {
2970            return Err(BeforeEffect(anyhow::anyhow!(
2971                "request ID already binds a different operation"
2972            ))
2973            .into());
2974        }
2975        ensure!(
2976            prior["status"] == "applied",
2977            "previous request has an uncertain result; inspect its receipt before a new request"
2978        );
2979        return Ok(workflows.to_vec());
2980    }
2981    let record = |status: &str| -> Result<()> {
2982        let tmp = path.with_extension("tmp");
2983        std::fs::write(
2984            &tmp,
2985            serde_json::to_vec(&serde_json::json!({
2986                "action": action, "status": status
2987            }))?,
2988        )?;
2989        std::fs::rename(tmp, &path)?;
2990        Ok(())
2991    };
2992    let operation = format!("chat:{talk}:{request}");
2993    let started = std::sync::atomic::AtomicBool::new(false);
2994    crate::daemon::rerun_checks_once(home, &operation, &state.repo, pr, head, workflows, || {
2995        // Once a receipt exists, failure must remain uncertain even if the
2996        // external command has not returned yet.
2997        started.store(true, std::sync::atomic::Ordering::SeqCst);
2998        record("started")
2999    })
3000    .await
3001    .map_err(|error| {
3002        if started.load(std::sync::atomic::Ordering::SeqCst) {
3003            error
3004        } else {
3005            anyhow::Error::new(BeforeEffect(error))
3006        }
3007    })?;
3008    record("applied")?;
3009    Ok(workflows.to_vec())
3010}
3011
3012/// Abandon a recorded run whose driver is proven gone. No confirmation phrase
3013/// is needed; an unknown or live driver is refused by
3014/// [`crate::driver::abandon_proven_dead`], so a working driver is never broken.
3015pub fn abandon(queue: &Queue, home: &Path, run: &str) -> Result<()> {
3016    run_task(queue, run)?;
3017    crate::driver::abandon_proven_dead(home, run)
3018}
3019
3020/// One line a person or agent can read after a successful command.
3021pub fn describe(task: &Task, what: &str) -> String {
3022    let status = match task.status {
3023        TaskStatus::Queued => "queued",
3024        _ => task.status.as_str(),
3025    };
3026    format!("{what} {} {} ({status})", task.short(), task.title)
3027}
3028
3029#[cfg(test)]
3030mod tests {
3031    use super::*;
3032    use crate::queue::Source;
3033    use jiff::Timestamp;
3034
3035    fn talk(talks: &Talks, id: &str) -> Talk {
3036        let mut t: Talk = serde_json::from_value(serde_json::json!({
3037            "schema":1,"id":id,"repo":".","agent":"worker","status":"open","turns":[],
3038            "created_at":Timestamp::now(),"updated_at":Timestamp::now(),
3039            "seat":crate::agent::SeatState::new("talk","worker",1)
3040        }))
3041        .unwrap();
3042        talks.put(&mut t).unwrap();
3043        t
3044    }
3045
3046    fn filed(queue: &Queue, talk: &str, text: &str) -> Task {
3047        let mut t = Task::new(
3048            text.into(),
3049            text.into(),
3050            ".".into(),
3051            Source::Agent {
3052                run: talk.into(),
3053                node: crate::queue::CHAT_NODE.into(),
3054            },
3055        );
3056        queue.put(&mut t).unwrap();
3057        t
3058    }
3059
3060    #[tokio::test]
3061    async fn direct_chat_completion_supersedes_the_earlier_blocked_run() {
3062        use crate::run::{RunState, RunStatus};
3063
3064        let dir = tempfile::tempdir().unwrap();
3065        let home = dir.path();
3066        let talks = Talks::at(home.join("talks"));
3067        let queue = Queue::at(home.join("queue"));
3068        let talk = talk(&talks, "talk-a");
3069        let mut task = filed(&queue, &talk.id, "deliver");
3070        for status in [RunStatus::Blocked, RunStatus::Merged] {
3071            let mut run = RunState::new(
3072                task.repo.clone(),
3073                "main".into(),
3074                "base".into(),
3075                task.instruction.clone(),
3076                crate::config::Config::default(),
3077            );
3078            run.status = status;
3079            if status == RunStatus::Merged {
3080                run.merge = Some(crate::run::MergeOutcome {
3081                    mode: crate::config::MergeMode::Pr,
3082                    ok: true,
3083                    detail: "merged".into(),
3084                    empty: false,
3085                });
3086            }
3087            run.driver_exited = true;
3088            run.reserve_under(home).unwrap();
3089            task.link_run(&run.id);
3090        }
3091        queue.put(&mut task).unwrap();
3092        execute(
3093            &queue,
3094            home,
3095            &talks,
3096            &talk.id,
3097            Operation::Done {
3098                task: task.id.clone(),
3099                reason: None,
3100                result: None,
3101                discard: false,
3102            },
3103        )
3104        .await
3105        .unwrap();
3106        assert_eq!(
3107            RunState::load_under(&task.runs[0], home).unwrap().status,
3108            RunStatus::Superseded
3109        );
3110    }
3111
3112    #[test]
3113    fn ownerless_import_reconciliation_requires_effect_evidence_not_saved_consent() {
3114        use crate::ask::{Answer, Question, Questions};
3115        let home = tempfile::tempdir().unwrap();
3116        let home = home.path();
3117        let queue = Queue::at(home.join("queue"));
3118        let talks = Talks::at(home.join("talks"));
3119        let questions = Questions::at(home.join("questions"));
3120        let mut q = Question::new(
3121            String::new(),
3122            crate::bump::NOTICE_NODE.into(),
3123            "release-watch".into(),
3124            "Historical release hold".into(),
3125            String::new(),
3126            vec!["hold".into()],
3127        );
3128        q.answer(Answer::Choice("hold".into())).unwrap();
3129        q.answer_delivered = true;
3130        questions.put(&mut q).unwrap();
3131        let source = std::fs::read(questions.path_of(&q.id)).unwrap();
3132        crate::task_chat::sweep(&queue, &talks, &questions, home);
3133        assert!(reconcile_task_decision(&queue, home, "authorized-chat", &q.id).is_err());
3134        let outbox = crate::task_inquiry::Outbox::at(home);
3135        assert_eq!(
3136            outbox.get(&q.id).unwrap().decision.unwrap().status,
3137            crate::task_decision::Status::RetryNeeded
3138        );
3139        let dir = home.join("release-watch-receipts");
3140        std::fs::create_dir_all(&dir).unwrap();
3141        std::fs::write(
3142            dir.join(format!("{}.json", q.id)),
3143            serde_json::to_vec(&crate::release_watch::WatchState {
3144                applied: vec![q.id.clone()],
3145                ..Default::default()
3146            })
3147            .unwrap(),
3148        )
3149        .unwrap();
3150        for _ in 0..2 {
3151            reconcile_task_decision(&queue, home, "authorized-chat", &q.id).unwrap();
3152        }
3153        let decision = outbox.get(&q.id).unwrap().decision.unwrap();
3154        assert_eq!(decision.status, crate::task_decision::Status::Resolved);
3155        assert!(decision.request.is_none());
3156        assert!(decision.source_answer_at.is_none());
3157        assert_eq!(std::fs::read(questions.path_of(&q.id)).unwrap(), source);
3158        assert!(queue.list().is_empty());
3159        assert!(talks.list().is_empty());
3160    }
3161
3162    #[test]
3163    fn receipt_reconciliation_error_is_visible_after_restart() {
3164        use crate::task_decision::{Attention, Status};
3165        let tmp = tempfile::tempdir().unwrap();
3166        let home = tmp.path();
3167        let queue = Queue::at(home.join("queue"));
3168        let task = filed(&queue, "talk-a", "work");
3169        let outbox = crate::task_inquiry::Outbox::at(home);
3170        let inquiry = outbox
3171            .file(&task, None, "merge".into(), "Merge?", "")
3172            .unwrap();
3173        let request = serde_json::to_string(&Operation::MergePr {
3174            repo: "example/project".into(),
3175            number: 42,
3176            head: "head".into(),
3177            request: "request-a".into(),
3178        })
3179        .unwrap();
3180        outbox
3181            .update_decision(&inquiry.id, |d| {
3182                d.accept(&request)?;
3183                d.start()
3184            })
3185            .unwrap();
3186        // No delivered chat: receipt ownership cannot be established.
3187        assert!(reconcile_decisions(&queue, home).is_err());
3188        let failed = outbox.get(&inquiry.id).unwrap().decision.unwrap();
3189        assert_eq!(failed.status, Status::RetryNeeded);
3190        assert_eq!(failed.attention(false), Attention::ReceiptCheck);
3191        assert!(
3192            failed
3193                .error
3194                .as_deref()
3195                .unwrap()
3196                .contains("merge decision has no chat")
3197        );
3198        assert_eq!(failed.request.as_deref(), Some(request.as_str()));
3199        assert!(!failed.retry_safe);
3200        assert!(reconcile_decisions(&queue, home).is_err());
3201        assert_eq!(outbox.get(&inquiry.id).unwrap().decision.unwrap(), failed);
3202    }
3203
3204    #[test]
3205    fn resume_recovery_waits_for_the_inquiry_publisher() {
3206        let tmp = tempfile::tempdir().unwrap();
3207        let queue = Queue::at(tmp.path().join("queue"));
3208        let mut task = filed(&queue, "talk-a", "work");
3209        let mut state = crate::run::RunState::new(
3210            task.repo.clone(),
3211            "main".into(),
3212            "base".into(),
3213            "work".into(),
3214            crate::config::Config::default(),
3215        );
3216        state.status = crate::run::RunStatus::Blocked;
3217        state.driver_exited = true;
3218        state.save_under(tmp.path()).unwrap();
3219        task.runs.push(state.id.clone());
3220        queue.put(&mut task).unwrap();
3221        let outbox = crate::task_inquiry::Outbox::at(tmp.path());
3222        let inquiry = outbox
3223            .file(
3224                &task,
3225                Some(state.id.clone()),
3226                "resume".into(),
3227                "Resume?",
3228                "",
3229            )
3230            .unwrap();
3231        let request = serde_json::to_string(&Operation::Resume {
3232            run: state.id.clone(),
3233        })
3234        .unwrap();
3235        outbox
3236            .update_decision(&inquiry.id, |d| {
3237                d.accept(&request)?;
3238                d.start()
3239            })
3240            .unwrap();
3241        let before = outbox.get(&inquiry.id).unwrap().decision.unwrap();
3242        let publisher = outbox.execution_claim(&inquiry.id).unwrap();
3243        reconcile_decisions(&queue, tmp.path()).unwrap();
3244        assert_eq!(outbox.get(&inquiry.id).unwrap().decision.unwrap(), before);
3245        drop(publisher);
3246        reconcile_decisions(&queue, tmp.path()).unwrap();
3247        let recovered = outbox.get(&inquiry.id).unwrap().decision.unwrap();
3248        assert_eq!(recovered.status, crate::task_decision::Status::RetryNeeded);
3249        assert!(recovered.retry_safe);
3250    }
3251
3252    #[tokio::test]
3253    async fn resume_receipt_matches_checkout_root_not_filing_directory() {
3254        use crate::task_decision::Status;
3255        let tmp = tempfile::tempdir().unwrap();
3256        let home = tmp.path();
3257        let repo = home.join("checkout");
3258        let subdir = repo.join("src");
3259        let foreign = home.join("foreign");
3260        std::fs::create_dir_all(&subdir).unwrap();
3261        std::fs::create_dir(&foreign).unwrap();
3262        for checkout in [&repo, &foreign] {
3263            crate::git::git(checkout, &["init", "-q"]).await.unwrap();
3264        }
3265        let queue = Queue::at(home.join("queue"));
3266        let mut task = Task::new("work".into(), "work".into(), subdir, Source::Human);
3267        let mut state = crate::run::RunState::new(
3268            repo,
3269            "main".into(),
3270            "base".into(),
3271            "work".into(),
3272            crate::config::Config::default(),
3273        );
3274        state.reserve_under(home).unwrap();
3275        task.runs.push(state.id.clone());
3276        queue.put(&mut task).unwrap();
3277        let outbox = crate::task_inquiry::Outbox::at(home);
3278        let inquiry = outbox
3279            .file(
3280                &task,
3281                Some(state.id.clone()),
3282                "resume".into(),
3283                "Resume?",
3284                "",
3285            )
3286            .unwrap();
3287        let request = serde_json::to_string(&Operation::Resume {
3288            run: state.id.clone(),
3289        })
3290        .unwrap();
3291        outbox
3292            .update_decision(&inquiry.id, |d| {
3293                d.accept(&request)?;
3294                d.start()
3295            })
3296            .unwrap();
3297        task.dispatched_resumes
3298            .insert(inquiry.id.clone(), state.id.clone());
3299        queue.put(&mut task).unwrap();
3300        reconcile_decisions(&queue, home).unwrap();
3301        assert_eq!(
3302            outbox.get(&inquiry.id).unwrap().decision.unwrap().status,
3303            Status::InProgress
3304        );
3305
3306        state.carry_dispatched_resumes(&task);
3307        state.begin_pass();
3308        state.save_under(home).unwrap();
3309        let mut reassigned = task.clone();
3310        reassigned.repo = foreign;
3311        assert!(resume_started(home, &reassigned, &inquiry.id, &state.id).is_err());
3312        reconcile_decisions(&queue, home).unwrap();
3313        assert_eq!(
3314            outbox.get(&inquiry.id).unwrap().decision.unwrap().status,
3315            Status::Resolved
3316        );
3317    }
3318
3319    #[test]
3320    fn only_the_chat_seat_of_an_open_talk_is_authorized() {
3321        let tmp = tempfile::tempdir().unwrap();
3322        let talks = Talks::at(tmp.path().join("talks"));
3323        let t = talk(&talks, "talk-a");
3324        assert!(authorize(&talks, &t.id, "chat").is_ok());
3325        assert!(authorize(&talks, &t.id, "deputy").is_err());
3326        assert!(authorize(&talks, &t.id, "").is_err());
3327        assert!(authorize(&talks, "", "chat").is_err());
3328        assert!(
3329            authorize(&talks, "talk-", "chat").is_err(),
3330            "prefix is not an id"
3331        );
3332    }
3333
3334    #[test]
3335    fn tasks_of_any_origin_are_controlled_on_request() {
3336        let tmp = tempfile::tempdir().unwrap();
3337        let queue = Queue::at(tmp.path().join("queue"));
3338        let theirs = filed(&queue, "talk-b", "theirs");
3339        let mut hand = Task::new("h".into(), "h".into(), ".".into(), Source::Human);
3340        hand.hold_manual(Some("operator".into()));
3341        queue.put(&mut hand).unwrap();
3342        // Another chat's task and an operator-held human task are the owner's
3343        // work too: the request goes through without any ownership scope.
3344        assert_eq!(
3345            hold(&queue, &theirs.id, "wait").unwrap().status,
3346            TaskStatus::Held
3347        );
3348        assert_eq!(
3349            release(&queue, &hand.id).unwrap().status,
3350            TaskStatus::Queued
3351        );
3352        let again = retry(&queue, &theirs.id, None, "new").unwrap();
3353        assert_eq!(again.instruction, "new");
3354        assert_eq!(again.status, TaskStatus::Queued);
3355    }
3356
3357    #[test]
3358    fn hold_then_release_keeps_history_and_restarts_attempts() {
3359        let tmp = tempfile::tempdir().unwrap();
3360        let queue = Queue::at(tmp.path().join("queue"));
3361        let mut t = filed(&queue, "talk-a", "work");
3362        t.attempts = 3;
3363        t.runs.push("20260101-000000-aaaa".into());
3364        queue.put(&mut t).unwrap();
3365        let held = hold(&queue, &t.id, "owner asked").unwrap();
3366        assert_eq!(held.status, TaskStatus::Held);
3367        assert_eq!(held.hold_reason.as_deref(), Some("owner asked"));
3368        let back = release(&queue, &t.id).unwrap();
3369        assert_eq!(back.status, TaskStatus::Queued);
3370        assert_eq!(back.attempts, 0);
3371        assert_eq!(back.runs, t.runs);
3372        assert!(back.resumption.is_some());
3373    }
3374
3375    #[test]
3376    fn hold_and_release_refuse_done_and_running_without_saving() {
3377        let tmp = tempfile::tempdir().unwrap();
3378        let queue = Queue::at(tmp.path().join("queue"));
3379        for status in [TaskStatus::Done, TaskStatus::Running] {
3380            let mut t = filed(&queue, "talk-a", "work");
3381            t.start("20260101-000000-aaaa".into());
3382            if status == TaskStatus::Done {
3383                t.succeed(crate::queue::CompletionContext::new(
3384                    crate::queue::CompletionActor::Cli,
3385                    None,
3386                    tmp.path(),
3387                    &t,
3388                ));
3389            }
3390            queue.put(&mut t).unwrap();
3391            let before = std::fs::read(queue.path_of(&t.id)).unwrap();
3392            for operation in ["hold", "release"] {
3393                let error = if operation == "hold" {
3394                    hold(&queue, &t.id, "owner asked")
3395                } else {
3396                    release(&queue, &t.id)
3397                }
3398                .unwrap_err()
3399                .to_string();
3400                assert!(error.contains(operation), "{error}");
3401                assert!(error.contains(&t.id), "{error}");
3402                assert!(error.contains(status.as_str()), "{error}");
3403                let guidance = if status == TaskStatus::Done {
3404                    "create a new task"
3405                } else {
3406                    "use resume or abandon"
3407                };
3408                assert!(error.contains(guidance), "{error}");
3409                assert_eq!(std::fs::read(queue.path_of(&t.id)).unwrap(), before);
3410            }
3411        }
3412    }
3413
3414    #[test]
3415    fn hold_and_release_allow_unfinished_inactive_tasks() {
3416        let tmp = tempfile::tempdir().unwrap();
3417        let queue = Queue::at(tmp.path().join("queue"));
3418        for status in [
3419            TaskStatus::Queued,
3420            TaskStatus::Held,
3421            TaskStatus::Failed,
3422            TaskStatus::Blocked,
3423            TaskStatus::Parked,
3424        ] {
3425            for operation in ["hold", "release"] {
3426                let mut t = filed(&queue, "talk-a", "work");
3427                t.status = status;
3428                t.hold_reason = Some("old reason".into());
3429                t.attempts = 3;
3430                t.runs.push("20260101-000000-aaaa".into());
3431                queue.put(&mut t).unwrap();
3432                let changed = if operation == "hold" {
3433                    let held = hold(&queue, &t.id, " new reason ").unwrap();
3434                    assert_eq!(held.status, TaskStatus::Held);
3435                    assert_eq!(held.hold_reason.as_deref(), Some("new reason"));
3436                    assert_eq!(held.attempts, t.attempts);
3437                    held
3438                } else {
3439                    let released = release(&queue, &t.id).unwrap();
3440                    assert_eq!(released.status, TaskStatus::Queued);
3441                    assert_eq!(released.attempts, 0);
3442                    assert_eq!(released.resumption.as_ref().unwrap().source, "chat");
3443                    released
3444                };
3445                assert_eq!(changed.runs, t.runs);
3446                assert_eq!(queue.get(&t.id).unwrap().status, changed.status);
3447            }
3448        }
3449    }
3450
3451    #[test]
3452    fn retry_edits_and_requeues_in_one_save() {
3453        let tmp = tempfile::tempdir().unwrap();
3454        let queue = Queue::at(tmp.path().join("queue"));
3455        let mut t = filed(&queue, "talk-a", "old text");
3456        t.runs.push("20260101-000000-aaaa".into());
3457        t.attempts = 2;
3458        t.hold_manual(Some("stopped".into()));
3459        queue.put(&mut t).unwrap();
3460        let again = retry(&queue, &t.id, None, "new text").unwrap();
3461        assert_eq!(again.instruction, "new text");
3462        assert_eq!(again.status, TaskStatus::Queued);
3463        assert_eq!(again.attempts, 0);
3464        assert_eq!(again.runs, t.runs, "run history is kept");
3465        assert_eq!(again.resumption.as_ref().unwrap().source, "chat");
3466        assert_eq!(again.resumption.as_ref().unwrap().instruction, "new text");
3467        // A running task cannot be edited: nothing is changed.
3468        let mut running = filed(&queue, "talk-a", "busy");
3469        running.start("20260101-000000-bbbb".into());
3470        queue.put(&mut running).unwrap();
3471        assert!(retry(&queue, &running.id, None, "x").is_err());
3472        assert_eq!(queue.get(&running.id).unwrap().instruction, "busy");
3473        assert!(retry(&queue, &t.id, None, "  ").is_err());
3474    }
3475
3476    #[test]
3477    fn execution_commands_need_the_full_id_of_a_recorded_run() {
3478        let tmp = tempfile::tempdir().unwrap();
3479        let queue = Queue::at(tmp.path().join("queue"));
3480        let mut t = filed(&queue, "talk-b", "work");
3481        t.runs.push("20260101-000000-aaaa".into());
3482        queue.put(&mut t).unwrap();
3483        assert_eq!(
3484            run_task(&queue, "20260101-000000-aaaa").unwrap().id,
3485            t.id,
3486            "any chat may address another chat's run"
3487        );
3488        assert!(run_task(&queue, "aaaa").is_err());
3489        assert!(run_task(&queue, "20260101-000000-bbbb").is_err());
3490        assert!(resume(&queue, tmp.path(), "aaaa").is_err());
3491    }
3492
3493    #[test]
3494    fn abandon_needs_no_phrase_but_refuses_unrecorded_and_unknown_runs() {
3495        let tmp = tempfile::tempdir().unwrap();
3496        let queue = Queue::at(tmp.path().join("queue"));
3497        let mut t = filed(&queue, "talk-b", "work");
3498        t.runs.push("20260101-000000-aaaa".into());
3499        queue.put(&mut t).unwrap();
3500        // A run no task recorded is refused before liveness is judged.
3501        assert!(abandon(&queue, tmp.path(), "20260101-000000-bbbb").is_err());
3502        // A recorded run whose driver is not proven dead (here: no state to
3503        // judge at all) is never abandoned.
3504        assert!(abandon(&queue, tmp.path(), "20260101-000000-aaaa").is_err());
3505    }
3506}
3507
3508#[cfg(test)]
3509mod goal_admission_tests {
3510    use super::*;
3511
3512    #[tokio::test]
3513    async fn goal_effects_require_current_generation_scope_and_no_new_owner_input() {
3514        let tmp = tempfile::tempdir().unwrap();
3515        let talks = Talks::at(tmp.path().join("talks"));
3516        let queue = Queue::at(tmp.path().join("queue"));
3517        let target = tmp.path().join("target");
3518        std::fs::create_dir(&target).unwrap();
3519        crate::git::git(&target, &["init", "-q"]).await.unwrap();
3520        let mut talk = crate::talk::seeded_for_test("goal-effect", tmp.path().into());
3521        talk.turns.push(
3522            serde_json::from_value(serde_json::json!({
3523                "sender": "operator", "who": "operator", "body": "Follow this task through",
3524                "at": jiff::Timestamp::now()
3525            }))
3526            .unwrap(),
3527        );
3528        talks.put(&mut talk).unwrap();
3529        let mut task = Task::new(
3530            "work".into(),
3531            "work".into(),
3532            target.clone(),
3533            crate::queue::Source::Agent {
3534                run: talk.id.clone(),
3535                node: crate::queue::CHAT_NODE.into(),
3536            },
3537        );
3538        queue.put(&mut task).unwrap();
3539        let mut unrelated = Task::new(
3540            "other".into(),
3541            "other".into(),
3542            target.clone(),
3543            crate::queue::Source::Agent {
3544                run: talk.id.clone(),
3545                node: crate::queue::CHAT_NODE.into(),
3546            },
3547        );
3548        queue.put(&mut unrelated).unwrap();
3549        crate::chat_goal::apply(
3550            &queue,
3551            tmp.path(),
3552            &talks,
3553            &talk.id,
3554            &crate::chat_goal::Source::Input { turn: 0 },
3555            crate::chat_goal::Command::Establish {
3556                id: "g".into(),
3557                purpose: "Deliver this task".into(),
3558                scope: "This task only".into(),
3559                condition: "Verified delivery".into(),
3560                completion: crate::chat_goal::Completion::TasksDone,
3561                repo: Some(target),
3562                tasks: vec![task.id.clone()],
3563                runs: vec![],
3564                watches: vec![],
3565            },
3566        )
3567        .await
3568        .unwrap();
3569        talks
3570            .mutate(&talk.id, |talk| {
3571                let boundary = talk.turns.len();
3572                let goal = &mut talk.goals[0];
3573                goal.wake = 1;
3574                goal.started = Some(1);
3575                goal.launch_turns = Some(boundary);
3576                Ok(())
3577            })
3578            .unwrap();
3579        let source = crate::chat_goal::Source::Goal {
3580            id: "g".into(),
3581            generation: 1,
3582        };
3583        assert!(
3584            execute_authenticated(
3585                &queue,
3586                tmp.path(),
3587                &talks,
3588                &talk.id,
3589                source.clone(),
3590                Operation::Priority {
3591                    task: unrelated.id.clone(),
3592                    priority: 8
3593                }
3594            )
3595            .await
3596            .is_err()
3597        );
3598        execute_authenticated(
3599            &queue,
3600            tmp.path(),
3601            &talks,
3602            &talk.id,
3603            source.clone(),
3604            Operation::Priority {
3605                task: task.id.clone(),
3606                priority: 3,
3607            },
3608        )
3609        .await
3610        .unwrap();
3611        let hold = Operation::Hold {
3612            task: task.id.clone(),
3613            reason: "pause".into(),
3614        };
3615        crate::chat_goal::with_source(source.clone(), async {
3616            // Reassignment publishes under this same claim, between the first
3617            // admission and the mutation's claim acquisition.
3618            admit_goal_operation(&queue, tmp.path(), &talks, &talk.id, &hold).unwrap();
3619            let original = task.repo.clone();
3620            {
3621                let claim = queue.claim(&task.id).unwrap();
3622                task = queue.get(&task.id).unwrap();
3623                task.repo = talk.repo.clone();
3624                queue.put(&mut task).unwrap();
3625                drop(claim);
3626            }
3627            let result = claimed_for_chat(&queue, &task.id, &talks, &talk.id)
3628                .and_then(|claimed| hold_claimed(&queue, claimed, "pause"));
3629            assert!(result.unwrap_err().to_string().contains(&task.id));
3630            assert_eq!(queue.get(&task.id).unwrap().status, TaskStatus::Queued);
3631            task.repo = original;
3632            queue.put(&mut task).unwrap();
3633        })
3634        .await;
3635        let error = execute_authenticated(
3636            &queue,
3637            tmp.path(),
3638            &talks,
3639            &talk.id,
3640            source.clone(),
3641            Operation::Done {
3642                task: task.id.clone(),
3643                reason: Some("discard unfinished work".into()),
3644                result: None,
3645                discard: true,
3646            },
3647        )
3648        .await
3649        .unwrap_err();
3650        assert!(
3651            error.to_string().contains("explicit owner turn"),
3652            "{error:#}"
3653        );
3654        assert_eq!(queue.get(&task.id).unwrap().status, TaskStatus::Queued);
3655        assert!(queue.get(&task.id).unwrap().completion_history.is_empty());
3656        assert!(
3657            execute_authenticated(
3658                &queue,
3659                tmp.path(),
3660                &talks,
3661                &talk.id,
3662                source.clone(),
3663                Operation::Done {
3664                    task: unrelated.id.clone(),
3665                    reason: None,
3666                    result: None,
3667                    discard: false,
3668                },
3669            )
3670            .await
3671            .is_err()
3672        );
3673        // Goal task completion requires a confirmed landing or investigation findings.
3674        // Mark as an investigation so the subsequent reopen check in this test has no
3675        // merged run blocking reopen.
3676        queue
3677            .modify(&task.id, |t| {
3678                t.investigation = true;
3679                true
3680            })
3681            .unwrap();
3682        execute_authenticated(
3683            &queue,
3684            tmp.path(),
3685            &talks,
3686            &talk.id,
3687            source.clone(),
3688            Operation::Done {
3689                task: task.id.clone(),
3690                reason: Some("goal work finished".into()),
3691                result: Some("goal findings recorded".into()),
3692                discard: false,
3693            },
3694        )
3695        .await
3696        .unwrap();
3697        let error = execute_authenticated(
3698            &queue,
3699            tmp.path(),
3700            &talks,
3701            &talk.id,
3702            source.clone(),
3703            Operation::Reopen {
3704                task: task.id.clone(),
3705                reason: "recover unfinished work".into(),
3706            },
3707        )
3708        .await
3709        .unwrap_err();
3710        assert!(
3711            error.to_string().contains("explicit owner turn"),
3712            "{error:#}"
3713        );
3714        assert_eq!(queue.get(&task.id).unwrap().status, TaskStatus::Done);
3715        execute_authenticated(
3716            &queue,
3717            tmp.path(),
3718            &talks,
3719            &talk.id,
3720            crate::chat_goal::Source::Input { turn: 0 },
3721            Operation::Reopen {
3722                task: task.id.clone(),
3723                reason: "recover unfinished work".into(),
3724            },
3725        )
3726        .await
3727        .unwrap();
3728        assert_eq!(queue.get(&task.id).unwrap().status, TaskStatus::Held);
3729        talks
3730            .mutate(&talk.id, |talk| {
3731                talk.turns.push(serde_json::from_value(serde_json::json!({
3732                    "sender": "operator", "who": "operator", "body": "Stop",
3733                    "at": jiff::Timestamp::now()
3734                }))?);
3735                Ok(())
3736            })
3737            .unwrap();
3738        assert!(
3739            execute_authenticated(
3740                &queue,
3741                tmp.path(),
3742                &talks,
3743                &talk.id,
3744                source.clone(),
3745                Operation::Priority {
3746                    task: task.id.clone(),
3747                    priority: 9
3748                }
3749            )
3750            .await
3751            .is_err()
3752        );
3753        talks
3754            .mutate(&talk.id, |talk| {
3755                talk.turns.pop();
3756                talk.goals[0].state = crate::chat_goal::State::Stopped;
3757                talk.goals[0].wake = 2;
3758                talk.goals[0].started = None;
3759                Ok(())
3760            })
3761            .unwrap();
3762        assert!(
3763            execute_authenticated(
3764                &queue,
3765                tmp.path(),
3766                &talks,
3767                &talk.id,
3768                source,
3769                Operation::Priority {
3770                    task: task.id.clone(),
3771                    priority: 9
3772                }
3773            )
3774            .await
3775            .is_err()
3776        );
3777        assert_eq!(queue.get(&task.id).unwrap().priority, 3);
3778    }
3779
3780    #[tokio::test]
3781    async fn land_sync_recovery_chat_control_requires_explicit_owner_input() {
3782        let tmp = tempfile::tempdir().unwrap();
3783        let home = tmp.path();
3784        let queue = Queue::at(home.join("queue"));
3785        let talks = Talks::at(home.join("talks"));
3786        let repo = home.join("repo");
3787        std::fs::create_dir(&repo).unwrap();
3788        let mut config = crate::config::Config::default();
3789        config.agents.push(crate::config::AgentSpec {
3790            id: "fixture".into(),
3791            kind: crate::config::AgentKind::Command,
3792            model: None,
3793            command: vec!["true".into()],
3794            extra_args: vec![],
3795            env: Default::default(),
3796            prompt_delivery: None,
3797            max_turn_secs: None,
3798        });
3799        let talk = crate::talk::begin(&talks, &config, repo, Some("fixture")).unwrap();
3800
3801        let make_op = || Operation::RecoverLandSync {
3802            run: "20261127-125940-3ce0".into(),
3803            head: "a".repeat(40),
3804            request: "req-chat-guard".into(),
3805        };
3806
3807        // Automatic turn without owner input must be refused.
3808        let err = execute_authenticated(
3809            &queue,
3810            home,
3811            &talks,
3812            &talk.id,
3813            crate::chat_goal::Source::Automatic,
3814            make_op(),
3815        )
3816        .await
3817        .unwrap_err();
3818        assert!(
3819            err.to_string()
3820                .contains("recover-land-sync requires explicit owner input"),
3821            "{err:#}"
3822        );
3823
3824        // Standing automatic recovery turn covering a real held task must refuse RecoverLandSync
3825        // as outside the standing allowlist.
3826        let mut task = crate::queue::Task::new(
3827            "held".into(),
3828            "held work".into(),
3829            home.join("repo"),
3830            crate::queue::Source::Agent {
3831                run: talk.id.clone(),
3832                node: crate::queue::CHAT_NODE.into(),
3833            },
3834        );
3835        task.hold_machine(Some("landing base synchronization budget exhausted".into()));
3836        queue.put(&mut task).unwrap();
3837        let input: crate::talk::Turn = serde_json::from_value(serde_json::json!({
3838            "sender": "magi",
3839            "who": "operator",
3840            "body": "report",
3841            "at": jiff::Timestamp::now(),
3842            "messages": [{
3843                "sender": "magi",
3844                "body": "report",
3845                "at": jiff::Timestamp::now(),
3846                "attachments": [],
3847                "recovery_event": standing::Event::task(&task)
3848            }]
3849        }))
3850        .unwrap();
3851        let standing_source = standing::capture(
3852            true,
3853            home,
3854            &talk,
3855            Some(&input),
3856            crate::chat_goal::Source::Automatic,
3857        );
3858        let err = execute_authenticated(
3859            &queue,
3860            home,
3861            &talks,
3862            &talk.id,
3863            standing_source,
3864            Operation::Standing {
3865                task: task.id.clone(),
3866                evidence: "auto".into(),
3867                command: Box::new(make_op()),
3868            },
3869        )
3870        .await
3871        .unwrap_err();
3872        assert!(
3873            err.to_string()
3874                .contains("outside the standing recovery allowlist"),
3875            "{err:#}"
3876        );
3877    }
3878}