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