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