Skip to main content

magi/
chat_control.rs

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