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    },
118    /// Change a task's queue priority.
119    Priority {
120        /// Task id or unambiguous prefix.
121        task: String,
122        /// New priority.
123        priority: i32,
124    },
125    /// Merge a PR the owner asked for, once per request.
126    MergePr {
127        /// Exact owner/repository name.
128        repo: String,
129        /// Pull request number.
130        number: u64,
131        /// Full head SHA the chat just read from the forge.
132        head: String,
133        /// Idempotency key minted by the chat agent.
134        request: String,
135    },
136    /// Authorize one bounded base-recovery interval and queue the existing run.
137    RecoverBase {
138        /// Exact retained run ID.
139        run: String,
140        /// Retained HEAD inspected for the owner's request (full SHA or 7+ hex digits).
141        head: String,
142        /// Durable idempotency key; reuse only for identical arguments.
143        request: String,
144    },
145    /// 既存 run の再開を queue に登録する。
146    Resume {
147        /// 完全な run ID。
148        run: String,
149    },
150    /// Queue a Git-only pass over the retained winner.
151    SyncBaseOnly {
152        /// Exact retained run ID.
153        run: String,
154    },
155    /// task を手動保留する。
156    Hold {
157        /// task ID または一意な接頭辞。
158        task: String,
159        /// 保留理由。
160        reason: String,
161    },
162    /// task を保留から解放する。
163    Release {
164        /// task ID または一意な接頭辞。
165        task: String,
166    },
167    /// 指示を変更して再試行する。
168    Retry {
169        /// task ID または一意な接頭辞。
170        task: String,
171        /// 新しいタイトル、省略時は指示から生成する。
172        title: Option<String>,
173        /// 新しい指示全文。
174        instruction: String,
175    },
176    /// PR の失敗した workflow を再実行する。
177    RerunChecks {
178        /// 完全な run ID。
179        run: String,
180        /// 冪等性を保証するリクエスト ID。
181        request: String,
182        /// 観測した PR head。
183        head: String,
184        /// 再実行対象の workflow run ID。
185        workflows: Vec<String>,
186    },
187    /// タスクチャットで所有者の判断を記録する(マージを含む)。
188    Decide {
189        /// 質問 ID(完全または一意な接頭辞)。
190        question: String,
191        /// 記録された選択肢のラベル。
192        choice: String,
193        /// 「use my text」で公開する置換タイトルそのもの。
194        #[serde(default)]
195        title: Option<String>,
196    },
197    /// `magi answer --reply`: the owner's answer to a question, as an ordinary
198    /// answer ([`crate::ask::record_answer`]).
199    Answer {
200        /// Full question id, resolved by the CLI.
201        question: String,
202        /// An offered choice (label or alias), or the free-text answer.
203        reply: String,
204        /// The literal replacement title for the posting gate's `use my text`.
205        #[serde(default)]
206        title: Option<String>,
207    },
208    /// `magi answer --reply-other`: the owner's decision outside the offered
209    /// choices, saved as a note that ends the consultation
210    /// ([`crate::consult::reply_other`]).
211    ReplyOther {
212        /// Full question id, resolved by the CLI.
213        question: String,
214        /// The owner's outcome.
215        text: String,
216    },
217    /// 保存された計画を作成、または適用する。
218    ReconcileRetention {
219        /// 対象タスク ID。
220        task: String,
221        /// 保護する実装の完全な run ID。
222        authority: String,
223        /// 適用する保存済み計画 ID(省略時は計画のみ)。
224        apply: Option<String>,
225    },
226    /// 生存が否定された run を破棄する。
227    Abandon {
228        /// 完全な run ID。
229        run: String,
230    },
231}
232
233/// Inputs prepared by `magi task add` before saving a fresh queue record.
234#[derive(Debug, serde::Serialize, serde::Deserialize)]
235#[serde(deny_unknown_fields)]
236pub struct Filing {
237    /// Task title.
238    pub title: String,
239    /// Complete task instruction.
240    pub instruction: String,
241    /// Validated absolute repository path.
242    pub repo: std::path::PathBuf,
243    /// Filing provenance prepared by the CLI.
244    pub source: crate::queue::Source,
245    /// Resolved implementation imports.
246    pub sources: crate::refs::Sources,
247    /// Optional initial hold reason.
248    pub hold: Option<String>,
249    /// Queue priority.
250    pub priority: i32,
251    /// Use one implementer.
252    pub solo: bool,
253    /// Prioritize execution.
254    pub urgent: bool,
255    /// Optional implementer count.
256    pub implementers: Option<usize>,
257    /// Optional Cargo build output policy.
258    #[serde(default, skip_serializing_if = "Option::is_none")]
259    pub build_cache: Option<crate::config::BuildCache>,
260    /// Absolute attachment paths to copy into the queue.
261    pub attach: Vec<std::path::PathBuf>,
262}
263
264/// Whether this process inherited a launcher control channel.
265/// Provenance-only CLI calls without a channel retain their ordinary local route.
266pub fn has_channel() -> bool {
267    #[cfg(any(unix, windows))]
268    {
269        #[cfg(unix)]
270        let socket = std::env::var_os("MAGI_CHAT_CONTROL_SOCKET").is_some();
271        #[cfg(windows)]
272        let socket = false;
273        std::env::var_os(bridge::CHANNEL_ENV).is_some() || socket
274    }
275    #[cfg(not(any(unix, windows)))]
276    {
277        false
278    }
279}
280
281/// The CLI sends only a typed operation when it inherited a turn capability.
282/// Outside a launched turn the existing, authorized local route remains usable.
283pub async fn dispatch(
284    queue: &Queue,
285    home: &Path,
286    talks: &Talks,
287    talk: &str,
288    operation: Operation,
289) -> Result<String> {
290    if matches!(
291        &operation,
292        Operation::Reassign { .. }
293            | Operation::RecoverBase { .. }
294            | Operation::SyncBaseOnly { .. }
295            | Operation::Goal { .. }
296            | Operation::Standing { .. }
297    ) {
298        #[cfg(unix)]
299        {
300            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");
301        }
302        #[cfg(windows)]
303        {
304            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");
305        }
306        #[cfg(not(any(unix, windows)))]
307        {
308            bail!("authenticated chat control channel is unavailable on this platform");
309        }
310    }
311    if standing_turn() {
312        #[cfg(unix)]
313        return bridge::request(&operation)
314            .context("automatic recovery requires the authenticated chat control channel");
315        #[cfg(windows)]
316        return bridge::request(&operation)
317            .await
318            .context("automatic recovery requires the authenticated chat control channel");
319        #[cfg(not(any(unix, windows)))]
320        bail!("authenticated chat control channel is unavailable on this platform");
321    }
322    #[cfg(unix)]
323    if std::env::var_os(bridge::CHANNEL_ENV).is_some()
324        || std::env::var_os("MAGI_CHAT_CONTROL_SOCKET").is_some()
325    {
326        // The launcher sets this flag for writable seats, including effective
327        // unsandboxed chat turns. execute() still enforces talk authorization.
328        match bridge::request(&operation) {
329            Err(error)
330                if error.is::<bridge::Unavailable>()
331                    && std::env::var("MAGI_ALLOW_WRITE").as_deref() == Ok("1") => {}
332            result => return result,
333        }
334    }
335    #[cfg(windows)]
336    if std::env::var_os(bridge::CHANNEL_ENV).is_some() {
337        return bridge::request(&operation).await;
338    }
339    execute(queue, home, talks, talk, operation).await
340}
341
342/// The transport supplies immutable launcher authority, never the CLI frame.
343async fn execute_authenticated(
344    queue: &Queue,
345    home: &Path,
346    talks: &Talks,
347    talk: &str,
348    source: crate::chat_goal::Source,
349    operation: Operation,
350) -> Result<String> {
351    if let crate::chat_goal::Source::Standing(scope) = source {
352        return Box::pin(standing::execute(
353            queue, home, talks, talk, &scope, operation,
354        ))
355        .await;
356    }
357    crate::chat_goal::with_source(source, execute(queue, home, talks, talk, operation)).await
358}
359
360/// Whether the launcher restricted this CLI to read-only inspection and typed controls.
361/// The environment marker can only restrict the CLI; it cannot grant bridge authority.
362pub fn standing_turn() -> bool {
363    std::env::var_os(standing::ENV).is_some()
364}
365
366async fn execute(
367    queue: &Queue,
368    home: &Path,
369    talks: &Talks,
370    talk: &str,
371    operation: Operation,
372) -> Result<String> {
373    authorize(talks, talk, crate::queue::CHAT_NODE)?;
374    crate::chat_goal::fence(talks, talk, &crate::chat_goal::current_source())?;
375    admit_goal_operation(queue, home, talks, talk, &operation)?;
376    Ok(match operation {
377        Operation::Standing { .. } => bail!(
378            "standing authorization is disabled or this turn is not an eligible automatic report"
379        ),
380        Operation::Goal { command } => {
381            crate::chat_goal::apply(
382                queue,
383                home,
384                talks,
385                talk,
386                &crate::chat_goal::current_source(),
387                command,
388            )
389            .await?
390        }
391        Operation::Reassign { task, repo } => {
392            let cwd = &talks.get(talk)?.repo;
393            let task = crate::task_reassign::reassign(
394                queue,
395                home,
396                cwd,
397                &task,
398                &repo,
399                &format!("chat:{talk}"),
400            )
401            .await?;
402            let mut message = describe(&task, "reassigned");
403            for note in crate::task_reassign::advisory_notes(&task, home) {
404                message.push_str(&format!("\n  {note}"));
405            }
406            message
407        }
408        Operation::ReconcileDecision { inquiry } => {
409            reconcile_task_decision(queue, home, talk, &inquiry)?;
410            format!("decision {inquiry} reconciled from the task's durable state")
411        }
412        Operation::ForDecision { inquiry, command } => {
413            execute_decision(queue, home, talks, talk, &inquiry, *command).await?
414        }
415        Operation::SettleDecision {
416            inquiry,
417            reason,
418            replacement,
419        } => {
420            let outbox = crate::task_inquiry::Outbox::at(home);
421            let record = outbox.get(&inquiry)?;
422            let questions = crate::ask::Questions::at(home.join("questions"));
423            let source = questions.read_history(&inquiry).ok();
424            // A quarantined saved reply is not a live unanswered decision.
425            // The owner can explicitly confirm that its unknown effect needs
426            // no further work without accepting or replaying the old reply.
427            let unaccepted_history = record
428                .decision
429                .as_ref()
430                .is_some_and(|d| d.request.is_none())
431                && source.as_ref().is_some_and(|source| {
432                    source.status == crate::ask::QuestionStatus::Answered
433                        && crate::task_chat::saved_reply_requires_confirmation(home, source)
434                });
435            // Task-backed legacy consumers run under the task claim. Hold it
436            // through settlement; ownerless release consumers use the inquiry
437            // execution fence inside Outbox::settle instead.
438            let _task_claim = if !record.task.is_empty()
439                && (unaccepted_history
440                    || record
441                        .decision
442                        .as_ref()
443                        .is_some_and(|d| d.request.is_some()))
444            {
445                Some(
446                    queue
447                        .claim(&record.task)
448                        .context("decision task is executing")?,
449                )
450            } else {
451                None
452            };
453            if record
454                .decision
455                .as_ref()
456                .is_some_and(|d| d.request.is_none())
457                && let Some(source) = source
458                && !(record.task.is_empty() && record.delivered_to.is_none())
459            {
460                ensure!(
461                    unaccepted_history || !crate::task_chat::awaits_decision(&source),
462                    "a legacy effect still awaits consumer reconciliation; settlement executes no action"
463                );
464            }
465            outbox.settle(&inquiry, talk, &reason, replacement.as_deref())?;
466            format!("settled decision {inquiry}: {reason}")
467        }
468        Operation::Add { filing } => serde_json::to_string(&file_task(queue, *filing)?)?,
469        Operation::Done { task } => {
470            let t = done_claimed(queue, home, claimed_for_chat(queue, &task, talks, talk)?)?;
471            format!("done {} {}", t.short(), t.title)
472        }
473        Operation::Priority { task, priority } => {
474            let t = priority_claimed(
475                queue,
476                claimed_for_chat(queue, &task, talks, talk)?,
477                priority,
478            )?;
479            format!("{} priority now {} - {}", t.short(), t.priority, t.title)
480        }
481        Operation::MergePr {
482            repo,
483            number,
484            head,
485            request,
486        } => crate::chat_merge::merge(
487            home,
488            talks,
489            talk,
490            crate::chat_merge::Request {
491                repo,
492                number,
493                head,
494                request,
495            },
496        )
497        .await
498        .map_err(|error| {
499            if error.is::<crate::chat_merge::BeforeMergeWrite>() {
500                anyhow::Error::new(BeforeEffect(error))
501            } else {
502                error
503            }
504        })?,
505        Operation::ReconcileRepairGrant { request } => serde_json::to_string(
506            &Box::pin(crate::repair_budget::reconcile::apply(queue, home, request)).await?,
507        )?,
508        Operation::GrantRepair { request } => {
509            // Keep run-state admission out of the shared control dispatcher
510            // future, which is also embedded in ordinary CLI task operations.
511            let owner_requested_at = match crate::chat_goal::current_source() {
512                crate::chat_goal::Source::Input { turn } => talks
513                    .get(talk)?
514                    .turns
515                    .get(turn)
516                    .and_then(|turn| crate::talk::owner_send_boundary(&turn.messages)),
517                _ => None,
518            };
519            let receipt = Box::pin(crate::repair_budget::grant_with_claim(
520                queue,
521                home,
522                request,
523                None,
524                owner_requested_at,
525            ))
526            .await
527            .map_err(|error| {
528                if error.is::<crate::repair_budget::PublicationUnknown>() {
529                    error
530                } else {
531                    BeforeEffect(error).into()
532                }
533            })?;
534            serde_json::to_string(&receipt)?
535        }
536        Operation::RecoverBase { run, head, request } => {
537            let result = Box::pin(crate::base_recovery_control::recover(
538                queue,
539                home,
540                crate::base_recovery_control::Request {
541                    run,
542                    head,
543                    request,
544                    actor: talk.to_owned(),
545                    decision: None,
546                    expected_stop: None,
547                },
548            ))
549            .await?;
550            if result.repeated {
551                format!(
552                    "This base-recovery request was already applied to task {}; inspect its current status before continuing",
553                    result.task.id
554                )
555            } else {
556                format!(
557                    "{}; bounded base recovery authorized; the daemon resumes the exact run under its execution lease",
558                    describe(&result.task, "recovery queued for")
559                )
560            }
561        }
562        Operation::Resume { run } => {
563            let t = resume(queue, home, &run)?;
564            format!(
565                "{}; the loop (`magi serve`) resumes the run under its execution lease",
566                describe(&t, "resume queued for")
567            )
568        }
569        Operation::SyncBaseOnly { run } => {
570            ensure!(
571                matches!(
572                    crate::chat_goal::current_source(),
573                    crate::chat_goal::Source::Input { .. }
574                ),
575                "sync-base-only requires an explicit owner request in this chat turn"
576            );
577            let owner = run_task(queue, &run)?;
578            let _claim = queue.claim(&owner.id)?;
579            let mut task = queue.get(&owner.id)?;
580            crate::base_sync_only::queue(&mut task, home, &run)?;
581            queue.put(&mut task)?;
582            describe(&task, "base synchronization only queued for")
583        }
584        Operation::Hold { task, reason } => describe(
585            &hold_claimed(queue, claimed_for_chat(queue, &task, talks, talk)?, &reason)?,
586            "held",
587        ),
588        Operation::Release { task } => describe(
589            &release_claimed(queue, claimed_for_chat(queue, &task, talks, talk)?)?,
590            "released",
591        ),
592        Operation::Retry {
593            task,
594            title,
595            instruction,
596        } => describe(
597            &retry_claimed(
598                queue,
599                claimed_for_chat(queue, &task, talks, talk)?,
600                title,
601                &instruction,
602            )?,
603            "retry queued for",
604        ),
605        Operation::RerunChecks {
606            run,
607            request,
608            head,
609            workflows,
610        } => {
611            let ids = rerun_checks(queue, home, talk, &run, &request, &head, &workflows).await?;
612            format!("requested a rerun of workflow run(s) {}", ids.join(", "))
613        }
614        Operation::Decide {
615            question,
616            choice,
617            title,
618        } => {
619            let q = record_decision(home, &question, &choice, title.as_deref())?;
620            format!(
621                "recorded `{choice}` for decision {}; effect pending until its durable application receipt is confirmed",
622                q.short()
623            )
624        }
625        Operation::Answer {
626            question,
627            reply,
628            title,
629        } => crate::ask::record_answer(
630            &crate::ask::Questions::at(home.join("questions")),
631            &question,
632            &reply,
633            title.as_deref(),
634        )?,
635        Operation::ReplyOther { question, text } => crate::consult::reply_other(
636            &crate::ask::Questions::at(home.join("questions")),
637            &question,
638            &text,
639        )?,
640        Operation::ReconcileRetention {
641            task,
642            authority,
643            apply,
644        } => {
645            let path = Box::pin(crate::retention::reconcile::run_chat(
646                home,
647                &task,
648                &authority,
649                apply.as_deref(),
650                crate::retention::reconcile::ChatRequest {
651                    talks,
652                    conversation: talk,
653                },
654            ))
655            .await?;
656            if apply.is_none() {
657                // Return the complete saved evidence through the capability bridge.
658                crate::retention::reconcile::chat_summary(&path)?
659            } else {
660                format!(
661                    "Applied saved plan {}",
662                    apply.as_deref().unwrap_or_default()
663                )
664            }
665        }
666        Operation::Abandon { run } => {
667            abandon(queue, home, &run)?;
668            format!("abandoned run {run}")
669        }
670    })
671}
672
673fn file_task(queue: &Queue, filing: Filing) -> Result<Task> {
674    let mut task = Task::new(filing.title, filing.instruction, filing.repo, filing.source);
675    task.sources = filing.sources;
676    if let Some(reason) = filing.hold {
677        task.hold_manual(Some(reason));
678    }
679    task.priority = filing.priority;
680    task.solo = filing.solo;
681    task.urgent = filing.urgent;
682    if filing.implementers.is_some() || filing.build_cache.is_some() {
683        task.overrides = Some(crate::queue::RunOverrides {
684            inherit_daemon_options: filing.implementers.is_none(),
685            candidates: filing.implementers,
686            build_cache: filing.build_cache,
687            ..Default::default()
688        });
689    }
690    if filing.attach.is_empty() {
691        queue.put(&mut task)?;
692    } else {
693        queue.attach_and_put(&mut task, &filing.attach)?;
694    }
695    Ok(task)
696}
697
698/// A goal turn cannot redirect existing effects to unrelated work.
699fn admit_goal_operation(
700    queue: &Queue,
701    home: &Path,
702    talks: &Talks,
703    talk_id: &str,
704    operation: &Operation,
705) -> Result<()> {
706    let crate::chat_goal::Source::Goal { id, generation } = crate::chat_goal::current_source()
707    else {
708        return Ok(());
709    };
710    let talk = talks.get(talk_id)?;
711    let goal = talk
712        .goals
713        .iter()
714        .find(|goal| goal.id == id)
715        .context("unknown goal")?;
716    goal.admit(generation)?;
717    ensure!(
718        !goal.owner_input.is_empty(),
719        "this goal was registered under standing authorization; fresh owner input is required with the setting off"
720    );
721    let repo = goal.effective_repo(&talk.repo);
722    let task_allowed = |reference: &str| -> Result<()> {
723        let id = queue.resolve_id(reference)?;
724        ensure!(
725            goal.tasks.contains(&id),
726            "effect targets a task outside this goal"
727        );
728        crate::chat_goal::task_record(queue, &id, repo)?;
729        Ok(())
730    };
731    let run_allowed = |run: &str| -> Result<()> {
732        ensure!(
733            goal.runs.iter().any(|id| id == run)
734                || goal
735                    .tasks
736                    .iter()
737                    .any(|id| crate::chat_goal::task_record(queue, id, repo)
738                        .is_ok_and(|task| task.execution_runs().iter().any(|id| id == run))),
739            "effect targets an execution outside this goal"
740        );
741        crate::chat_goal::run_record(home, run, repo)?;
742        Ok(())
743    };
744    match operation {
745        Operation::Standing { .. } => bail!("standing authorization is disabled for this turn"),
746        Operation::Goal { .. } => {}
747        Operation::Add { filing } => {
748            crate::chat_goal::require_repo("filing", talk_id, &filing.repo, repo)?;
749            ensure!(
750                matches!(&filing.source, crate::queue::Source::Agent { run, node }
751                    if run == talk_id && node == crate::queue::CHAT_NODE),
752                "goal filing must retain this conversation's provenance"
753            );
754        }
755        Operation::Done { task }
756        | Operation::Priority { task, .. }
757        | Operation::Hold { task, .. }
758        | Operation::Release { task }
759        | Operation::Retry { task, .. }
760        | Operation::ReconcileRetention { task, .. } => task_allowed(task)?,
761        Operation::GrantRepair { request } => {
762            task_allowed(&request.task)?;
763            run_allowed(&request.run)?;
764        }
765        Operation::ReconcileRepairGrant { request } => {
766            task_allowed(&request.task)?;
767            run_allowed(&request.run)?;
768        }
769        Operation::Resume { run }
770        | Operation::SyncBaseOnly { run }
771        | Operation::RecoverBase { run, .. }
772        | Operation::Abandon { run }
773        | Operation::RerunChecks { run, .. } => run_allowed(run)?,
774        Operation::ForDecision { inquiry, .. }
775        | Operation::ReconcileDecision { inquiry }
776        | Operation::SettleDecision { inquiry, .. } => {
777            let record = crate::task_inquiry::Outbox::at(home).get(inquiry)?;
778            crate::chat_goal::require_repo("inquiry", inquiry, &record.repo, repo)?;
779            task_allowed(&record.task)?;
780            if let Some(run) = record.run {
781                run_allowed(&run)?;
782            }
783        }
784        Operation::Decide { question, .. }
785        | Operation::Answer { question, .. }
786        | Operation::ReplyOther { question, .. } => {
787            let questions = crate::ask::Questions::at(home.join("questions"));
788            let question = questions.get_for_effects(&questions.resolve_id(question)?)?;
789            if question.run_names_task() {
790                task_allowed(&question.run)?;
791            } else {
792                run_allowed(&question.run)?;
793            }
794        }
795        Operation::MergePr {
796            repo: slug, number, ..
797        } => {
798            let expected = format!("https://github.com/{slug}/pull/{number}");
799            let mut found = false;
800            let mut inspect = |run: &str| -> Result<()> {
801                let state = crate::chat_goal::run_record(home, run, repo)?;
802                found |= state
803                    .pr
804                    .as_ref()
805                    .is_some_and(|pr| pr.url.eq_ignore_ascii_case(&expected));
806                Ok(())
807            };
808            for run in &goal.runs {
809                inspect(run)?;
810            }
811            for task in &goal.tasks {
812                for run in crate::chat_goal::task_record(queue, task, repo)?.execution_runs() {
813                    inspect(run)?;
814                }
815            }
816            ensure!(found, "merge targets a pull request outside this goal");
817        }
818        Operation::Reassign { .. } => bail!("automatic goal turns cannot change repository scope"),
819    }
820    Ok(())
821}
822
823/// Run one typed operation on behalf of the owner, retaining failures and
824/// uncertainty. A repeated command never blindly replays a possibly applied
825/// external effect. The underlying operation retains its existing claims and
826/// receipts; this journal is its user-visible lifecycle, not a second worker.
827async fn execute_decision(
828    queue: &Queue,
829    home: &Path,
830    talks: &Talks,
831    chat: &str,
832    id: &str,
833    command: Operation,
834) -> Result<String> {
835    use crate::task_decision::Status;
836    admit_goal_operation(queue, home, talks, chat, &command)?;
837    let outbox = crate::task_inquiry::Outbox::at(home);
838    let _execution = outbox.execution_claim(id)?;
839    let inquiry = outbox.get(id)?;
840    ensure!(
841        inquiry.delivered_to.as_deref() == Some(chat),
842        "decision belongs to another chat"
843    );
844    let task = queue.get(&inquiry.task)?;
845    ensure!(task.repo == inquiry.repo, "decision repository changed");
846    let deferred = matches!(
847        command,
848        Operation::Resume { .. } | Operation::MergePr { .. }
849    );
850    let merge = match &command {
851        Operation::MergePr {
852            repo,
853            number,
854            head,
855            request,
856        } => Some(crate::chat_merge::Request {
857            repo: repo.clone(),
858            number: *number,
859            head: head.clone(),
860            request: request.clone(),
861        }),
862        _ => None,
863    };
864    match &command {
865        Operation::Done { task: target }
866        | Operation::Hold { task: target, .. }
867        | Operation::Release { task: target }
868        | Operation::Retry { task: target, .. } => {
869            ensure!(
870                queue.resolve_id(target)? == task.id,
871                "command targets another task"
872            );
873        }
874        Operation::Resume { run }
875        | Operation::Abandon { run }
876        | Operation::RerunChecks { run, .. } => {
877            ensure!(
878                task.runs.contains(run) && inquiry.run.as_ref().is_none_or(|own| own == run),
879                "command targets another execution"
880            );
881            ensure!(
882                queue
883                    .list()
884                    .iter()
885                    .filter(|owner| owner.runs.contains(run))
886                    .count()
887                    == 1,
888                "execution ownership is ambiguous"
889            );
890        }
891        Operation::MergePr { repo, number, .. } => {
892            let run = inquiry
893                .run
894                .as_ref()
895                .or_else(|| task.runs.last())
896                .context("task has no execution for this merge")?;
897            let state = crate::run::RunState::load_under(run, home)?;
898            ensure!(state.id == *run, "merge run identity changed");
899            ensure!(
900                crate::git::same_checkout(&state.repo, &task.repo)?,
901                "merge targets another repository"
902            );
903            let expected = format!("https://github.com/{repo}/pull/{number}");
904            ensure!(
905                state
906                    .pr
907                    .as_ref()
908                    .is_some_and(|pr| pr.url.eq_ignore_ascii_case(&expected)),
909                "merge targets another task or repository"
910            );
911        }
912        _ => bail!("use a task/run effect command with --decision; routed approvals use decide"),
913    }
914    let request = serde_json::to_string(&command)?;
915    let mut decision = inquiry.decision.context("inquiry is informational")?;
916    if decision.request.is_some()
917        && decision.status != Status::Resolved
918        && let Operation::Resume { run } = &command
919    {
920        ensure!(
921            decision.request.as_deref() == Some(&request),
922            "decision already binds a different request"
923        );
924        // Queued also includes successfully published resumes. Reconcile under
925        // the execution claim before permitting any retry, even if the run has
926        // since returned to a resumable state. Only proven non-publication may
927        // enter the retry path below.
928        reconcile_resume_claimed(queue, home, &outbox, id, run)?;
929        decision = outbox
930            .get(id)?
931            .decision
932            .context("inquiry is informational")?;
933        ensure!(
934            decision.status == Status::Resolved || decision.retry_safe,
935            "previous resume remains queued or executing; it will not be replayed"
936        );
937    }
938    if decision.status == Status::Resolved {
939        ensure!(
940            decision.request.as_deref() == Some(&request),
941            "decision resolved for a different request"
942        );
943        return Ok(format!(
944            "decision {id} is already resolved; inspect its outcome history"
945        ));
946    }
947    if let Operation::RerunChecks { run, request, .. } = &command {
948        // Reject correctable input before binding the decision to this exact
949        // command. Execution revalidates these reads before taking its lock.
950        rerun_preflight(queue, home, run, request)?;
951    }
952    if let Some(action) = &merge {
953        // Malformed input must not durably bind this decision to a command
954        // that can never reach its effect service.
955        action.validate()?;
956    }
957    // Keep admission across acceptance and execution: contention and request
958    // collisions must not bind a fresh decision to an unstartable operation.
959    let merge_admission = merge
960        .as_ref()
961        .map(|action| crate::chat_merge::admit(home, talks, chat, action))
962        .transpose()?;
963    if decision.request.is_none() && decision.status == Status::RetryNeeded {
964        if let Ok(source) = crate::ask::Questions::at(home.join("questions")).get(id) {
965            ensure!(
966                !crate::task_chat::awaits_decision(&source),
967                "a legacy effect still needs its receipt reconciled before another effect is accepted"
968            );
969        }
970    }
971    {
972        // A live task cannot accept a repair grant. Do not prevent decisions
973        // that its active driver is waiting for by taking its execution claim.
974        let claim = (queue.get(&task.id)?.status != TaskStatus::Running)
975            .then(|| queue.claim(&task.id))
976            .transpose();
977        let _claim = match claim {
978            Ok(claim) => claim,
979            Err(error) => {
980                // Admission could not start this attempt. Retain the exact
981                // owner request and pre-effect failure just as execution-side
982                // claim contention does, without publishing any task effect.
983                let message = format!(
984                    "{error:#}. No effect began; retry this same request after resolving the cause, or explicitly settle it."
985                );
986                outbox.update_decision(id, |d| {
987                    let safe = d.request.is_none() || d.retry_safe;
988                    d.accept(&request)?;
989                    if safe {
990                        d.fail_before_effect(&message)
991                    } else {
992                        // A prior queued/uncertain attempt still needs its own
993                        // receipt. Contention is not proof that it never ran.
994                        Ok(false)
995                    }
996                })?;
997                return Err(anyhow::Error::new(BeforeEffect(error)));
998            }
999        };
1000        outbox.update_decision(id, |d| d.accept(&request))?;
1001    }
1002    let late_admission = crate::chat_goal::fence(talks, chat, &crate::chat_goal::current_source())
1003        .and_then(|()| admit_goal_operation(queue, home, talks, chat, &command));
1004    if late_admission.is_ok()
1005        && decision.request.is_some()
1006        && matches!(decision.status, Status::InProgress | Status::RetryNeeded)
1007    {
1008        if decision.retry_safe {
1009            outbox.update_decision(id, |d| {
1010                d.retry_unapplied()?;
1011                d.start()
1012            })?;
1013        } else {
1014            let action = merge
1015                .as_ref()
1016                .context("previous effect needs receipt reconciliation; it will not be replayed")?;
1017            ensure!(
1018                merge_receipt(home, chat, action)?.is_some(),
1019                "previous merge has no receipt; inspect the operation before retrying"
1020            );
1021        }
1022        // The shared merge service only checks the forge once this exact
1023        // request has a receipt; it never issues the merge command twice.
1024    } else if late_admission.is_ok() {
1025        outbox.update_decision(id, |d| d.start())?;
1026    }
1027    let local = match late_admission {
1028        // A refusal now says nothing about a prior attempt that may have acted.
1029        Err(error)
1030            if decision.request.is_some()
1031                && !decision.retry_safe
1032                && (matches!(decision.status, Status::InProgress | Status::RetryNeeded)
1033                    || decision
1034                        .history
1035                        .iter()
1036                        .any(|event| event.status == Status::InProgress)) =>
1037        {
1038            return Err(error);
1039        }
1040        Err(error) => Err(anyhow::Error::new(BeforeEffect(error))),
1041        Ok(()) => apply_local_decision(
1042            queue,
1043            home,
1044            id,
1045            &request,
1046            &inquiry.task,
1047            &inquiry.repo,
1048            &command,
1049        ),
1050    };
1051    let result = if let Err(error) = local {
1052        Err(error)
1053    } else if let Some(message) = local? {
1054        Ok(message)
1055    } else if let Operation::Resume { run } = &command {
1056        // Validation precedes any write: a refusal means nothing began.
1057        crate::resume::validate(home, run)
1058            .map(|_| ())
1059            .map_err(|e| anyhow::Error::new(BeforeEffect(e)))
1060            .and_then(|()| -> Result<String> {
1061                let pinned =
1062                    crate::resume::pin_queued(queue, run, None, Some(id)).map_err(|error| {
1063                        if error.is::<crate::resume::BeforeQueueWrite>() {
1064                            anyhow::Error::new(BeforeEffect(error))
1065                        } else {
1066                            error
1067                        }
1068                    })?;
1069                if !pinned {
1070                    return Err(anyhow::Error::new(BeforeEffect(anyhow::anyhow!(
1071                        "no queued task owns this run"
1072                    ))));
1073                }
1074                Ok(format!(
1075                    "resume queued for {run}; execution start remains unconfirmed"
1076                ))
1077            })
1078    } else if let Operation::Abandon { run } = &command {
1079        crate::driver::abandon_decision(home, run, id, &request)
1080            .map_err(|error| {
1081                if error.is::<crate::driver::BeforeAbandonWrite>() {
1082                    anyhow::Error::new(BeforeEffect(error))
1083                } else {
1084                    error
1085                }
1086            })
1087            .map(|()| format!("abandoned run {run}"))
1088    } else if let Some(admission) = merge_admission {
1089        crate::chat_merge::merge_admitted(home, merge.as_ref().unwrap().clone(), admission)
1090            .await
1091            .map_err(|error| {
1092                if error.is::<crate::chat_merge::BeforeMergeWrite>() {
1093                    anyhow::Error::new(BeforeEffect(error))
1094                } else {
1095                    error
1096                }
1097            })
1098    } else {
1099        Box::pin(execute(queue, home, talks, chat, command)).await
1100    };
1101    match result {
1102        Ok(message) => {
1103            if let Some(action) = &merge {
1104                if let Some(receipt) = merge_receipt(home, chat, action)? {
1105                    if receipt["status"] == "merged" {
1106                        outbox.update_decision(id, |d| d.applied(&message))?;
1107                    } else if receipt["status"] != "pending" {
1108                        outbox.update_decision(id, |d| {
1109                            d.fail(&format!(
1110                                "{message}; reuse this same request ID to reconcile only"
1111                            ))
1112                        })?;
1113                    }
1114                }
1115            } else if !deferred {
1116                outbox.update_decision(id, |d| {
1117                    d.applied(&format!("typed command completed: {message}"))
1118                })?;
1119            }
1120            if deferred
1121                && outbox
1122                    .get(id)?
1123                    .decision
1124                    .as_ref()
1125                    .is_some_and(|d| d.status == Status::InProgress)
1126            {
1127                outbox.update_decision(id, |d| d.queued())?;
1128            }
1129            // Resume has only been queued. Its execution is confirmed by a
1130            // later scheduler projection, never by this command's return.
1131            Ok(message)
1132        }
1133        Err(error) => {
1134            let message = if error.is::<BeforeEffect>() {
1135                format!(
1136                    "{error:#}. No effect began; retry this same request after resolving the cause, or explicitly settle it."
1137                )
1138            } else {
1139                format!(
1140                    "Operation failed or has an uncertain result: {error:#}. Inspect its receipt before retrying."
1141                )
1142            };
1143            outbox.update_decision(id, |d| {
1144                if error.is::<BeforeEffect>() {
1145                    d.fail_before_effect(&message)
1146                } else {
1147                    d.fail(&message)
1148                }
1149            })?;
1150            Err(error)
1151        }
1152    }
1153}
1154
1155#[derive(Debug, thiserror::Error)]
1156#[error("effect did not start: {0:#}")]
1157struct BeforeEffect(anyhow::Error);
1158
1159/// Commit a task-local effect and its exact receipt under one queue claim.
1160/// The inquiry projection may lag this write, but restart never has to infer
1161/// completion from the task's current status or repeat the operation.
1162fn apply_local_decision(
1163    queue: &Queue,
1164    home: &Path,
1165    id: &str,
1166    request: &str,
1167    owner: &str,
1168    repo: &Path,
1169    command: &Operation,
1170) -> Result<Option<String>> {
1171    let target = match command {
1172        Operation::Done { task }
1173        | Operation::Hold { task, .. }
1174        | Operation::Release { task }
1175        | Operation::Retry { task, .. } => task,
1176        _ => return Ok(None),
1177    };
1178    let prepare = || -> Result<_> {
1179        let (_claim, mut task) = claimed(queue, target)?;
1180        ensure!(
1181            task.id == owner && task.repo == repo,
1182            "decision ownership changed"
1183        );
1184        if let Some(prior) = task.decision_effects.get(id) {
1185            ensure!(prior == request, "decision receipt binds another command");
1186            let message = format!("task {}: decision {id} already applied", task.id);
1187            return Ok((_claim, task, message, true));
1188        }
1189        let message = match command {
1190            Operation::Done { .. } => {
1191                task.succeed();
1192                describe(&task, "done")
1193            }
1194            Operation::Hold { reason, .. } => {
1195                check_hold_release(&task, "hold")?;
1196                let reason = reason.trim();
1197                task.hold_manual((!reason.is_empty()).then(|| reason.to_owned()));
1198                describe(&task, "held")
1199            }
1200            Operation::Release { .. } => {
1201                check_hold_release(&task, "release")?;
1202                task.release_operator("chat", Some(id));
1203                describe(&task, "released")
1204            }
1205            Operation::Retry {
1206                title, instruction, ..
1207            } => {
1208                ensure!(
1209                    !instruction.trim().is_empty(),
1210                    "the new instruction is empty"
1211                );
1212                let title = title
1213                    .clone()
1214                    .unwrap_or_else(|| crate::queue::title_from(instruction, 72));
1215                task.edit(title, instruction.clone())?;
1216                task.release_operator("chat", Some(id));
1217                describe(&task, "retry queued for")
1218            }
1219            _ => unreachable!("task-local operation checked above"),
1220        };
1221        task.decision_effects
1222            .insert(id.to_owned(), request.to_owned());
1223        Ok((_claim, task, message, false))
1224    };
1225    let (_claim, mut task, message, already_applied) = prepare().map_err(BeforeEffect)?;
1226    if !already_applied {
1227        queue.put(&mut task)?;
1228    }
1229    if matches!(command, Operation::Done { .. }) {
1230        crate::daemon::supersede_prior_runs(&task, home);
1231    }
1232    Ok(Some(message))
1233}
1234
1235/// Explicit owner-requested reconciliation executes nothing. Under the task
1236/// claim, prove that the exact intended condition already holds; otherwise keep
1237/// uncertainty visible. External effects require their own receipts instead.
1238fn reconcile_task_decision(queue: &Queue, home: &Path, chat: &str, id: &str) -> Result<()> {
1239    let outbox = crate::task_inquiry::Outbox::at(home);
1240    let inquiry = outbox.get(id)?;
1241    ensure!(
1242        inquiry.delivered_to.as_deref() == Some(chat)
1243            || (inquiry.task.is_empty() && inquiry.delivered_to.is_none()),
1244        "decision belongs to another chat"
1245    );
1246    let decision = inquiry.decision.context("inquiry is informational")?;
1247    if decision.status == crate::task_decision::Status::Resolved {
1248        return Ok(());
1249    }
1250    if decision
1251        .request
1252        .as_ref()
1253        .is_none_or(|request| request.starts_with("decision: "))
1254    {
1255        let source = crate::ask::Questions::at(home.join("questions")).read_history(id)?;
1256        crate::task_chat::sync_effect_receipt(home, queue, &source);
1257        ensure!(
1258            outbox
1259                .get(id)?
1260                .decision
1261                .is_some_and(|d| d.status == crate::task_decision::Status::Resolved),
1262            "source effect remains unconfirmed; no operation was replayed"
1263        );
1264        return Ok(());
1265    }
1266    let request = decision
1267        .request
1268        .context("decision has no accepted operation to reconcile")?;
1269    let command: Operation = serde_json::from_str(&request)?;
1270    if let Operation::Resume { run } = &command {
1271        reconcile_resume_decision(queue, home, &outbox, id, run)?;
1272        ensure!(
1273            outbox.get(id)?.decision.is_some_and(|d| {
1274                d.status == crate::task_decision::Status::Resolved || d.retry_safe
1275            }),
1276            "resume remains queued or executing; no operation was replayed"
1277        );
1278        return Ok(());
1279    }
1280    let (_claim, task) = claimed(queue, &inquiry.task)?;
1281    ensure!(task.repo == inquiry.repo, "decision repository changed");
1282    if let Some(receipt) = task.decision_effects.get(id) {
1283        ensure!(
1284            receipt == &request,
1285            "decision receipt binds another command"
1286        );
1287        return outbox.update_decision(id, |d| {
1288            d.applied("exact task command receipt confirmed; no operation replayed")
1289        });
1290    }
1291    let matches = match command {
1292        Operation::Hold {
1293            task: target,
1294            reason,
1295        } => {
1296            queue.resolve_id(&target)? == task.id
1297                && task.status == TaskStatus::Held
1298                && task.hold_reason.as_deref() == Some(reason.trim())
1299        }
1300        Operation::Release { task: target } => {
1301            queue.resolve_id(&target)? == task.id
1302                && task.status == TaskStatus::Queued
1303                && !task.operator_held()
1304        }
1305        Operation::Done { task: target } => {
1306            queue.resolve_id(&target)? == task.id && task.status == TaskStatus::Done
1307        }
1308        Operation::Retry {
1309            task: target,
1310            title,
1311            instruction,
1312        } => {
1313            queue.resolve_id(&target)? == task.id
1314                && task.instruction == instruction
1315                && title.as_ref().is_none_or(|title| *title == task.title)
1316                && task.status == TaskStatus::Queued
1317        }
1318        Operation::Abandon { run } => abandonment_receipt(home, &task, id, &run, &request)?,
1319        _ => anyhow::bail!(
1320            "external effects require their authoritative receipt; no operation was replayed"
1321        ),
1322    };
1323    ensure!(
1324        matches,
1325        "intended task condition is not confirmed; no operation was replayed"
1326    );
1327    outbox.update_decision(id, |d| d.applied("owner-requested reconciliation: exact intended task condition confirmed under its claim; no effect remains necessary"))
1328}
1329
1330/// Read the exact request's committed execution pass or durable pin supersession.
1331/// A transient task status alone never proves either outcome.
1332pub(crate) fn resume_started(home: &Path, task: &Task, inquiry: &str, run: &str) -> Result<bool> {
1333    ensure!(
1334        crate::run::is_run_id(run) && task.runs.iter().any(|id| id == run),
1335        "resume run ownership changed"
1336    );
1337    let state = crate::run::RunState::load_under(run, home)?;
1338    ensure!(state.id == run, "resume run identity changed");
1339    ensure!(
1340        crate::git::same_checkout(&state.repo, &task.repo)?,
1341        "resume run repository changed"
1342    );
1343    if task
1344        .superseded_resumes
1345        .get(inquiry)
1346        .is_some_and(|target| target == run)
1347    {
1348        return Ok(true);
1349    }
1350    Ok(state.decision_starts.get(inquiry).is_some_and(|index| {
1351        state
1352            .passes
1353            .get(*index)
1354            .is_some_and(|pass| pass.index == *index)
1355    }))
1356}
1357
1358/// Publication writes the pin and actions_applied marker atomically. Fence the
1359/// publisher and scheduler before treating their absence as pre-effect proof.
1360/// A published pin may already be consumed, so its absence alone is not proof.
1361fn reconcile_resume_decision(
1362    queue: &Queue,
1363    home: &Path,
1364    outbox: &crate::task_inquiry::Outbox,
1365    id: &str,
1366    run: &str,
1367) -> Result<()> {
1368    let Ok(_execution) = outbox.execution_claim(id) else {
1369        return Ok(());
1370    };
1371    reconcile_resume_claimed(queue, home, outbox, id, run)
1372}
1373
1374/// The caller holds this inquiry's execution claim, including on resubmission.
1375fn reconcile_resume_claimed(
1376    queue: &Queue,
1377    home: &Path,
1378    outbox: &crate::task_inquiry::Outbox,
1379    id: &str,
1380    run: &str,
1381) -> Result<()> {
1382    let inquiry = outbox.get(id)?;
1383    let Ok(_claim) = queue.claim(&inquiry.task) else {
1384        return Ok(());
1385    };
1386    let task = queue.get(&inquiry.task)?;
1387    ensure!(task.repo == inquiry.repo, "resume task repository changed");
1388    let decision = inquiry.decision.context("inquiry is informational")?;
1389    if decision.status == crate::task_decision::Status::Resolved {
1390        return Ok(());
1391    }
1392    if resume_started(home, &task, id, run)? {
1393        outbox.update_decision(id, |d| {
1394            d.applied("exact resume execution-start or supersession receipt confirmed")
1395        })?;
1396    } else if !task.action_applied(id)
1397        && !task.dispatched_resumes.contains_key(id)
1398        && !task.superseded_resumes.contains_key(id)
1399        && !task
1400            .resume_override
1401            .as_ref()
1402            .is_some_and(|pin| pin.question_id == id)
1403    {
1404        outbox.update_decision(id, |d| {
1405            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.")
1406        })?;
1407    }
1408    Ok(())
1409}
1410
1411fn abandonment_receipt(
1412    home: &Path,
1413    task: &Task,
1414    id: &str,
1415    run: &str,
1416    request: &str,
1417) -> Result<bool> {
1418    ensure!(
1419        task.runs.iter().any(|own| own == run),
1420        "abandon run ownership changed"
1421    );
1422    let state = crate::run::RunState::load_under(run, home)?;
1423    ensure!(state.id == run, "abandon run identity changed");
1424    ensure!(
1425        crate::git::same_checkout(&state.repo, &task.repo)?,
1426        "abandon run repository changed"
1427    );
1428    Ok(state
1429        .abandonment_receipts
1430        .get(id)
1431        .is_some_and(|receipt| receipt == request))
1432}
1433
1434fn merge_receipt(
1435    home: &Path,
1436    chat: &str,
1437    action: &crate::chat_merge::Request,
1438) -> Result<Option<serde_json::Value>> {
1439    ensure!(
1440        crate::ask::valid_asset_name(chat) && crate::ask::valid_asset_name(&action.request),
1441        "invalid merge receipt identity"
1442    );
1443    let path = home
1444        .join("chat-controls")
1445        .join(chat)
1446        .join(format!("{}.json", action.request));
1447    let bytes = match std::fs::read(path) {
1448        Ok(bytes) => bytes,
1449        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
1450        Err(error) => return Err(error.into()),
1451    };
1452    let receipt: serde_json::Value = serde_json::from_slice(&bytes)?;
1453    ensure!(
1454        receipt["action"] == serde_json::to_value(action)?,
1455        "merge receipt names another operation"
1456    );
1457    Ok(Some(receipt))
1458}
1459
1460/// Repair the decision projection from independently durable command receipts.
1461/// This starts no workers and retries no operation.
1462pub fn reconcile_decisions(queue: &Queue, home: &Path) -> Result<()> {
1463    let outbox = crate::task_inquiry::Outbox::at(home);
1464    let (inquiries, unreadable) = outbox.list_readable()?;
1465    let mut errors = Vec::new();
1466    if unreadable != 0 {
1467        errors.push(format!("{unreadable} unreadable inquiry record(s)"));
1468    }
1469    for inquiry in inquiries {
1470        let id = inquiry.id.clone();
1471        if let Err(error) = reconcile_inquiry(queue, home, &outbox, inquiry) {
1472            let message = format!(
1473                "Decision receipt reconciliation failed: {error:#}. Inspect this inquiry's receipt before retrying."
1474            );
1475            tracing::warn!("decision {id}: {message}");
1476            if let Err(error) = outbox.update_decision(&id, |d| d.fail(&message)) {
1477                tracing::warn!("decision {id} error could not be persisted: {error:#}");
1478            }
1479            errors.push(format!("{id}: {message}"));
1480        }
1481    }
1482    ensure!(
1483        errors.is_empty(),
1484        "{} decision reconciliation problem(s): {}",
1485        errors.len(),
1486        errors.join("; ")
1487    );
1488    Ok(())
1489}
1490
1491fn reconcile_inquiry(
1492    queue: &Queue,
1493    home: &Path,
1494    outbox: &crate::task_inquiry::Outbox,
1495    inquiry: crate::task_inquiry::Inquiry,
1496) -> Result<()> {
1497    use crate::task_decision::Status;
1498    let Some(decision) = inquiry.decision else {
1499        return Ok(());
1500    };
1501    if decision.status == Status::Resolved {
1502        return Ok(());
1503    }
1504    let Some(request) = decision.request else {
1505        return Ok(());
1506    };
1507    let Ok(command) = serde_json::from_str::<Operation>(&request) else {
1508        return Ok(());
1509    };
1510    if let Operation::Resume { run } = &command {
1511        return reconcile_resume_decision(queue, home, outbox, &inquiry.id, run);
1512    }
1513    let task = queue.get(&inquiry.task)?;
1514    ensure!(task.repo == inquiry.repo, "decision repository changed");
1515    if let Some(receipt) = task.decision_effects.get(&inquiry.id) {
1516        ensure!(
1517            receipt == &request,
1518            "decision receipt binds another command"
1519        );
1520        outbox.update_decision(&inquiry.id, |d| {
1521            d.applied("exact task command receipt confirmed after restart")
1522        })?;
1523        return Ok(());
1524    }
1525    let mut pending_external = false;
1526    let receipt = match command {
1527        Operation::Abandon { run } => {
1528            abandonment_receipt(home, &task, &inquiry.id, &run, &request)?
1529                .then(|| format!("run {run}: exact abandonment receipt committed"))
1530        }
1531        Operation::RerunChecks {
1532            request,
1533            run,
1534            head,
1535            workflows,
1536        } => {
1537            let chat = inquiry.delivered_to.as_deref().unwrap_or_default();
1538            let path = home
1539                .join("chat-controls")
1540                .join(chat)
1541                .join(format!("{request}.json"));
1542            let state = crate::run::RunState::load_under(&run, home)?;
1543            let action = serde_json::json!({
1544                "run": run, "repo": state.repo,
1545                "pr": state.pr.as_ref().map(|pr| pr.url.as_str()),
1546                "head": head, "runs": workflows,
1547            });
1548            std::fs::read(path)
1549                .ok()
1550                .and_then(|bytes| serde_json::from_slice::<serde_json::Value>(&bytes).ok())
1551                .filter(|receipt| receipt["status"] == "applied" && receipt["action"] == action)
1552                .map(|_| format!("chat-controls/{chat}/{request}.json: applied"))
1553        }
1554        Operation::MergePr {
1555            repo,
1556            number,
1557            head,
1558            request,
1559        } => {
1560            let action = crate::chat_merge::Request {
1561                repo,
1562                number,
1563                head,
1564                request,
1565            };
1566            let chat = inquiry
1567                .delivered_to
1568                .as_deref()
1569                .context("merge decision has no chat")?;
1570            let receipt = merge_receipt(home, chat, &action)?;
1571            pending_external = receipt
1572                .as_ref()
1573                .is_some_and(|receipt| receipt["status"] == "pending");
1574            if let Some(receipt) = &receipt
1575                && receipt["status"] != "merged"
1576                && receipt["status"] != "pending"
1577            {
1578                outbox.update_decision(&inquiry.id, |d| d.fail(&format!("Merge outcome requires reconciliation: {}. Reuse the same request ID to check only.", receipt["detail"])))?;
1579            }
1580            receipt
1581                .filter(|receipt| receipt["status"] == "merged")
1582                .map(|receipt| format!("confirmed merge receipt: {}", receipt["detail"]))
1583        }
1584        _ => None,
1585    };
1586    if let Some(receipt) = receipt {
1587        outbox.update_decision(&inquiry.id, |d| d.applied(&receipt))?;
1588    } else if decision.status == Status::InProgress
1589        && !pending_external
1590        && outbox
1591            .get(&inquiry.id)?
1592            .decision
1593            .as_ref()
1594            .is_some_and(|d| d.status == Status::InProgress)
1595    {
1596        let talks = Talks::at(home.join("talks"));
1597        let chat = inquiry
1598            .delivered_to
1599            .as_deref()
1600            .context("executing decision has no chat")?;
1601        if !talks.turn_held(chat) && !crate::chat_worker::turn_worker_active(&talks, chat) {
1602            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."))?;
1603        }
1604    }
1605    Ok(())
1606}
1607
1608/// Record the owner's choice for a decision from an open standing chat. The
1609/// chat agent interprets the owner's request directly, a merge included; no
1610/// quote, consent phrase or task ownership is required. See [`record_decision`].
1611pub fn decide(
1612    talks: &Talks,
1613    home: &Path,
1614    talk: &str,
1615    question: &str,
1616    choice: &str,
1617) -> Result<crate::ask::Question> {
1618    authorize(talks, talk, crate::queue::CHAT_NODE)?;
1619    record_decision(home, question, choice, None)
1620}
1621
1622/// Answer an open decision whose answer the machinery consumes
1623/// ([`crate::task_chat::awaits_decision`]: a merge or release approval, the
1624/// posting gate, triage, a divergence reconcile, a structured choice action).
1625/// The question must still be open and `choice` one of its offered choices;
1626/// the consumer behind it keeps its own state and transition checks.
1627fn record_decision(
1628    home: &Path,
1629    question: &str,
1630    choice: &str,
1631    title: Option<&str>,
1632) -> Result<crate::ask::Question> {
1633    use crate::ask::{Answer, Questions};
1634    let questions = Questions::at(home.join("questions"));
1635    let id = questions.resolve_id(question)?;
1636    let q = questions.get(&id)?;
1637    let queue = Queue::at(home.join("queue"));
1638    let _claims = decision_claims(&queue, &q)?;
1639    for task in queue.list() {
1640        if q.run == task.id
1641            || task.runs.contains(&q.run)
1642            || q.routed_task.as_deref() == Some(&task.id)
1643        {
1644            ensure!(
1645                !task.stale_question(&q),
1646                "question predates task repository reassignment; inspect the current task and release it for fresh execution"
1647            );
1648        }
1649    }
1650    ensure!(
1651        crate::task_chat::awaits_decision(&q),
1652        "question {} is not a decision the machinery waits on; answer it with `magi answer`",
1653        q.short()
1654    );
1655    let (q, ()) = questions.update(&q.id, |r| {
1656        if crate::task_chat::saved_reply_requires_confirmation(home, r) {
1657            ensure!(
1658                crate::task_inquiry::Outbox::at(home)
1659                    .get(&r.id)?
1660                    .decision
1661                    .is_some_and(
1662                        |decision| decision.status != crate::task_decision::Status::Resolved
1663                    ),
1664                "saved decision is settled; no effect remains necessary"
1665            );
1666            r.status = crate::ask::QuestionStatus::Open;
1667            r.answer = None;
1668            r.answered_at = None;
1669            r.answer_authority = None;
1670        }
1671        ensure!(
1672            r.status.open(),
1673            "question {} is already {}",
1674            r.short(),
1675            r.status.as_str()
1676        );
1677        let reply = r.resolve_reply(choice)?.to_owned();
1678        ensure!(
1679            crate::land::approval(Some(&reply)) != crate::land::Approval::Merge || r.merge_target.is_some()
1680                || !(r.node == crate::land::APPROVAL_NODE || (r.node == crate::bump::NOTICE_NODE && r.seat == "release-watch")),
1681            "approval has no recorded PR/head; recover its target or discuss a non-merge operation in chat"
1682        );
1683        let replacement =
1684            r.node == crate::github_text::ASK_NODE && reply == crate::github_text::USE_MY_TEXT;
1685        ensure!(
1686            replacement || title.is_none(),
1687            "--title is only valid for a publication decision's `use my text` choice"
1688        );
1689        let title = if replacement {
1690            let title =
1691                title.context("use my text needs --title with the literal replacement title")?;
1692            ensure!(
1693                !title.trim().is_empty(),
1694                "replacement title must not be empty"
1695            );
1696            Some(title.to_owned())
1697        } else {
1698            None
1699        };
1700        let answer = if r.free_text() {
1701            Answer::Text(reply)
1702        } else {
1703            Answer::Choice(reply)
1704        };
1705        r.publication_title = title;
1706        r.answer(answer)?;
1707        Ok(())
1708    })?;
1709    Ok(q)
1710}
1711
1712/// Fence idle built-in triage answers with grant admission and worker writes.
1713/// Live drivers must remain answerable (grant admission refuses them). Other
1714/// question consumers keep their own claims, including synchronous dismissal.
1715/// Every grant also rechecks answered-but-unsettled effects before acceptance.
1716pub(crate) fn decision_claims(
1717    queue: &Queue,
1718    q: &crate::ask::Question,
1719) -> Result<Vec<crate::queue::Claim>> {
1720    let mut owners: Vec<_> = queue
1721        .list()
1722        .into_iter()
1723        .filter(|task| {
1724            q.run == task.id
1725                || task.runs.contains(&q.run)
1726                || q.routed_task.as_deref() == Some(&task.id)
1727        })
1728        .map(|task| task.id)
1729        .collect();
1730    owners.sort();
1731    let mut claims = Vec::new();
1732    if matches!(
1733        q.node.as_str(),
1734        crate::triage::NODE | crate::triage::DEPS_NODE
1735    ) {
1736        for id in &owners {
1737            if queue.get(id)?.status != TaskStatus::Running {
1738                claims.push(queue.claim(id)?);
1739            }
1740        }
1741    }
1742    for id in owners {
1743        ensure!(
1744            !crate::repair_budget::reconcile::superseded_question(&queue.get(&id)?, q),
1745            "question was superseded by explicit repair receipt recovery; inspect the reconciliation receipt"
1746        );
1747    }
1748    Ok(claims)
1749}
1750
1751/// The conversation this process speaks for, or why it may not act.
1752pub fn authorize(talks: &Talks, run: &str, node: &str) -> Result<Talk> {
1753    if node != crate::queue::CHAT_NODE || run.trim().is_empty() {
1754        bail!("task control requires MAGI_NODE=chat and MAGI_RUN from a standing chat");
1755    }
1756    let id = crate::chat_watch::authorize(talks, run, node)?;
1757    talks.get(&id)
1758}
1759
1760/// The task that recorded `run` (a full run id).
1761fn run_task(queue: &Queue, run: &str) -> Result<Task> {
1762    ensure!(
1763        crate::run::is_run_id(run),
1764        "an execution command needs the full run id"
1765    );
1766    queue
1767        .list()
1768        .into_iter()
1769        .find(|t| t.runs.iter().any(|r| r == run))
1770        .with_context(|| format!("run {run} belongs to no task"))
1771}
1772
1773/// Claim a task from a full or unambiguous-prefix id and read it under the
1774/// claim, never from a lookup made before it.
1775fn claimed(queue: &Queue, reference: &str) -> Result<(crate::queue::Claim, Task)> {
1776    let id = queue.resolve_id(reference)?;
1777    let claim = queue
1778        .claim(&id)
1779        .with_context(|| format!("task {id} is claimed by a running daemon"))?;
1780    let task = queue.get(&id)?;
1781    Ok((claim, task))
1782}
1783
1784fn claimed_for_chat(
1785    queue: &Queue,
1786    reference: &str,
1787    talks: &Talks,
1788    chat: &str,
1789) -> Result<(crate::queue::Claim, Task)> {
1790    let claimed = claimed(queue, reference)?;
1791    if let crate::chat_goal::Source::Goal { id, generation } = crate::chat_goal::current_source() {
1792        let talk = talks.get(chat)?;
1793        let goal = talk
1794            .goals
1795            .iter()
1796            .find(|goal| goal.id == id)
1797            .context("unknown goal")?;
1798        goal.admit(generation)?;
1799        let task = &claimed.1;
1800        ensure!(
1801            goal.tasks.contains(&task.id),
1802            "effect targets a task outside this goal"
1803        );
1804        crate::chat_goal::require_repo(
1805            "task",
1806            &task.id,
1807            &task.repo,
1808            goal.effective_repo(&talk.repo),
1809        )?;
1810    }
1811    Ok(claimed)
1812}
1813
1814fn check_hold_release(task: &Task, operation: &str) -> Result<()> {
1815    match task.status {
1816        TaskStatus::Queued
1817        | TaskStatus::Held
1818        | TaskStatus::Failed
1819        | TaskStatus::Blocked
1820        | TaskStatus::Parked => Ok(()),
1821        TaskStatus::Done => bail!(
1822            "cannot {operation} task {} (done): completed work must not be restarted; create a new task instead",
1823            task.id
1824        ),
1825        TaskStatus::Running => bail!(
1826            "cannot {operation} task {} (running): its run may still be active; use resume or abandon for the existing run instead",
1827            task.id
1828        ),
1829    }
1830}
1831
1832/// Mark a task complete under its queue claim, as `magi task done` does.
1833pub fn done(queue: &Queue, home: &Path, reference: &str) -> Result<Task> {
1834    done_claimed(queue, home, claimed(queue, reference)?)
1835}
1836
1837fn done_claimed(
1838    queue: &Queue,
1839    home: &Path,
1840    (_claim, mut task): (crate::queue::Claim, Task),
1841) -> Result<Task> {
1842    task.succeed();
1843    // Manual completion also retires earlier attempts when the latest one landed.
1844    crate::daemon::supersede_prior_runs(&task, home);
1845    queue.put(&mut task)?;
1846    Ok(task)
1847}
1848
1849/// Change priority under the same claim and state check as the terminal route.
1850pub fn set_priority(queue: &Queue, reference: &str, priority: i32) -> Result<Task> {
1851    priority_claimed(queue, claimed(queue, reference)?, priority)
1852}
1853
1854fn priority_claimed(
1855    queue: &Queue,
1856    (_claim, mut task): (crate::queue::Claim, Task),
1857    priority: i32,
1858) -> Result<Task> {
1859    task.set_priority(priority)?;
1860    queue.put(&mut task)?;
1861    Ok(task)
1862}
1863
1864/// Hold a task for the owner.
1865pub fn hold(queue: &Queue, reference: &str, reason: &str) -> Result<Task> {
1866    hold_claimed(queue, claimed(queue, reference)?, reason)
1867}
1868
1869fn hold_claimed(
1870    queue: &Queue,
1871    (_claim, mut task): (crate::queue::Claim, Task),
1872    reason: &str,
1873) -> Result<Task> {
1874    check_hold_release(&task, "hold")?;
1875    let reason = reason.trim();
1876    task.hold_manual((!reason.is_empty()).then(|| reason.to_owned()));
1877    queue.put(&mut task)?;
1878    Ok(task)
1879}
1880
1881/// Release a task (the same transition as `magi task release`: the attempt
1882/// count restarts, the history stays). An operator hold is released too: the
1883/// owner asked for it.
1884pub fn release(queue: &Queue, reference: &str) -> Result<Task> {
1885    release_claimed(queue, claimed(queue, reference)?)
1886}
1887
1888fn release_claimed(queue: &Queue, (_claim, mut task): (crate::queue::Claim, Task)) -> Result<Task> {
1889    check_hold_release(&task, "release")?;
1890    crate::base_sync_recovery::ensure_generic_release(queue, &task)?;
1891    let run = task.execution_runs().last().cloned();
1892    let preserved = match run {
1893        Some(run) => crate::repair_budget::queue_resumption(queue, &mut task, &run)?,
1894        None => false,
1895    };
1896    if !preserved {
1897        task.release_operator("chat", None);
1898    }
1899    queue.put(&mut task)?;
1900    Ok(task)
1901}
1902
1903/// Change a queued or held task's instruction and queue it again, in one
1904/// save under one claim. Only what [`Task::edit`] allows can be retried; the
1905/// attempt count follows [`Task::release`] (restarts), while runs, passes and
1906/// the resumption history are kept.
1907pub fn retry(
1908    queue: &Queue,
1909    reference: &str,
1910    title: Option<String>,
1911    instruction: &str,
1912) -> Result<Task> {
1913    retry_claimed(queue, claimed(queue, reference)?, title, instruction)
1914}
1915
1916fn retry_claimed(
1917    queue: &Queue,
1918    (_claim, mut task): (crate::queue::Claim, Task),
1919    title: Option<String>,
1920    instruction: &str,
1921) -> Result<Task> {
1922    ensure!(
1923        !instruction.trim().is_empty(),
1924        "the new instruction is empty"
1925    );
1926    if let Some(state) = crate::base_sync_recovery::held_run(queue, &task)
1927        && state
1928            .base_sync_recovery
1929            .stop
1930            .as_ref()
1931            .is_some_and(|stop| stop.kind == crate::base_sync_recovery::StopKind::Conflict)
1932    {
1933        anyhow::bail!(
1934            "retry cannot authorize editing a retained base-sync stop. {} Keep the retained review criteria and use a dedicated repair grant for the narrow resolution.",
1935            state.base_sync_next_action()
1936        );
1937    }
1938    crate::base_sync_recovery::ensure_generic_release(queue, &task)?;
1939    let title = title.unwrap_or_else(|| crate::queue::title_from(instruction, 72));
1940    task.edit(title, instruction.to_owned())?;
1941    task.release_operator("chat", None);
1942    queue.put(&mut task)?;
1943    Ok(task)
1944}
1945
1946/// Resume a stopped, blocked or parked run (its task's latest). Only queues
1947/// the pinned resume; returns the owning task.
1948pub fn resume(queue: &Queue, home: &Path, run: &str) -> Result<Task> {
1949    let task = run_task(queue, run)?;
1950    ensure!(
1951        task.execution_runs().last().map(String::as_str) == Some(run),
1952        "only the task's latest run can be resumed"
1953    );
1954    crate::resume::validate(home, run)?;
1955    ensure!(
1956        crate::resume::pin_queued(queue, run, None, None)?,
1957        "no queued task owns run {run}"
1958    );
1959    queue.get(&task.id)
1960}
1961
1962// These reads and input checks cannot start an effect. Keep them shared by
1963// decision acceptance and execution so invalid input never pins a new request.
1964fn rerun_preflight(
1965    queue: &Queue,
1966    home: &Path,
1967    run: &str,
1968    request: &str,
1969) -> Result<crate::run::RunState> {
1970    run_task(queue, run)?;
1971    let state = crate::run::RunState::load_under(run, home)?;
1972    ensure!(state.pr.is_some(), "the run recorded no pull request");
1973    ensure!(
1974        crate::ask::valid_asset_name(request),
1975        "request must be a safe filename of at most 64 bytes"
1976    );
1977    Ok(state)
1978}
1979
1980/// チャットのリクエスト単位で受付記録を残し、共通遷移でチェックを再実行する。
1981pub async fn rerun_checks(
1982    queue: &Queue,
1983    home: &Path,
1984    talk: &str,
1985    run: &str,
1986    request: &str,
1987    head: &str,
1988    workflows: &[String],
1989) -> Result<Vec<String>> {
1990    let state = rerun_preflight(queue, home, run, request).map_err(BeforeEffect)?;
1991    let dir = home.join("chat-controls").join(talk);
1992    std::fs::create_dir_all(&dir)?;
1993    let lock = std::fs::OpenOptions::new()
1994        .create(true)
1995        .truncate(false)
1996        .write(true)
1997        .open(dir.join(format!("{request}.lock")))?;
1998    crate::pr_head::try_lock_file(&lock).map_err(|error| BeforeEffect(error.into()))?;
1999    let path = dir.join(format!("{request}.json"));
2000    let pr = &state
2001        .pr
2002        .as_ref()
2003        .context("the run recorded no pull request")?
2004        .url;
2005    let action = serde_json::json!({
2006        "run": run, "repo": state.repo, "pr": pr, "head": head, "runs": workflows
2007    });
2008    if path.exists() {
2009        let prior: serde_json::Value = serde_json::from_slice(&std::fs::read(&path)?)?;
2010        if prior["action"] != action {
2011            return Err(BeforeEffect(anyhow::anyhow!(
2012                "request ID already binds a different operation"
2013            ))
2014            .into());
2015        }
2016        ensure!(
2017            prior["status"] == "applied",
2018            "previous request has an uncertain result; inspect its receipt before a new request"
2019        );
2020        return Ok(workflows.to_vec());
2021    }
2022    let record = |status: &str| -> Result<()> {
2023        let tmp = path.with_extension("tmp");
2024        std::fs::write(
2025            &tmp,
2026            serde_json::to_vec(&serde_json::json!({
2027                "action": action, "status": status
2028            }))?,
2029        )?;
2030        std::fs::rename(tmp, &path)?;
2031        Ok(())
2032    };
2033    let operation = format!("chat:{talk}:{request}");
2034    let started = std::sync::atomic::AtomicBool::new(false);
2035    crate::daemon::rerun_checks_once(home, &operation, &state.repo, pr, head, workflows, || {
2036        // Once a receipt exists, failure must remain uncertain even if the
2037        // external command has not returned yet.
2038        started.store(true, std::sync::atomic::Ordering::SeqCst);
2039        record("started")
2040    })
2041    .await
2042    .map_err(|error| {
2043        if started.load(std::sync::atomic::Ordering::SeqCst) {
2044            error
2045        } else {
2046            anyhow::Error::new(BeforeEffect(error))
2047        }
2048    })?;
2049    record("applied")?;
2050    Ok(workflows.to_vec())
2051}
2052
2053/// Abandon a recorded run whose driver is proven gone. No confirmation phrase
2054/// is needed; an unknown or live driver is refused by
2055/// [`crate::driver::abandon_proven_dead`], so a working driver is never broken.
2056pub fn abandon(queue: &Queue, home: &Path, run: &str) -> Result<()> {
2057    run_task(queue, run)?;
2058    crate::driver::abandon_proven_dead(home, run)
2059}
2060
2061/// One line a person or agent can read after a successful command.
2062pub fn describe(task: &Task, what: &str) -> String {
2063    let status = match task.status {
2064        TaskStatus::Queued => "queued",
2065        _ => task.status.as_str(),
2066    };
2067    format!("{what} {} {} ({status})", task.short(), task.title)
2068}
2069
2070#[cfg(test)]
2071mod tests {
2072    use super::*;
2073    use crate::queue::Source;
2074    use jiff::Timestamp;
2075
2076    fn talk(talks: &Talks, id: &str) -> Talk {
2077        let mut t: Talk = serde_json::from_value(serde_json::json!({
2078            "schema":1,"id":id,"repo":".","agent":"worker","status":"open","turns":[],
2079            "created_at":Timestamp::now(),"updated_at":Timestamp::now(),
2080            "seat":crate::agent::SeatState::new("talk","worker",1)
2081        }))
2082        .unwrap();
2083        talks.put(&mut t).unwrap();
2084        t
2085    }
2086
2087    fn filed(queue: &Queue, talk: &str, text: &str) -> Task {
2088        let mut t = Task::new(
2089            text.into(),
2090            text.into(),
2091            ".".into(),
2092            Source::Agent {
2093                run: talk.into(),
2094                node: crate::queue::CHAT_NODE.into(),
2095            },
2096        );
2097        queue.put(&mut t).unwrap();
2098        t
2099    }
2100
2101    #[test]
2102    fn ownerless_import_reconciliation_requires_effect_evidence_not_saved_consent() {
2103        use crate::ask::{Answer, Question, Questions};
2104        let home = tempfile::tempdir().unwrap();
2105        let home = home.path();
2106        let queue = Queue::at(home.join("queue"));
2107        let talks = Talks::at(home.join("talks"));
2108        let questions = Questions::at(home.join("questions"));
2109        let mut q = Question::new(
2110            String::new(),
2111            crate::bump::NOTICE_NODE.into(),
2112            "release-watch".into(),
2113            "Historical release hold".into(),
2114            String::new(),
2115            vec!["hold".into()],
2116        );
2117        q.answer(Answer::Choice("hold".into())).unwrap();
2118        q.answer_delivered = true;
2119        questions.put(&mut q).unwrap();
2120        let source = std::fs::read(questions.path_of(&q.id)).unwrap();
2121        crate::task_chat::sweep(&queue, &talks, &questions, home);
2122        assert!(reconcile_task_decision(&queue, home, "authorized-chat", &q.id).is_err());
2123        let outbox = crate::task_inquiry::Outbox::at(home);
2124        assert_eq!(
2125            outbox.get(&q.id).unwrap().decision.unwrap().status,
2126            crate::task_decision::Status::RetryNeeded
2127        );
2128        let dir = home.join("release-watch-receipts");
2129        std::fs::create_dir_all(&dir).unwrap();
2130        std::fs::write(
2131            dir.join(format!("{}.json", q.id)),
2132            serde_json::to_vec(&crate::release_watch::WatchState {
2133                applied: vec![q.id.clone()],
2134                ..Default::default()
2135            })
2136            .unwrap(),
2137        )
2138        .unwrap();
2139        for _ in 0..2 {
2140            reconcile_task_decision(&queue, home, "authorized-chat", &q.id).unwrap();
2141        }
2142        let decision = outbox.get(&q.id).unwrap().decision.unwrap();
2143        assert_eq!(decision.status, crate::task_decision::Status::Resolved);
2144        assert!(decision.request.is_none());
2145        assert!(decision.source_answer_at.is_none());
2146        assert_eq!(std::fs::read(questions.path_of(&q.id)).unwrap(), source);
2147        assert!(queue.list().is_empty());
2148        assert!(talks.list().is_empty());
2149    }
2150
2151    #[test]
2152    fn resume_recovery_waits_for_the_inquiry_publisher() {
2153        let tmp = tempfile::tempdir().unwrap();
2154        let queue = Queue::at(tmp.path().join("queue"));
2155        let mut task = filed(&queue, "talk-a", "work");
2156        let mut state = crate::run::RunState::new(
2157            task.repo.clone(),
2158            "main".into(),
2159            "base".into(),
2160            "work".into(),
2161            crate::config::Config::default(),
2162        );
2163        state.status = crate::run::RunStatus::Blocked;
2164        state.driver_exited = true;
2165        state.save_under(tmp.path()).unwrap();
2166        task.runs.push(state.id.clone());
2167        queue.put(&mut task).unwrap();
2168        let outbox = crate::task_inquiry::Outbox::at(tmp.path());
2169        let inquiry = outbox
2170            .file(
2171                &task,
2172                Some(state.id.clone()),
2173                "resume".into(),
2174                "Resume?",
2175                "",
2176            )
2177            .unwrap();
2178        let request = serde_json::to_string(&Operation::Resume {
2179            run: state.id.clone(),
2180        })
2181        .unwrap();
2182        outbox
2183            .update_decision(&inquiry.id, |d| {
2184                d.accept(&request)?;
2185                d.start()
2186            })
2187            .unwrap();
2188        let before = outbox.get(&inquiry.id).unwrap().decision.unwrap();
2189        let publisher = outbox.execution_claim(&inquiry.id).unwrap();
2190        reconcile_decisions(&queue, tmp.path()).unwrap();
2191        assert_eq!(outbox.get(&inquiry.id).unwrap().decision.unwrap(), before);
2192        drop(publisher);
2193        reconcile_decisions(&queue, tmp.path()).unwrap();
2194        let recovered = outbox.get(&inquiry.id).unwrap().decision.unwrap();
2195        assert_eq!(recovered.status, crate::task_decision::Status::RetryNeeded);
2196        assert!(recovered.retry_safe);
2197    }
2198
2199    #[tokio::test]
2200    async fn resume_receipt_matches_checkout_root_not_filing_directory() {
2201        use crate::task_decision::Status;
2202        let tmp = tempfile::tempdir().unwrap();
2203        let home = tmp.path();
2204        let repo = home.join("checkout");
2205        let subdir = repo.join("src");
2206        let foreign = home.join("foreign");
2207        std::fs::create_dir_all(&subdir).unwrap();
2208        std::fs::create_dir(&foreign).unwrap();
2209        for checkout in [&repo, &foreign] {
2210            crate::git::git(checkout, &["init", "-q"]).await.unwrap();
2211        }
2212        let queue = Queue::at(home.join("queue"));
2213        let mut task = Task::new("work".into(), "work".into(), subdir, Source::Human);
2214        let mut state = crate::run::RunState::new(
2215            repo,
2216            "main".into(),
2217            "base".into(),
2218            "work".into(),
2219            crate::config::Config::default(),
2220        );
2221        state.reserve_under(home).unwrap();
2222        task.runs.push(state.id.clone());
2223        queue.put(&mut task).unwrap();
2224        let outbox = crate::task_inquiry::Outbox::at(home);
2225        let inquiry = outbox
2226            .file(
2227                &task,
2228                Some(state.id.clone()),
2229                "resume".into(),
2230                "Resume?",
2231                "",
2232            )
2233            .unwrap();
2234        let request = serde_json::to_string(&Operation::Resume {
2235            run: state.id.clone(),
2236        })
2237        .unwrap();
2238        outbox
2239            .update_decision(&inquiry.id, |d| {
2240                d.accept(&request)?;
2241                d.start()
2242            })
2243            .unwrap();
2244        task.dispatched_resumes
2245            .insert(inquiry.id.clone(), state.id.clone());
2246        queue.put(&mut task).unwrap();
2247        reconcile_decisions(&queue, home).unwrap();
2248        assert_eq!(
2249            outbox.get(&inquiry.id).unwrap().decision.unwrap().status,
2250            Status::InProgress
2251        );
2252
2253        state.carry_dispatched_resumes(&task);
2254        state.begin_pass();
2255        state.save_under(home).unwrap();
2256        let mut reassigned = task.clone();
2257        reassigned.repo = foreign;
2258        assert!(resume_started(home, &reassigned, &inquiry.id, &state.id).is_err());
2259        reconcile_decisions(&queue, home).unwrap();
2260        assert_eq!(
2261            outbox.get(&inquiry.id).unwrap().decision.unwrap().status,
2262            Status::Resolved
2263        );
2264    }
2265
2266    #[test]
2267    fn only_the_chat_seat_of_an_open_talk_is_authorized() {
2268        let tmp = tempfile::tempdir().unwrap();
2269        let talks = Talks::at(tmp.path().join("talks"));
2270        let t = talk(&talks, "talk-a");
2271        assert!(authorize(&talks, &t.id, "chat").is_ok());
2272        assert!(authorize(&talks, &t.id, "deputy").is_err());
2273        assert!(authorize(&talks, &t.id, "").is_err());
2274        assert!(authorize(&talks, "", "chat").is_err());
2275        assert!(
2276            authorize(&talks, "talk-", "chat").is_err(),
2277            "prefix is not an id"
2278        );
2279    }
2280
2281    #[test]
2282    fn tasks_of_any_origin_are_controlled_on_request() {
2283        let tmp = tempfile::tempdir().unwrap();
2284        let queue = Queue::at(tmp.path().join("queue"));
2285        let theirs = filed(&queue, "talk-b", "theirs");
2286        let mut hand = Task::new("h".into(), "h".into(), ".".into(), Source::Human);
2287        hand.hold_manual(Some("operator".into()));
2288        queue.put(&mut hand).unwrap();
2289        // Another chat's task and an operator-held human task are the owner's
2290        // work too: the request goes through without any ownership scope.
2291        assert_eq!(
2292            hold(&queue, &theirs.id, "wait").unwrap().status,
2293            TaskStatus::Held
2294        );
2295        assert_eq!(
2296            release(&queue, &hand.id).unwrap().status,
2297            TaskStatus::Queued
2298        );
2299        let again = retry(&queue, &theirs.id, None, "new").unwrap();
2300        assert_eq!(again.instruction, "new");
2301        assert_eq!(again.status, TaskStatus::Queued);
2302    }
2303
2304    #[test]
2305    fn hold_then_release_keeps_history_and_restarts_attempts() {
2306        let tmp = tempfile::tempdir().unwrap();
2307        let queue = Queue::at(tmp.path().join("queue"));
2308        let mut t = filed(&queue, "talk-a", "work");
2309        t.attempts = 3;
2310        t.runs.push("20260101-000000-aaaa".into());
2311        queue.put(&mut t).unwrap();
2312        let held = hold(&queue, &t.id, "owner asked").unwrap();
2313        assert_eq!(held.status, TaskStatus::Held);
2314        assert_eq!(held.hold_reason.as_deref(), Some("owner asked"));
2315        let back = release(&queue, &t.id).unwrap();
2316        assert_eq!(back.status, TaskStatus::Queued);
2317        assert_eq!(back.attempts, 0);
2318        assert_eq!(back.runs, t.runs);
2319        assert!(back.resumption.is_some());
2320    }
2321
2322    #[test]
2323    fn hold_and_release_refuse_done_and_running_without_saving() {
2324        let tmp = tempfile::tempdir().unwrap();
2325        let queue = Queue::at(tmp.path().join("queue"));
2326        for status in [TaskStatus::Done, TaskStatus::Running] {
2327            let mut t = filed(&queue, "talk-a", "work");
2328            t.start("20260101-000000-aaaa".into());
2329            if status == TaskStatus::Done {
2330                t.succeed();
2331            }
2332            queue.put(&mut t).unwrap();
2333            let before = std::fs::read(queue.path_of(&t.id)).unwrap();
2334            for operation in ["hold", "release"] {
2335                let error = if operation == "hold" {
2336                    hold(&queue, &t.id, "owner asked")
2337                } else {
2338                    release(&queue, &t.id)
2339                }
2340                .unwrap_err()
2341                .to_string();
2342                assert!(error.contains(operation), "{error}");
2343                assert!(error.contains(&t.id), "{error}");
2344                assert!(error.contains(status.as_str()), "{error}");
2345                let guidance = if status == TaskStatus::Done {
2346                    "create a new task"
2347                } else {
2348                    "use resume or abandon"
2349                };
2350                assert!(error.contains(guidance), "{error}");
2351                assert_eq!(std::fs::read(queue.path_of(&t.id)).unwrap(), before);
2352            }
2353        }
2354    }
2355
2356    #[test]
2357    fn hold_and_release_allow_unfinished_inactive_tasks() {
2358        let tmp = tempfile::tempdir().unwrap();
2359        let queue = Queue::at(tmp.path().join("queue"));
2360        for status in [
2361            TaskStatus::Queued,
2362            TaskStatus::Held,
2363            TaskStatus::Failed,
2364            TaskStatus::Blocked,
2365            TaskStatus::Parked,
2366        ] {
2367            for operation in ["hold", "release"] {
2368                let mut t = filed(&queue, "talk-a", "work");
2369                t.status = status;
2370                t.hold_reason = Some("old reason".into());
2371                t.attempts = 3;
2372                t.runs.push("20260101-000000-aaaa".into());
2373                queue.put(&mut t).unwrap();
2374                let changed = if operation == "hold" {
2375                    let held = hold(&queue, &t.id, " new reason ").unwrap();
2376                    assert_eq!(held.status, TaskStatus::Held);
2377                    assert_eq!(held.hold_reason.as_deref(), Some("new reason"));
2378                    assert_eq!(held.attempts, t.attempts);
2379                    held
2380                } else {
2381                    let released = release(&queue, &t.id).unwrap();
2382                    assert_eq!(released.status, TaskStatus::Queued);
2383                    assert_eq!(released.attempts, 0);
2384                    assert_eq!(released.resumption.as_ref().unwrap().source, "chat");
2385                    released
2386                };
2387                assert_eq!(changed.runs, t.runs);
2388                assert_eq!(queue.get(&t.id).unwrap().status, changed.status);
2389            }
2390        }
2391    }
2392
2393    #[test]
2394    fn retry_edits_and_requeues_in_one_save() {
2395        let tmp = tempfile::tempdir().unwrap();
2396        let queue = Queue::at(tmp.path().join("queue"));
2397        let mut t = filed(&queue, "talk-a", "old text");
2398        t.runs.push("20260101-000000-aaaa".into());
2399        t.attempts = 2;
2400        t.hold_manual(Some("stopped".into()));
2401        queue.put(&mut t).unwrap();
2402        let again = retry(&queue, &t.id, None, "new text").unwrap();
2403        assert_eq!(again.instruction, "new text");
2404        assert_eq!(again.status, TaskStatus::Queued);
2405        assert_eq!(again.attempts, 0);
2406        assert_eq!(again.runs, t.runs, "run history is kept");
2407        assert_eq!(again.resumption.as_ref().unwrap().source, "chat");
2408        assert_eq!(again.resumption.as_ref().unwrap().instruction, "new text");
2409        // A running task cannot be edited: nothing is changed.
2410        let mut running = filed(&queue, "talk-a", "busy");
2411        running.start("20260101-000000-bbbb".into());
2412        queue.put(&mut running).unwrap();
2413        assert!(retry(&queue, &running.id, None, "x").is_err());
2414        assert_eq!(queue.get(&running.id).unwrap().instruction, "busy");
2415        assert!(retry(&queue, &t.id, None, "  ").is_err());
2416    }
2417
2418    #[test]
2419    fn execution_commands_need_the_full_id_of_a_recorded_run() {
2420        let tmp = tempfile::tempdir().unwrap();
2421        let queue = Queue::at(tmp.path().join("queue"));
2422        let mut t = filed(&queue, "talk-b", "work");
2423        t.runs.push("20260101-000000-aaaa".into());
2424        queue.put(&mut t).unwrap();
2425        assert_eq!(
2426            run_task(&queue, "20260101-000000-aaaa").unwrap().id,
2427            t.id,
2428            "any chat may address another chat's run"
2429        );
2430        assert!(run_task(&queue, "aaaa").is_err());
2431        assert!(run_task(&queue, "20260101-000000-bbbb").is_err());
2432        assert!(resume(&queue, tmp.path(), "aaaa").is_err());
2433    }
2434
2435    #[test]
2436    fn abandon_needs_no_phrase_but_refuses_unrecorded_and_unknown_runs() {
2437        let tmp = tempfile::tempdir().unwrap();
2438        let queue = Queue::at(tmp.path().join("queue"));
2439        let mut t = filed(&queue, "talk-b", "work");
2440        t.runs.push("20260101-000000-aaaa".into());
2441        queue.put(&mut t).unwrap();
2442        // A run no task recorded is refused before liveness is judged.
2443        assert!(abandon(&queue, tmp.path(), "20260101-000000-bbbb").is_err());
2444        // A recorded run whose driver is not proven dead (here: no state to
2445        // judge at all) is never abandoned.
2446        assert!(abandon(&queue, tmp.path(), "20260101-000000-aaaa").is_err());
2447    }
2448}
2449
2450#[cfg(test)]
2451mod goal_admission_tests {
2452    use super::*;
2453
2454    #[tokio::test]
2455    async fn goal_effects_require_current_generation_scope_and_no_new_owner_input() {
2456        let tmp = tempfile::tempdir().unwrap();
2457        let talks = Talks::at(tmp.path().join("talks"));
2458        let queue = Queue::at(tmp.path().join("queue"));
2459        let target = tmp.path().join("target");
2460        std::fs::create_dir(&target).unwrap();
2461        crate::git::git(&target, &["init", "-q"]).await.unwrap();
2462        let mut talk = crate::talk::seeded_for_test("goal-effect", tmp.path().into());
2463        talk.turns.push(
2464            serde_json::from_value(serde_json::json!({
2465                "sender": "operator", "who": "operator", "body": "Follow this task through",
2466                "at": jiff::Timestamp::now()
2467            }))
2468            .unwrap(),
2469        );
2470        talks.put(&mut talk).unwrap();
2471        let mut task = Task::new(
2472            "work".into(),
2473            "work".into(),
2474            target.clone(),
2475            crate::queue::Source::Agent {
2476                run: talk.id.clone(),
2477                node: crate::queue::CHAT_NODE.into(),
2478            },
2479        );
2480        queue.put(&mut task).unwrap();
2481        let mut unrelated = Task::new(
2482            "other".into(),
2483            "other".into(),
2484            target.clone(),
2485            crate::queue::Source::Agent {
2486                run: talk.id.clone(),
2487                node: crate::queue::CHAT_NODE.into(),
2488            },
2489        );
2490        queue.put(&mut unrelated).unwrap();
2491        crate::chat_goal::apply(
2492            &queue,
2493            tmp.path(),
2494            &talks,
2495            &talk.id,
2496            &crate::chat_goal::Source::Input { turn: 0 },
2497            crate::chat_goal::Command::Establish {
2498                id: "g".into(),
2499                purpose: "Deliver this task".into(),
2500                scope: "This task only".into(),
2501                condition: "Verified delivery".into(),
2502                completion: crate::chat_goal::Completion::TasksDone,
2503                repo: Some(target),
2504                tasks: vec![task.id.clone()],
2505                runs: vec![],
2506                watches: vec![],
2507            },
2508        )
2509        .await
2510        .unwrap();
2511        talks
2512            .mutate(&talk.id, |talk| {
2513                let boundary = talk.turns.len();
2514                let goal = &mut talk.goals[0];
2515                goal.wake = 1;
2516                goal.started = Some(1);
2517                goal.launch_turns = Some(boundary);
2518                Ok(())
2519            })
2520            .unwrap();
2521        let source = crate::chat_goal::Source::Goal {
2522            id: "g".into(),
2523            generation: 1,
2524        };
2525        assert!(
2526            execute_authenticated(
2527                &queue,
2528                tmp.path(),
2529                &talks,
2530                &talk.id,
2531                source.clone(),
2532                Operation::Priority {
2533                    task: unrelated.id.clone(),
2534                    priority: 8
2535                }
2536            )
2537            .await
2538            .is_err()
2539        );
2540        execute_authenticated(
2541            &queue,
2542            tmp.path(),
2543            &talks,
2544            &talk.id,
2545            source.clone(),
2546            Operation::Priority {
2547                task: task.id.clone(),
2548                priority: 3,
2549            },
2550        )
2551        .await
2552        .unwrap();
2553        let hold = Operation::Hold {
2554            task: task.id.clone(),
2555            reason: "pause".into(),
2556        };
2557        crate::chat_goal::with_source(source.clone(), async {
2558            // Reassignment publishes under this same claim, between the first
2559            // admission and the mutation's claim acquisition.
2560            admit_goal_operation(&queue, tmp.path(), &talks, &talk.id, &hold).unwrap();
2561            let original = task.repo.clone();
2562            {
2563                let claim = queue.claim(&task.id).unwrap();
2564                task = queue.get(&task.id).unwrap();
2565                task.repo = talk.repo.clone();
2566                queue.put(&mut task).unwrap();
2567                drop(claim);
2568            }
2569            let result = claimed_for_chat(&queue, &task.id, &talks, &talk.id)
2570                .and_then(|claimed| hold_claimed(&queue, claimed, "pause"));
2571            assert!(result.unwrap_err().to_string().contains(&task.id));
2572            assert_eq!(queue.get(&task.id).unwrap().status, TaskStatus::Queued);
2573            task.repo = original;
2574            queue.put(&mut task).unwrap();
2575        })
2576        .await;
2577        talks
2578            .mutate(&talk.id, |talk| {
2579                talk.turns.push(serde_json::from_value(serde_json::json!({
2580                    "sender": "operator", "who": "operator", "body": "Stop",
2581                    "at": jiff::Timestamp::now()
2582                }))?);
2583                Ok(())
2584            })
2585            .unwrap();
2586        assert!(
2587            execute_authenticated(
2588                &queue,
2589                tmp.path(),
2590                &talks,
2591                &talk.id,
2592                source.clone(),
2593                Operation::Priority {
2594                    task: task.id.clone(),
2595                    priority: 9
2596                }
2597            )
2598            .await
2599            .is_err()
2600        );
2601        talks
2602            .mutate(&talk.id, |talk| {
2603                talk.turns.pop();
2604                talk.goals[0].state = crate::chat_goal::State::Stopped;
2605                talk.goals[0].wake = 2;
2606                talk.goals[0].started = None;
2607                Ok(())
2608            })
2609            .unwrap();
2610        assert!(
2611            execute_authenticated(
2612                &queue,
2613                tmp.path(),
2614                &talks,
2615                &talk.id,
2616                source,
2617                Operation::Priority {
2618                    task: task.id.clone(),
2619                    priority: 9
2620                }
2621            )
2622            .await
2623            .is_err()
2624        );
2625        assert_eq!(queue.get(&task.id).unwrap().priority, 3);
2626    }
2627}