Skip to main content

magi/
chat_control.rs

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