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