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