Skip to main content

magi/
chat_control.rs

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