Skip to main content

magi/
task_chat.rs

1//! Durable task-decision outbox. Questions remain the transport from restricted
2//! seats; only the daemon writes the task link and the talk's own draft.
3use anyhow::{Context, Result};
4use std::path::Path;
5
6use crate::{
7    ask::{Question, Questions},
8    config::Config,
9    queue::{Queue, Task},
10    talk::{self, Talks},
11};
12
13/// Never guess when more than one task claims the same run.
14pub fn task_of(q: &Question, tasks: &[Task]) -> Option<String> {
15    let mut matching = tasks
16        .iter()
17        .filter(|t| t.id == q.run || t.runs.contains(&q.run));
18    let task = matching.next()?;
19    matching.next().is_none().then(|| task.id.clone())
20}
21
22/// Informational bump notices have no decision. Every actionable task inquiry
23/// routes to chat, including recovery of approvals without a saved target.
24pub(crate) fn chat_routable(q: &Question) -> bool {
25    q.node != crate::bump::NOTICE_NODE
26        || q.merge_target.is_some()
27        || (q.seat == "release-watch" && !q.choices.is_empty())
28}
29
30/// Routed questions whose answer is consumed by machinery (the posting gate,
31/// the branch-divergence reconcile, the release watcher) rather than by a
32/// step-1 control command. They stay open after delivery and the chat settles
33/// them with `magi task control decide`, including merge and recovery
34/// decisions: the agent records the owner's request as it is.
35pub fn awaits_decision(q: &Question) -> bool {
36    q.node == crate::land::APPROVAL_NODE
37        || q.merge_target.is_some()
38        || (chat_routable(q)
39            // A structured action (done, resume, requeue ...) is applied by the
40            // daemon from the recorded answer, so the record must stay open.
41            && (!q.actions.is_empty()
42                || q.node == crate::github_text::ASK_NODE
43                || q.node == crate::triage::NODE
44                || q.node == crate::triage::DEPS_NODE
45                || (q.node == crate::reconcile::NODE && q.seat == crate::reconcile::SEAT)
46                || (q.node == crate::bump::NOTICE_NODE && q.seat == "release-watch")))
47}
48
49/// Also recognize legacy and watch-linked records before the first sweep.
50pub(crate) fn routes(q: &Question, home: &Path) -> bool {
51    if q.routed_task.is_some() {
52        return true;
53    }
54    if standalone_inquiry(home, q) {
55        return false;
56    }
57    if !q.status.open() || !chat_routable(q) {
58        return false;
59    }
60    let tasks = Queue::at(home.join("queue")).list();
61    let watches = crate::release_watch::states_for_questions(home, std::slice::from_ref(q));
62    task_of_with_watches(q, &tasks, &watches).is_some()
63}
64
65/// Shared task destination reservation for decisions and attention reports.
66pub(crate) fn destination(
67    queue: &Queue,
68    talks: &Talks,
69    task_id: &str,
70) -> Result<(Task, talk::Talk)> {
71    destination_checked(queue, talks, task_id, |_| Ok(()))
72}
73
74/// Validate an inquiry's ownership inside the task destination reservation.
75pub(crate) fn destination_checked(
76    queue: &Queue,
77    talks: &Talks,
78    task_id: &str,
79    check: impl FnOnce(&Task) -> Result<()>,
80) -> Result<(Task, talk::Talk)> {
81    let mut reserved = None;
82    let mut invalid = None;
83    queue.modify(task_id, |task| {
84        if let Err(error) = check(task) {
85            invalid = Some(error);
86            return false;
87        }
88        let associated = task
89            .chat
90            .clone()
91            .or_else(|| task.filed_by_chat().map(str::to_owned))
92            .or_else(|| crate::consult::chat_talk_of(&queue.list(), task));
93        // Persist ownership before any talk operation. A failed delivery keeps
94        // this reservation so the next sweep uses exactly the same destination.
95        let id = associated.unwrap_or_else(|| format!("task-{}", task.id));
96        let changed = task.chat.as_ref() != Some(&id);
97        task.chat = Some(id.clone());
98        reserved = Some((task.clone(), id));
99        changed
100    })?;
101    if let Some(error) = invalid {
102        return Err(error);
103    }
104    let (task, id) = reserved.context("task chat destination was not reserved")?;
105    let chat = destination_in(talks, &task.repo, &id)?;
106    Ok((task, chat))
107}
108
109/// Stable IDs also reserve run-only and home-wide operations conversations.
110/// Creation is serialized by `begin_with_id`; the first repo context persists.
111pub(crate) fn destination_in(talks: &Talks, repo: &Path, id: &str) -> Result<talk::Talk> {
112    let load = |id: &str| -> Result<talk::Talk> {
113        if talks.path_of(id).exists() {
114            talks.get(id)
115        } else {
116            let (cfg, _) = Config::discover(repo, None)?;
117            talk::begin_with_id(
118                talks,
119                &cfg,
120                repo.to_path_buf(),
121                None,
122                &talk::Preferred {
123                    agent: None,
124                    persona: None,
125                    implementers: Some(1),
126                },
127                Some(id.to_owned()),
128            )
129        }
130    };
131    load(id)
132}
133
134/// Reserve the destination under the task lock, then deliver without it.
135/// A stable creation id and persisted link let retries recover interrupted delivery.
136/// Never wait for a talk lock while holding the task write lock.
137pub fn post(
138    queue: &Queue,
139    talks: &Talks,
140    home: &Path,
141    task_id: &str,
142    q: &Question,
143) -> Result<String> {
144    let task = queue.get(task_id)?;
145    let run = if q.run == task.id {
146        task.runs.last().map(String::as_str).unwrap_or("none")
147    } else {
148        &q.run
149    };
150    let facts = crate::chat_notify::run_facts(home, run);
151    let clean = |s: &str| -> String {
152        crate::prompt::defuse(&crate::scrub::scrub(s, &crate::scrub::Identity::current()))
153            .chars()
154            .take(12_000)
155            .collect()
156    };
157    let pr = q
158        .merge_target
159        .as_ref()
160        .map(|t| t.pr.as_str())
161        .or(facts.pr.as_deref())
162        .unwrap_or("none");
163    let body = format!(
164        "# {}\n\n{}\n\n{}\n\nTask: {}\nRun: {}\nPR: {}\nState: {}\n",
165        crate::prompt::TASK_MESSAGE_HEADING,
166        clean(&q.summary),
167        clean(&q.detail),
168        task.id,
169        run,
170        clean(pr),
171        task.status.as_str()
172    );
173    let instructions = if let Some(target) = &q.merge_target {
174        format!(
175            "\nMerge decision {} for PR {} at head {}: explain the decision and include this full question ID in your reply to offer the chat buttons. Buttons are optional; when the owner asks to merge, record it with `magi task control decide {} merge` (exactly this head is merged). For non-merge recovery (repair, dismiss, withdraw or replacement), carry out what the owner asks with `magi task control decide {} <option>`. Silence is a hold.\n",
176            q.id, target.pr, target.head, q.id, q.id
177        )
178    } else if awaits_decision(q) {
179        let offered = if q.choices.is_empty() {
180            String::new()
181        } else {
182            format!(
183                " The recorded options are: {}.",
184                q.choices
185                    .iter()
186                    .map(|c| format!("`{c}`"))
187                    .collect::<Vec<_>>()
188                    .join(", ")
189            )
190        };
191        format!(
192            "\nDecision {}: discuss it with the owner as free text.{offered} When the owner decides, record it with `magi task control decide {} <option>`. For a publication `use my text` decision, add `--title <literal replacement title>` to pass the title as data. Do not start a deputy/waiter. Silence is a hold.\n",
193            q.id, q.id
194        )
195    } else {
196        "\nDiscuss this free-text decision with the owner. Apply decisions only through `magi task control`. Do not answer the legacy question or start a deputy/waiter.\n".into()
197    };
198    let legacy_answer = q.resolution().map(|answer| format!(
199        "\nHistorical saved reply (evidence only, never a new owner request): {}. Inspect the operation receipt; do not replay it.\n", clean(&answer)
200    )).unwrap_or_default();
201    let text = format!(
202        "{body}\nThis automatic report is not an owner instruction. Investigate and report; it authorizes neither repository edits nor new tasks.\n{instructions}{legacy_answer}"
203    );
204    let outbox = crate::task_inquiry::Outbox::at(home);
205    outbox.enqueue(crate::task_inquiry::Inquiry {
206        schema: 1,
207        id: q.id.clone(),
208        task: task.id.clone(),
209        run: task.runs.contains(&q.run).then(|| q.run.clone()),
210        repo: task.repo.clone(),
211        source: format!("{}:{}:{}", q.node, q.seat, q.run),
212        occurrence: None,
213        text,
214        display: format!("{body}{legacy_answer}"),
215        key: format!("question:{}", q.id),
216        evidence: Some(crate::notice_semantics::question(home, &task, run, q)),
217        created_at: q.asked_at,
218        delivered_to: None,
219        decision: Some(crate::task_decision::Decision::awaiting(q.summary.clone())),
220        delivery_error: None,
221        archived: false,
222    })?;
223    outbox.deliver(queue, talks, &q.id)
224}
225
226/// Snapshot reader for the finite legacy population. New operational records
227/// follow the ordinary route below; history is processed once and never wakes
228/// a conversation just because an upgrade or scheduler restart occurred.
229#[derive(serde::Serialize, serde::Deserialize)]
230struct Migration {
231    schema: u32,
232    pending: Vec<String>,
233    /// Immutable boundary, retained after individual imports finish.
234    #[serde(default)]
235    sources: Option<std::collections::BTreeSet<String>>,
236    #[serde(default)]
237    errors: std::collections::BTreeMap<String, String>,
238}
239
240/// Whether a saved source belongs to the finite history import. A corrupt
241/// boundary is a hold, never evidence that its replies may be executed.
242pub(crate) fn migration_sources(home: &Path) -> Result<Option<std::collections::BTreeSet<String>>> {
243    let path = home.join("notifications/task-chat-migration-v1/state.json");
244    let bytes = match std::fs::read(path) {
245        Ok(bytes) => bytes,
246        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
247            return Ok(Some(Default::default()));
248        }
249        Err(error) => return Err(error.into()),
250    };
251    let state: Migration = serde_json::from_slice(&bytes)?;
252    anyhow::ensure!(state.schema == 1, "unsupported inquiry migration");
253    Ok(state.sources)
254}
255
256/// A foreground ask without run/task attribution retains legacy ownership.
257/// Release-watch inquiries may have an empty run but still belong to a task.
258pub(crate) fn standalone_inquiry(home: &Path, q: &Question) -> bool {
259    if q.routed_task.is_some() || (q.node == crate::bump::NOTICE_NODE && q.seat == "release-watch")
260    {
261        return false;
262    }
263    if q.legacy_foreground || q.run.is_empty() {
264        return true;
265    }
266    // Older foreground asks have no explicit route marker. Recognize only
267    // positive legacy provenance, never infer it from a missing task alone.
268    if Queue::at(home.join("queue"))
269        .list()
270        .iter()
271        .any(|task| task.id == q.run || task.runs.contains(&q.run))
272    {
273        return false;
274    }
275    let run = crate::run::RunState::load_under(&q.run, home).ok();
276    if run
277        .as_ref()
278        .and_then(|run| run.origin.as_ref())
279        .is_some_and(|origin| origin.task.is_some())
280    {
281        return false;
282    }
283    (q.node == "ask" && q.seat == "operator")
284        || (q.cwd.is_some()
285            && run
286                .as_ref()
287                .and_then(|run| run.origin.as_ref())
288                .is_some_and(|origin| origin.task.is_none()))
289}
290
291pub(crate) fn migrated_source(home: &Path, id: &str) -> bool {
292    // Also repairs the effective scope of older, overbroad journals without
293    // decoding the entire history on each scheduler lap.
294    if Questions::at(home.join("questions"))
295        .read_history(id)
296        .is_ok_and(|q| standalone_inquiry(home, &q))
297    {
298        return false;
299    }
300    migration_sources(home).map_or_else(
301        |error| {
302            tracing::warn!("source {id} stays held: {error:#}");
303            true
304        },
305        |sources| sources.as_ref().is_none_or(|ids| ids.contains(id)),
306    )
307}
308
309/// A live answer update is distinct from importing a saved reply. Persist its
310/// exact generation before Questions exposes it to an effect consumer, even
311/// when the first migration sweep has not run yet. Queuing is not resolution.
312pub(crate) fn accept_fresh_reply(home: &Path, q: &Question) -> Result<()> {
313    if standalone_inquiry(home, q) {
314        return Ok(());
315    }
316    let outbox = crate::task_inquiry::Outbox::at(home);
317    match outbox.get(&q.id) {
318        Ok(record)
319            if record.decision.as_ref().is_some_and(|decision| {
320                decision.status == crate::task_decision::Status::Resolved
321            }) =>
322        {
323            return Ok(());
324        }
325        Ok(_) => {}
326        Err(error)
327            if error
328                .downcast_ref::<std::io::Error>()
329                .is_some_and(|error| error.kind() == std::io::ErrorKind::NotFound) =>
330        {
331            let tasks = Queue::at(home.join("queue")).list();
332            let watches = crate::release_watch::states_for_questions(home, std::slice::from_ref(q));
333            let task_id = task_of_with_watches(q, &tasks, &watches);
334            let Some(task) = tasks.iter().find(|task| Some(&task.id) == task_id.as_ref()) else {
335                return Ok(());
336            };
337            let mut inquiry = history_record(q, Some(task));
338            inquiry.run = task.runs.contains(&q.run).then(|| q.run.clone());
339            inquiry.archived = false;
340            inquiry.display = format!("{}\n\n{}", q.summary, q.detail);
341            inquiry.text = format!(
342                "{}\n\nAn owner response was recorded. Its effect is not yet confirmed; do not replay it.",
343                inquiry.display
344            );
345            inquiry.decision = Some(crate::task_decision::Decision::awaiting(q.summary.clone()));
346            outbox.enqueue(inquiry)?;
347        }
348        Err(error) => return Err(error),
349    }
350    outbox.update_decision(&q.id, |decision| {
351        let accepted =
352            decision.accept(&format!("decision: {}", q.resolution().unwrap_or_default()))?;
353        let changed = decision.source_answer_at != q.answered_at;
354        decision.source_answer_at = q.answered_at;
355        Ok(accepted || changed)
356    })?;
357    Ok(())
358}
359
360/// Import never turns a saved reply into an executable request. Only a fresh
361/// owner answer can authorize consumption of a quarantined source reply.
362pub(crate) fn saved_reply_requires_confirmation(home: &Path, q: &Question) -> bool {
363    migrated_source(home, &q.id) && source_reply_needs_confirmation(home, q)
364}
365
366pub(crate) fn source_reply_needs_confirmation(home: &Path, q: &Question) -> bool {
367    if q.answer.is_none()
368        || (q.accepted_answer_at.is_some() && q.accepted_answer_at == q.answered_at)
369    {
370        return false;
371    }
372    let request = format!("decision: {}", q.resolution().unwrap_or_default());
373    !crate::task_inquiry::Outbox::at(home)
374        .get(&q.id)
375        .is_ok_and(|record| {
376            record.decision.as_ref().is_some_and(|decision| {
377                decision.request.as_deref() == Some(request.as_str())
378                    && decision.source_answer_at.is_some()
379                    && decision.source_answer_at == q.answered_at
380            })
381        })
382}
383
384/// A migration source which still needs operator reconciliation. Reading the
385/// pending list never acknowledges or removes these failures.
386#[derive(serde::Serialize)]
387pub struct MigrationIssue {
388    /// Exact source identity; ownership may be unknowable until it is repaired.
389    pub id: String,
390    /// Why import remains pending. No action or approval has been executed.
391    pub reason: String,
392}
393
394/// Report persistent import failures alongside readable native inquiries.
395/// Even a damaged migration journal must not hide the rest of the pending list.
396pub fn migration_issues(home: &Path) -> Vec<MigrationIssue> {
397    let read = || -> Result<Vec<MigrationIssue>> {
398        let path = home.join("notifications/task-chat-migration-v1/state.json");
399        let bytes = match std::fs::read(path) {
400            Ok(bytes) => bytes,
401            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(vec![]),
402            Err(error) => return Err(error.into()),
403        };
404        let migration: Migration = serde_json::from_slice(&bytes)?;
405        anyhow::ensure!(migration.schema == 1, "unsupported inquiry migration");
406        Ok(migration
407            .errors
408            .into_iter()
409            .map(|(id, reason)| MigrationIssue { id, reason })
410            .collect())
411    };
412    let mut issues = read().unwrap_or_else(|error| {
413        vec![MigrationIssue {
414            id: "migration".into(),
415            reason: format!(
416                "Migration journal needs reconciliation: {error:#}. No approval was inferred."
417            ),
418        }]
419    });
420    if !issues.iter().any(|issue| issue.id == "migration") {
421        match std::fs::read_to_string(
422            home.join("notifications/task-chat-migration-v1/last-error.txt"),
423        ) {
424            Ok(reason) => issues.push(MigrationIssue {
425                id: "migration".into(),
426                reason,
427            }),
428            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
429            Err(error) => issues.push(MigrationIssue {
430                id: "migration".into(),
431                reason: format!("Migration diagnostic is unreadable: {error:#}"),
432            }),
433        }
434    }
435    issues
436}
437
438pub(crate) fn migration_pending(home: &Path) -> Result<std::collections::BTreeSet<String>> {
439    let path = home.join("notifications/task-chat-migration-v1/state.json");
440    let bytes = match std::fs::read(path) {
441        Ok(bytes) => bytes,
442        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Default::default()),
443        Err(error) => return Err(error.into()),
444    };
445    let migration: Migration = serde_json::from_slice(&bytes)?;
446    anyhow::ensure!(migration.schema == 1, "unsupported inquiry migration");
447    Ok(migration.pending.into_iter().collect())
448}
449
450fn migrate_batch(
451    queue: &Queue,
452    talks: &Talks,
453    questions: &Questions,
454    home: &Path,
455    watches: &[crate::release_watch::WatchState],
456) -> Result<()> {
457    let dir = home.join("notifications/task-chat-migration-v1");
458    std::fs::create_dir_all(&dir)?;
459    let lock = std::fs::OpenOptions::new()
460        .create(true)
461        .truncate(false)
462        .write(true)
463        .open(dir.join("migration.lock"))?;
464    if let Err(error) = crate::pr_head::try_lock_file(&lock) {
465        if error.kind() == std::io::ErrorKind::WouldBlock || error.raw_os_error() == Some(33) {
466            return Ok(());
467        }
468        return Err(error.into());
469    }
470    let path = dir.join("state.json");
471    let mut migration: Migration = if path.exists() {
472        serde_json::from_slice(&std::fs::read(&path)?)?
473    } else {
474        Migration {
475            schema: 1,
476            // list() intentionally skips unreadable records for the old UI.
477            // A finite migration boundary must include their filenames too.
478            pending: {
479                let mut ids = std::collections::BTreeSet::new();
480                match std::fs::read_dir(questions.root()) {
481                    Ok(entries) => {
482                        for entry in entries {
483                            let path = entry?.path();
484                            if path.extension().is_some_and(|ext| ext == "json") {
485                                let id = path
486                                    .file_stem()
487                                    .and_then(|name| name.to_str())
488                                    .context("saved inquiry filename is not UTF-8")?;
489                                ids.insert(id.to_owned());
490                            }
491                        }
492                    }
493                    Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
494                    Err(error) => return Err(error.into()),
495                }
496                ids.into_iter().collect()
497            },
498            sources: None,
499            errors: Default::default(),
500        }
501    };
502    let needs_boundary = migration.sources.is_none();
503    if needs_boundary {
504        let mut sources: std::collections::BTreeSet<_> =
505            migration.pending.iter().cloned().collect();
506        match std::fs::read_dir(questions.root()) {
507            Ok(entries) => {
508                for entry in entries {
509                    let path = entry?.path();
510                    if path
511                        .extension()
512                        .is_some_and(|extension| extension == "json")
513                    {
514                        let id = path
515                            .file_stem()
516                            .and_then(|stem| stem.to_str())
517                            .context("saved inquiry filename is not UTF-8")?;
518                        sources.insert(id.to_owned());
519                    }
520                }
521            }
522            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
523            Err(error) => return Err(error.into()),
524        }
525        migration.pending = sources.iter().cloned().collect();
526        migration.sources = Some(sources);
527    }
528    anyhow::ensure!(migration.schema == 1, "unsupported task inquiry migration");
529    let save = |state: &Migration| -> Result<()> {
530        let temp = path.with_extension("tmp");
531        std::fs::write(&temp, serde_json::to_vec(state)?)?;
532        std::fs::rename(temp, &path)?;
533        Ok(())
534    };
535    // Persist the boundary before delivering anything. Receipt loss can repeat
536    // a batch, but the original inquiry/transcript keys make that repeat inert.
537    if !path.exists() || needs_boundary {
538        save(&migration)?;
539    }
540    if migration.pending.is_empty() {
541        return Ok(());
542    }
543    let batch: Vec<_> = migration
544        .pending
545        .drain(..migration.pending.len().min(64))
546        .collect();
547    let tasks = queue.list();
548    for id in batch {
549        let result = (|| -> Result<()> {
550            let q = questions.read_history(&id)?;
551            if standalone_inquiry(home, &q) {
552                if let Some(sources) = &mut migration.sources {
553                    sources.remove(&id);
554                }
555                return Ok(());
556            }
557            if q.node == crate::bump::NOTICE_NODE && q.choices.is_empty() {
558                return Ok(());
559            }
560            let task = task_of_with_watches(&q, &tasks, watches)
561                .and_then(|id| tasks.iter().find(|task| task.id == id));
562            let outbox = crate::task_inquiry::Outbox::at(home);
563            let receipt = match effect_receipt(home, queue, &q, task.map(|task| task.id.as_str())) {
564                Ok(receipt) => receipt,
565                Err(error) => {
566                    if pending_intent(home, &q, task, watches) {
567                        if let Some(task) = task {
568                            if q.routed_task.as_ref() != Some(&task.id) {
569                                questions.update(&q.id, |source| {
570                                    source.routed_task = Some(task.id.clone());
571                                    Ok(())
572                                })?;
573                            }
574                            post(queue, talks, home, &task.id, &q)?;
575                            sync_effect_receipt(home, queue, &q);
576                        } else if !q.run.is_empty() {
577                            let mut record = history_record(&q, None);
578                            record.decision =
579                                Some(crate::task_decision::Decision::awaiting(q.summary.clone()));
580                            record
581                                .decision
582                                .as_mut()
583                                .unwrap()
584                                .fail(&format!("Source receipt needs reconciliation: {error:#}"))?;
585                            record.delivery_error =
586                                Some("Restore the original task ownership before acting, or explicitly settle with task control settle-decision and a reason.".into());
587                            record.archived = false;
588                            outbox.enqueue(record)?;
589                        }
590                    } else {
591                        archive_history(&outbox, &q, task, None)?;
592                    }
593                    return Ok(());
594                }
595            };
596            let pending = receipt.is_none() && pending_intent(home, &q, task, watches);
597            if !pending {
598                archive_history(&outbox, &q, task, receipt.as_deref())?;
599                return Ok(());
600            }
601            if let Some(task) = task {
602                // Reserve task routing before delivery: a deputy/waiter must
603                // never be a second audience for the same imported inquiry.
604                if q.routed_task.as_ref() != Some(&task.id) {
605                    questions.update(&q.id, |source| {
606                        source.routed_task = Some(task.id.clone());
607                        Ok(())
608                    })?;
609                }
610                post(queue, talks, home, &task.id, &q)?;
611                sync_effect_receipt(home, queue, &q);
612            } else {
613                // An ownerless saved inquiry (empty run included) keeps its
614                // unresolved intent in the pending list for manual repair.
615                let mut record = history_record(&q, None);
616                record.archived = false;
617                record.decision = Some(crate::task_decision::Decision::awaiting(q.summary.clone()));
618                record.delivery_error = Some("Owning task is missing or ambiguous. Restore the original task/run association, or ask any chat to use task control settle-decision with this inquiry ID and a reason. Migration executed no operation.".into());
619                outbox.enqueue(record)?;
620                sync_effect_receipt(home, queue, &q);
621            }
622            Ok(())
623        })();
624        if let Err(error) = result {
625            tracing::warn!("legacy inquiry {id} import: {error:#}");
626            migration.errors.insert(
627                id.clone(),
628                format!(
629                    "Saved inquiry needs reconciliation: {error:#}. Import executed no action."
630                ),
631            );
632            migration.pending.push(id);
633        } else {
634            migration.errors.remove(&id);
635        }
636    }
637    save(&migration)
638}
639
640fn pending_intent(
641    home: &Path,
642    q: &Question,
643    task: Option<&Task>,
644    watches: &[crate::release_watch::WatchState],
645) -> bool {
646    if q.status.open() {
647        return true;
648    }
649    if watches
650        .iter()
651        .any(|watch| watch.question.as_deref() == Some(q.id.as_str()))
652    {
653        return true;
654    }
655    let Some(task) = task else {
656        return q.answer.is_none() || awaits_decision(q);
657    };
658    if task.blocked_by.contains(&q.id) {
659        return true;
660    }
661    if task.status == crate::queue::TaskStatus::Done {
662        return false;
663    }
664    if q.run != task.id && task.runs.last() != Some(&q.run) {
665        return false;
666    }
667    if q.node == crate::github_text::ASK_NODE {
668        return crate::run::RunState::load_under(&q.run, home).is_ok_and(|run| {
669            run.github_text
670                .as_ref()
671                .is_some_and(|gate| gate.question.as_ref() == Some(&q.id))
672                && (run.pr_publication_pending || run.merge.as_ref().is_none_or(|out| !out.ok))
673        });
674    }
675    awaits_decision(q) || (q.routed_chat.is_some() && q.answer.is_none())
676}
677
678fn history_record(q: &Question, task: Option<&Task>) -> crate::task_inquiry::Inquiry {
679    let saved_reply = q.answer.as_ref().map(|answer| match answer {
680        crate::ask::Answer::Choice(text) | crate::ask::Answer::Text(text) => text.as_str(),
681    });
682    let display = format!(
683        "{}\n\n{}\n\nSaved status: {}\nSaved reply (history only): {}",
684        q.summary,
685        q.detail,
686        q.status.as_str(),
687        saved_reply.unwrap_or("none")
688    );
689    crate::task_inquiry::Inquiry {
690        schema: 1,
691        id: q.id.clone(),
692        task: task.map(|task| task.id.clone()).unwrap_or_default(),
693        run: (!q.run.is_empty() && !q.run_names_task()).then(|| q.run.clone()),
694        repo: task.map(|task| task.repo.clone()).unwrap_or_default(),
695        source: format!("{}:{}:{}", q.node, q.seat, q.run),
696        occurrence: None,
697        text: display.clone(),
698        display,
699        key: format!("question:{}", q.id),
700        evidence: None,
701        created_at: q.asked_at,
702        delivered_to: None,
703        decision: None,
704        delivery_error: None,
705        archived: true,
706    }
707}
708
709fn archive_history(
710    outbox: &crate::task_inquiry::Outbox,
711    q: &Question,
712    task: Option<&Task>,
713    receipt: Option<&str>,
714) -> Result<()> {
715    let mut record = history_record(q, task);
716    if let Some(receipt) = receipt {
717        let mut decision = crate::task_decision::Decision::awaiting(q.summary.clone());
718        decision.applied(receipt)?;
719        record.decision = Some(decision);
720    }
721    outbox.enqueue(record)?;
722    if let Some(receipt) = receipt {
723        outbox.update_decision(&q.id, |d| d.applied(receipt))?;
724    } else if outbox.get(&q.id)?.decision.is_some() {
725        outbox.suspend_delivery(&q.id, "Passive saved inquiry history; no current consumer requests this effect. No automatic redelivery is scheduled. Explicit owner settlement remains available where no action is queued.")?;
726    }
727    Ok(())
728}
729
730/// Queue once before retiring the ordinary question. Merge records stay open
731/// as the existing land/release consent authority, including their deadlines.
732pub fn sweep(queue: &Queue, talks: &Talks, questions: &Questions, home: &Path) {
733    let tasks = queue.list();
734    let all = questions.list();
735    let watches = crate::release_watch::states_for_questions(home, &all);
736    let migration_error = home.join("notifications/task-chat-migration-v1/last-error.txt");
737    if let Err(error) = migrate_batch(queue, talks, questions, home, &watches) {
738        tracing::warn!("legacy inquiry migration remains pending: {error:#}");
739        if let Err(save) = std::fs::write(
740            &migration_error,
741            format!("Migration remains pending: {error:#}. No approval was inferred."),
742        ) {
743            tracing::warn!("cannot persist migration failure: {save:#}");
744        }
745    } else if let Err(error) = std::fs::remove_file(&migration_error)
746        && error.kind() != std::io::ErrorKind::NotFound
747    {
748        tracing::warn!("cannot clear migration diagnostic: {error:#}");
749    }
750    let deferred = migration_pending(home).unwrap_or_else(|error| {
751        tracing::warn!("legacy delivery boundary is unreadable: {error:#}");
752        all.iter().map(|q| q.id.clone()).collect()
753    });
754    let outbox = crate::task_inquiry::Outbox::at(home);
755    for q in &all {
756        if deferred.contains(&q.id) {
757            continue;
758        }
759        if let Ok(record) = outbox.get(&q.id) {
760            // Execution views quarantine imported replies. Receipt projection
761            // needs their original payload, without making it executable.
762            match questions.read_history(&q.id) {
763                Ok(source) => sync_effect_receipt(home, queue, &source),
764                Err(error) => {
765                    tracing::warn!("decision {} source history: {error:#}", q.id);
766                    let _ = outbox.update_decision(&q.id, |d| {
767                        d.fail(&format!("Source history needs reconciliation: {error:#}"))
768                    });
769                }
770            }
771            // Missing ownership is recoverable, but never guessed or routed
772            // around the compatibility policy while its consumer still exists.
773            if record.task.is_empty()
774                && chat_routable(q)
775                && let Some(task) = task_of_with_watches(q, &tasks, &watches)
776            {
777                if let Err(error) = post(queue, talks, home, &task, q) {
778                    tracing::warn!("decision {} owner recovery: {error:#}", q.id);
779                }
780            }
781        }
782    }
783    for q in all.into_iter().filter(|q| {
784        q.status.open()
785            && chat_routable(q)
786            && !standalone_inquiry(home, q)
787            && !deferred.contains(&q.id)
788    }) {
789        // The pre-migration scan may have projected a not-yet-imported source
790        // as open. Recheck the native result before scheduling delivery: the
791        // batch may just have classified it as passive completed history.
792        if outbox.get(&q.id).is_ok_and(|record| {
793            record.archived
794                || record.decision.is_some_and(|decision| {
795                    decision.status == crate::task_decision::Status::Resolved
796                })
797        }) {
798            continue;
799        }
800        let Some(task_id) = q
801            .routed_task
802            .clone()
803            .or_else(|| task_of_with_watches(&q, &tasks, &watches))
804        else {
805            continue;
806        };
807        // A delivered decision that waits for the owner is left alone: it is
808        // rewritten only while it still lacks its task link (R2-1-1 / R2-2-1:
809        // every poll used to lock and rewrite it).
810        let needs_task = chat_routable(&q) && q.routed_task.as_deref() != Some(task_id.as_str());
811        if q.routed_chat.is_some() && !needs_task {
812            continue;
813        }
814        let result = (|| -> Result<()> {
815            let q = if needs_task {
816                questions
817                    .update(&q.id, |r| {
818                        if chat_routable(r) && r.routed_task.as_deref() != Some(task_id.as_str()) {
819                            r.routed_task = Some(task_id.clone());
820                        }
821                        Ok(())
822                    })?
823                    .0
824            } else {
825                q.clone()
826            };
827            // Already queued approvals must not reopen a chat on every poll.
828            if q.routed_chat.is_some() {
829                return Ok(());
830            }
831            let chat = post(queue, talks, home, &task_id, &q)?;
832            questions.update(&q.id, |r| {
833                r.routed_chat = Some(chat.clone());
834                if awaits_decision(r) {
835                    // Its answer is still read by the machinery behind it; the
836                    // consultation link keeps compatibility consumers and
837                    // conversation context associated with the decision.
838                    r.consult.get_or_insert_with(|| crate::ask::ChatConsult {
839                        talk: chat.clone(),
840                        at: jiff::Timestamp::now(),
841                    });
842                } else if chat_routable(r) && r.merge_target.is_none() {
843                    r.abandon(format!("forwarded to task chat {chat}"));
844                }
845                Ok(())
846            })?;
847            Ok(())
848        })();
849        if let Err(e) = result {
850            tracing::warn!("task decision {} delivery: {e:#}", q.id);
851        }
852    }
853}
854
855/// Project only authoritative durable application evidence. Answered, delivered
856/// and read fields are deliberately not treated as effect receipts.
857pub(crate) fn sync_effect_receipt(home: &Path, queue: &Queue, q: &Question) {
858    if q.answer.is_some()
859        && q.accepted_answer_at.is_some()
860        && q.accepted_answer_at == q.answered_at
861        && let Err(error) = accept_fresh_reply(home, q)
862    {
863        tracing::warn!("decision {} acceptance: {error:#}", q.id);
864        return;
865    }
866    let outbox = crate::task_inquiry::Outbox::at(home);
867    let Ok(record) = outbox.get(&q.id) else {
868        return;
869    };
870    let Some(decision) = record.decision else {
871        return;
872    };
873    if decision.status == crate::task_decision::Status::Resolved {
874        return;
875    }
876    let result = match effect_receipt(home, queue, q, Some(&record.task)) {
877        Ok(Some(receipt)) => outbox.update_decision(&q.id, |d| d.applied(&receipt)),
878        Ok(None) if q.answer.is_some() && decision.request.is_none() => outbox.update_decision(&q.id, |d| d.fail("Saved reply has no confirmed effect receipt. Inspect its outcome; migration did not replay the reply. Discussion without a queued effect can be explicitly settled.")),
879        Ok(None) => Ok(()),
880        Err(error) => outbox.update_decision(&q.id, |d| d.fail(&format!("Source receipt needs reconciliation: {error:#}"))),
881    };
882    if let Err(error) = result {
883        tracing::warn!("decision {} projection: {error:#}", q.id);
884    }
885}
886
887fn effect_receipt(
888    home: &Path,
889    queue: &Queue,
890    q: &Question,
891    task: Option<&str>,
892) -> Result<Option<String>> {
893    if q.resolution().is_none() {
894        return Ok(None);
895    }
896
897    if q.node == crate::land::APPROVAL_NODE
898        && q.resolution().as_deref() == Some(crate::land::REPAIR)
899    {
900        let run = crate::run::RunState::load_under(&q.run, home)?;
901        let Some(repair) = run.merge_repairs.iter().find(|r| r.question == q.id) else {
902            return Ok(None);
903        };
904        anyhow::ensure!(
905            q.merge_target
906                .as_ref()
907                .is_none_or(|target| { target.pr == repair.pr && target.head == repair.head }),
908            "repair receipt targets a different PR or head"
909        );
910        return match repair.phase {
911            crate::run::MergeRepairPhase::Complete => Ok(Some(format!(
912                "run {}: repair and re-review {} completed for {} at {}",
913                q.run, q.id, repair.pr, repair.head
914            ))),
915            crate::run::MergeRepairPhase::Failed => anyhow::bail!(
916                "repair {} failed: {}",
917                q.id,
918                repair
919                    .failure
920                    .as_deref()
921                    .unwrap_or("inspect the run's repair evidence before retrying")
922            ),
923            // A Resume pass is only transport; even a finished fixer still
924            // owes the requested fresh review and gate.
925            _ => Ok(None),
926        };
927    }
928
929    if q.node == crate::land::APPROVAL_NODE
930        && q.resolution().as_deref() == Some(crate::merge_decision::WITHDRAW)
931    {
932        let run = crate::run::RunState::load_under(&q.run, home)?;
933        if let Some(receipt) = &run.merge_decision
934            && receipt.question == q.id
935            && receipt.choice == crate::merge_decision::WITHDRAW
936            && receipt.closed
937            && run.status == crate::run::RunStatus::Superseded
938            && run.pr.as_ref().is_some_and(|pr| {
939                pr.url == receipt.target.pr && pr.state.eq_ignore_ascii_case("closed")
940            })
941            && q.merge_target
942                .as_ref()
943                .is_none_or(|target| target == &receipt.target)
944        {
945            return Ok(Some(format!(
946                "run {}: withdrawal {} confirmed PR closure and retired execution",
947                q.run, q.id
948            )));
949        }
950        // Resume is only this legacy choice's transport. Its execution-start
951        // marker cannot confirm closure or complete a withdrawal decision.
952        return Ok(None);
953    }
954
955    if crate::release_watch::quiet_effect_applied(home, q)? {
956        return Ok(Some(format!(
957            "release watch {}: owner choice applied",
958            q.id
959        )));
960    }
961    if matches!(
962        q.node.as_str(),
963        crate::triage::NODE | crate::triage::DEPS_NODE
964    ) && let Some(id) = task
965        .filter(|id| !id.is_empty())
966        .or_else(|| (!q.run.is_empty()).then_some(q.run.as_str()))
967        && queue.triage_discard_applied(id, &q.id)?
968    {
969        return Ok(Some(format!(
970            "task {id}: triage discard {} committed",
971            q.id
972        )));
973    }
974
975    let task = task
976        .filter(|id| !id.is_empty())
977        .map(|id| queue.get(id))
978        .transpose()?;
979    if q.node == crate::land::APPROVAL_NODE
980        && let Some(choice) = q.resolution()
981        && (choice.eq_ignore_ascii_case(crate::land::HOLD)
982            || crate::merge_decision::selected_agent(&choice).is_some())
983    {
984        // New holds carry a receipt in the same task write as the effect,
985        // independent even of reopening the old run's landing checkpoint.
986        if choice.eq_ignore_ascii_case(crate::land::HOLD)
987            && let Some(task) = &task
988            && task.decision_effects.get(&q.id) == Some(&format!("decision: {choice}"))
989        {
990            return Ok(Some(format!(
991                "task {}: landing hold {} committed",
992                task.id, q.id
993            )));
994        }
995        let run = crate::run::RunState::load_under(&q.run, home)?;
996        let Some(receipt) = run.merge_decision.as_ref().filter(|receipt| {
997            receipt.question == q.id
998                && receipt.choice == choice
999                && q.merge_target
1000                    .as_ref()
1001                    .is_none_or(|target| target == &receipt.target)
1002        }) else {
1003            return Ok(None);
1004        };
1005        if choice.eq_ignore_ascii_case(crate::land::HOLD) {
1006            return Ok(task
1007                .filter(|task| task.action_applied(&q.id))
1008                .map(|task| format!("task {}: landing hold {} committed", task.id, q.id)));
1009        }
1010        // Resume only transports a replacement request to the old driver.
1011        // Neither that pass nor a queued replacement proves dispatch occurred.
1012        if receipt.closed
1013            && run.status == crate::run::RunStatus::Superseded
1014            && run.pr.as_ref().is_some_and(|pr| {
1015                pr.url == receipt.target.pr && pr.state.eq_ignore_ascii_case("closed")
1016            })
1017            && let Some(next) = &receipt.replacement_run
1018            && let Some(task) = &task
1019            && task.runs.contains(next)
1020        {
1021            let replacement = crate::run::RunState::load_under(next, home)?;
1022            if replacement.repo == task.repo
1023                && replacement.replaces.as_ref().is_some_and(|r| {
1024                    r.question == q.id
1025                        && r.run == q.run
1026                        && r.pr == receipt.target.pr
1027                        && Some(r.agent.as_str()) == crate::merge_decision::selected_agent(&choice)
1028                })
1029                && replacement.passes.iter().any(|pass| pass.task_entry)
1030            {
1031                return Ok(Some(format!(
1032                    "run {}: PR closure confirmed; replacement {next} started for {}",
1033                    q.run, q.id
1034                )));
1035            }
1036        }
1037        return Ok(None);
1038    }
1039    if let Some(action) = q.chosen_action().filter(|a| a.maintenance()) {
1040        let path = home.join("choice-actions").join(format!("{}.json", q.id));
1041        let bytes = match std::fs::read(path) {
1042            Ok(bytes) => bytes,
1043            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
1044            Err(error) => return Err(error.into()),
1045        };
1046        let value: serde_json::Value = serde_json::from_slice(&bytes)?;
1047        anyhow::ensure!(
1048            value["action"] == serde_json::to_value(action)?,
1049            "maintenance receipt targets a different action"
1050        );
1051        anyhow::ensure!(
1052            value["status"] == "applied",
1053            "maintenance outcome is not confirmed: {}",
1054            value["status"]
1055        );
1056        return Ok(Some(format!("choice-actions/{}.json: applied", q.id)));
1057    }
1058    if q.node == crate::triage::NODE || q.node == crate::triage::DEPS_NODE {
1059        return Ok(task
1060            .filter(|task| task.triage_applied(&q.id))
1061            .map(|_| format!("task triage {} committed", q.id)));
1062    }
1063    if let Some(task) = &task
1064        && task.action_applied(&q.id)
1065    {
1066        if matches!(
1067            q.chosen_action(),
1068            Some(
1069                crate::ask::ChoiceAction::Done
1070                    | crate::ask::ChoiceAction::Hold
1071                    | crate::ask::ChoiceAction::Requeue
1072            )
1073        ) && task.decision_effects.get(&q.id)
1074            == Some(&format!(
1075                "decision: {}",
1076                q.resolution().expect("answered action")
1077            ))
1078        {
1079            return Ok(Some(format!(
1080                "task {}: exact choice effect {} committed",
1081                task.id, q.id
1082            )));
1083        }
1084        let applied = match q.chosen_action() {
1085            Some(crate::ask::ChoiceAction::Resume { run }) => {
1086                crate::chat_control::resume_started(home, task, &q.id, run)?
1087            }
1088            Some(crate::ask::ChoiceAction::Done) => task.status == crate::queue::TaskStatus::Done,
1089            Some(crate::ask::ChoiceAction::Hold) => {
1090                task.status == crate::queue::TaskStatus::Held
1091                    && task.hold_reason.as_ref() == Some(&q.summary)
1092            }
1093            Some(crate::ask::ChoiceAction::Requeue) => task.fresh_start,
1094            _ => false,
1095        };
1096        if applied {
1097            return Ok(Some(format!(
1098                "task {}: intended effect {} confirmed",
1099                task.id, q.id
1100            )));
1101        }
1102    }
1103    if q.node == crate::github_text::ASK_NODE {
1104        let run = crate::run::RunState::load_under(&q.run, home)?;
1105        if let Some(gate) = &run.github_text
1106            && let Some(next) = &gate.question
1107            && next != &q.id
1108            && crate::ask::Questions::at(home.join("questions"))
1109                .get(next)
1110                .is_ok_and(|successor| {
1111                    successor.run == q.run
1112                        && successor.node == q.node
1113                        && successor.asked_at >= q.asked_at
1114                })
1115        {
1116            return Ok(Some(format!(
1117                "publication inquiry {} explicitly superseded by active source gate {next}; original reply will not be consumed",
1118                q.id
1119            )));
1120        }
1121        if let Some(gate) = &run.github_text
1122            && let Some(receipt) = &gate.publication
1123        {
1124            let expected = match crate::github_text::read_reply(q) {
1125                crate::github_text::Reply::Original => crate::run::GithubTextChoice::Original,
1126                crate::github_text::Reply::Rewrite => crate::run::GithubTextChoice::Rewrite,
1127                crate::github_text::Reply::Title(_) => crate::run::GithubTextChoice::MyTitle,
1128                crate::github_text::Reply::Fallback => crate::run::GithubTextChoice::Fallback,
1129            };
1130            if q.resolution().is_some()
1131                && receipt.inquiry == q.id
1132                && receipt.fingerprint == gate.fingerprint
1133            {
1134                anyhow::ensure!(
1135                    receipt.choice == expected,
1136                    "publication applied a different payload than the saved reply"
1137                );
1138                return Ok(Some(format!(
1139                    "publication {} for {}: {:?} applied",
1140                    receipt.url, q.id, receipt.choice
1141                )));
1142            }
1143        }
1144    }
1145    if q.node == crate::land::APPROVAL_NODE
1146        && q.resolution().as_deref() == Some(crate::merge_decision::DISMISS)
1147    {
1148        // The durable run stop is the dismissal receipt. Done tasks and
1149        // later attempts deliberately retain their existing task outcome.
1150        let run = crate::run::RunState::load_under(&q.run, home)?;
1151        let stopped = run
1152            .merge_decision
1153            .as_ref()
1154            .is_some_and(|d| d.question == q.id && d.choice == crate::merge_decision::DISMISS);
1155        // A still-active latest owner needs its queue transition too. A
1156        // crash after saving the stop but before that write is not completion.
1157        let settled = queue.list().iter().all(|task| {
1158            task.runs.last() != Some(&q.run)
1159                || task.status == crate::queue::TaskStatus::Done
1160                || task.action_applied(&q.id)
1161        });
1162        if stopped && settled {
1163            return Ok(Some(format!(
1164                "run {}: obsolete approval {} dismissed; PR unchanged",
1165                q.run, q.id
1166            )));
1167        }
1168    }
1169    if let Some(target) = &q.merge_target
1170        && q.resolution().as_deref() == Some(crate::land::APPROVE)
1171    {
1172        let run = crate::run::RunState::load_under(&q.run, home)?;
1173        if run.pr_merged_head.as_deref() == Some(target.head.as_str())
1174            && run
1175                .pr
1176                .as_ref()
1177                .is_some_and(|pr| pr.url == target.pr && pr.state.eq_ignore_ascii_case("merged"))
1178        {
1179            return Ok(Some(format!(
1180                "run {}: merged {} at {}",
1181                q.run, target.pr, target.head
1182            )));
1183        }
1184    }
1185    Ok(None)
1186}
1187
1188/// Buttons are offered by a real persona reply after the persisted delivery.
1189/// Generated reports and owner free text can never offer approval themselves.
1190pub fn approval_offered(talk: &talk::Talk, q: &Question) -> bool {
1191    talk.status.open()
1192        && q.status.open()
1193        && q.merge_target.is_some()
1194        && q.routed_chat.as_deref() == Some(talk.id.as_str())
1195        && talk.notified.contains(&format!("question:{}", q.id))
1196        && talk.turns.iter().any(|turn| {
1197            talk::sender(turn, None) == talk::Sender::Persona && turn.body.contains(&q.id)
1198        })
1199}
1200
1201fn task_of_with_watches(
1202    q: &Question,
1203    tasks: &[Task],
1204    watches: &[crate::release_watch::WatchState],
1205) -> Option<String> {
1206    let mut ids = std::collections::BTreeSet::new();
1207    if let Some(id) = task_of(q, tasks) {
1208        ids.insert(id);
1209    }
1210    for reference in crate::consult::question_task_refs(q, watches) {
1211        for task in tasks.iter().filter(|t| match reference {
1212            crate::consult::QuestionTaskRef::Task(id) => t.id == id,
1213            crate::consult::QuestionTaskRef::Run(id) => t.runs.iter().any(|r| r == id),
1214        }) {
1215            ids.insert(task.id.clone());
1216        }
1217    }
1218    if ids.len() == 1 {
1219        ids.pop_first()
1220    } else {
1221        None
1222    }
1223}
1224
1225#[cfg(test)]
1226mod tests {
1227    use super::*;
1228    use crate::ask::{Answer, QuestionStatus};
1229
1230    #[test]
1231    fn routed_merge_accepts_direct_answers_and_checks_optional_button_binding() {
1232        let mut q = Question::new(
1233            "run".into(),
1234            crate::land::APPROVAL_NODE.into(),
1235            "land".into(),
1236            "Merge?".into(),
1237            String::new(),
1238            vec!["merge".into(), "hold".into()],
1239        );
1240        q.routed_task = Some("task".into());
1241        q.routed_chat = Some("chat".into());
1242        q.merge_target = Some(crate::merge_decision::Target {
1243            pr: "https://example.test/pull/1".into(),
1244            head: "head-a".into(),
1245            language: "en".into(),
1246        });
1247        assert!(q.clone().answer(Answer::Choice("merge".into())).is_ok());
1248        assert!(
1249            q.settle_by_deputy("seat", "merge", None).is_err(),
1250            "a routed decision is the task chat's, never a deputy's"
1251        );
1252        assert!(
1253            q.answer_chat_button(Answer::Choice("merge".into()), "other-chat", "head-a")
1254                .is_err()
1255        );
1256        assert!(
1257            q.answer_chat_button(Answer::Choice("merge".into()), "chat", "old-head")
1258                .is_err()
1259        );
1260        assert!(
1261            q.answer_chat_button(Answer::Text("merge".into()), "chat", "head-a")
1262                .is_err()
1263        );
1264        assert_eq!(q.status, QuestionStatus::Open);
1265        q.answer_chat_button(Answer::Choice("merge".into()), "chat", "head-a")
1266            .unwrap();
1267        assert_eq!(q.resolution().as_deref(), Some("merge"));
1268        assert!(
1269            q.answer_chat_button(Answer::Choice("merge".into()), "chat", "head-a")
1270                .is_err()
1271        );
1272    }
1273
1274    #[test]
1275    fn gate_divergence_and_release_questions_route_and_await_a_decision() {
1276        let q = |node: &str, seat: &str, choices: Vec<String>| {
1277            Question::new(
1278                "run".into(),
1279                node.into(),
1280                seat.into(),
1281                "s".into(),
1282                String::new(),
1283                choices,
1284            )
1285        };
1286        let gate = q(
1287            crate::github_text::ASK_NODE,
1288            "posting-gate",
1289            vec!["use fallback".into()],
1290        );
1291        assert!(chat_routable(&gate) && awaits_decision(&gate));
1292        // Triage discard / dependency decisions are applied by the daemon from
1293        // the recorded answer, so they stay open until the chat settles them.
1294        for node in [crate::triage::NODE, crate::triage::DEPS_NODE] {
1295            let triage = q(node, "triage", vec!["hold".into(), "discard".into()]);
1296            assert!(chat_routable(&triage) && awaits_decision(&triage));
1297        }
1298        let mut acted = q("conduct", "conductor", vec!["finish".into(), "hold".into()]);
1299        acted
1300            .actions
1301            .insert("finish".into(), crate::ask::ChoiceAction::Done);
1302        assert!(chat_routable(&acted) && awaits_decision(&acted));
1303        let diverged = q(
1304            crate::reconcile::NODE,
1305            crate::reconcile::SEAT,
1306            vec!["a".into()],
1307        );
1308        assert!(chat_routable(&diverged) && awaits_decision(&diverged));
1309        let release = q(
1310            crate::bump::NOTICE_NODE,
1311            "release-watch",
1312            vec!["hold".into()],
1313        );
1314        assert!(chat_routable(&release) && awaits_decision(&release));
1315        let legacy_release = q(
1316            crate::bump::NOTICE_NODE,
1317            "release-watch",
1318            vec![crate::land::APPROVE.into(), crate::land::HOLD.into()],
1319        );
1320        assert!(chat_routable(&legacy_release));
1321        assert!(awaits_decision(&legacy_release));
1322        // A choice-less bump notice is informational; a targetless approval
1323        // still needs an owner discussion and safe recovery in its chat.
1324        assert!(!chat_routable(&q(crate::bump::NOTICE_NODE, "bump", vec![])));
1325        assert!(chat_routable(&q(
1326            crate::land::APPROVAL_NODE,
1327            "land",
1328            vec!["merge".into()]
1329        )));
1330        let q = |node: &str| q(node, "seat", vec![]);
1331        assert!(chat_routable(&q("conduct")) && !awaits_decision(&q("conduct")));
1332        let mut m = q(crate::bump::NOTICE_NODE);
1333        m.merge_target = Some(crate::merge_decision::Target {
1334            pr: "https://example.test/pull/1".into(),
1335            head: "h".into(),
1336            language: "en".into(),
1337        });
1338        assert!(chat_routable(&m));
1339    }
1340
1341    #[test]
1342    fn unreadable_repository_config_keeps_task_routing_and_pending_delivery() {
1343        let home = tempfile::tempdir().unwrap();
1344        let queue = Queue::at(home.path().join("queue"));
1345        let repo = home.path().join("repo");
1346        std::fs::create_dir(&repo).unwrap();
1347        std::fs::write(repo.join("magi.toml"), "this is = [not toml").unwrap();
1348        let mut task = Task::new("t".into(), "i".into(), repo, crate::queue::Source::Human);
1349        queue.put(&mut task).unwrap();
1350        let questions = Questions::at(home.path().join("questions"));
1351        let mut q = Question::new(
1352            task.id.clone(),
1353            "conduct".into(),
1354            "seat".into(),
1355            "s".into(),
1356            String::new(),
1357            vec![],
1358        );
1359        questions.put(&mut q).unwrap();
1360        assert_eq!(q.routed_task.as_deref(), Some(task.id.as_str()));
1361        assert_eq!(
1362            questions.get(&q.id).unwrap().routed_task.as_deref(),
1363            Some(task.id.as_str())
1364        );
1365        let talks = Talks::at(home.path().join("talks"));
1366        sweep(&queue, &talks, &questions, home.path());
1367        let outbox = crate::task_inquiry::Outbox::at(home.path());
1368        outbox.sweep(&queue, &talks).unwrap();
1369        assert!(
1370            migration_issues(home.path())
1371                .iter()
1372                .any(|issue| issue.id == q.id)
1373        );
1374        let pending = outbox.get(&q.id).unwrap();
1375        assert!(pending.delivered_to.is_none());
1376        assert!(talks.list().is_empty());
1377        assert_eq!(
1378            pending.decision.unwrap().status,
1379            crate::task_decision::Status::AwaitingOwner
1380        );
1381    }
1382
1383    #[test]
1384    fn a_delivered_decision_is_not_rewritten_on_every_sweep() {
1385        let home = tempfile::tempdir().unwrap();
1386        let queue = Queue::at(home.path().join("queue"));
1387        let talks = talk::Talks::at(home.path().join("talks"));
1388        let questions = Questions::at(home.path().join("questions"));
1389        let mut task = Task::new(
1390            "t".into(),
1391            "i".into(),
1392            home.path().to_path_buf(),
1393            crate::queue::Source::Human,
1394        );
1395        queue.put(&mut task).unwrap();
1396        let mut q = Question::new(
1397            task.id.clone(),
1398            "conduct".into(),
1399            "conductor".into(),
1400            "Finish?".into(),
1401            String::new(),
1402            vec!["finish".into(), "hold".into()],
1403        );
1404        q.actions
1405            .insert("finish".into(), crate::ask::ChoiceAction::Done);
1406        q.routed_task = Some(task.id.clone());
1407        q.routed_chat = Some("chat".into());
1408        questions.put(&mut q).unwrap();
1409        assert!(awaits_decision(&q));
1410        let path = questions.path_of(&q.id);
1411        let before = std::fs::read(&path).unwrap();
1412        let written = std::fs::metadata(&path).unwrap().modified().unwrap();
1413        // A rewrite of identical bytes still replaces the file; give it a
1414        // timestamp it could not share with the original write.
1415        std::thread::sleep(std::time::Duration::from_millis(50));
1416        sweep(&queue, &talks, &questions, home.path());
1417        sweep(&queue, &talks, &questions, home.path());
1418        assert_eq!(std::fs::read(&path).unwrap(), before);
1419        assert_eq!(
1420            std::fs::metadata(&path).unwrap().modified().unwrap(),
1421            written
1422        );
1423    }
1424    #[test]
1425    fn repair_receipts_keep_transport_and_failed_repairs_pending() {
1426        use crate::{
1427            ask::ChoiceAction,
1428            run::{MergeRepair, MergeRepairPhase as Phase, RunState},
1429            task_decision::{Decision, Status},
1430            task_inquiry::Outbox,
1431        };
1432        let temp = tempfile::tempdir().unwrap();
1433        let home = temp.path();
1434        let queue = Queue::at(home.join("queue"));
1435        let mut run = RunState::new(
1436            home.into(),
1437            "main".into(),
1438            "base".into(),
1439            "work".into(),
1440            Config::default(),
1441        );
1442        run.reserve_under(home).unwrap();
1443        let mut q = Question::new(
1444            run.id.clone(),
1445            crate::land::APPROVAL_NODE.into(),
1446            "land".into(),
1447            "Repair findings".into(),
1448            String::new(),
1449            vec![crate::land::REPAIR.into()],
1450        );
1451        q.merge_target = Some(crate::merge_decision::Target {
1452            pr: "https://example.test/pull/1".into(),
1453            head: "head".into(),
1454            language: "en".into(),
1455        });
1456        q.actions.insert(
1457            crate::land::REPAIR.into(),
1458            ChoiceAction::Resume {
1459                run: run.id.clone(),
1460            },
1461        );
1462        q.answer(Answer::Choice(crate::land::REPAIR.into()))
1463            .unwrap();
1464        run.next_pass_inquiries = vec![q.id.clone()];
1465        run.begin_pass();
1466        run.save_under(home).unwrap();
1467        let mut task = Task::new(
1468            "work".into(),
1469            "work".into(),
1470            home.into(),
1471            crate::queue::Source::Human,
1472        );
1473        task.runs.push(run.id.clone());
1474        task.mark_action_applied(&q.id);
1475        queue.put(&mut task).unwrap();
1476        let outbox = Outbox::at(home);
1477        let mut record = history_record(&q, Some(&task));
1478        let mut decision = Decision::awaiting(q.summary.clone());
1479        decision
1480            .accept(&format!("decision: {}", crate::land::REPAIR))
1481            .unwrap();
1482        record.decision = Some(decision);
1483        record.archived = false;
1484        outbox.enqueue(record).unwrap();
1485        let check = |expected| {
1486            sync_effect_receipt(home, &Queue::at(home.join("queue")), &q);
1487            let decision = Outbox::at(home).get(&q.id).unwrap().decision.unwrap();
1488            assert_eq!(decision.status, expected);
1489            decision
1490        };
1491        check(Status::Queued); // Resume started; no repair request was consumed yet.
1492        run.merge_repairs.push(MergeRepair {
1493            question: "unrelated".into(),
1494            head: "head".into(),
1495            pr: q.merge_target.as_ref().unwrap().pr.clone(),
1496            reviews: vec![],
1497            gate: vec![],
1498            gate_head: None,
1499            gate_fixes: vec![],
1500            pre_gate: vec![],
1501            phase: Phase::Complete,
1502            failure: None,
1503        });
1504        run.save_under(home).unwrap();
1505        check(Status::Queued);
1506        run.merge_repairs[0].question = q.id.clone();
1507        for phase in [
1508            Phase::Requested,
1509            Phase::Fixing,
1510            Phase::Reviewing,
1511            Phase::Failed,
1512        ] {
1513            run.merge_repairs[0].phase = phase;
1514            run.merge_repairs[0].failure =
1515                (phase == Phase::Failed).then(|| "dirty worktree; inspect before retry".into());
1516            run.save_under(home).unwrap();
1517            let decision = check(if phase == Phase::Failed {
1518                Status::RetryNeeded
1519            } else {
1520                Status::Queued
1521            });
1522            if phase == Phase::Failed {
1523                assert!(decision.error.unwrap().contains("dirty worktree"));
1524                assert!(
1525                    !decision.retry_safe,
1526                    "a repair failure cannot authorize blind replay"
1527                );
1528            }
1529        }
1530        run.merge_repairs[0].phase = Phase::Complete;
1531        run.merge_repairs[0].head = "different-head".into();
1532        run.save_under(home).unwrap();
1533        check(Status::RetryNeeded);
1534        run.merge_repairs[0].head = "head".into();
1535        run.merge_repairs[0].failure = None;
1536        run.save_under(home).unwrap();
1537        check(Status::Resolved);
1538        check(Status::Resolved);
1539    }
1540
1541    #[test]
1542    fn landing_stop_receipts_require_the_intended_effect_after_restart() {
1543        use crate::{
1544            ask::ChoiceAction,
1545            merge_decision::{self as md, Replacement, Target},
1546            queue::{Source, TaskStatus},
1547            run::{PrRecord, RunState, RunStatus},
1548            task_decision::{Decision, Status},
1549            task_inquiry::Outbox,
1550        };
1551        for choice in [crate::land::HOLD, "reimplement:beta"] {
1552            let temp = tempfile::tempdir().unwrap();
1553            let home = temp.path();
1554            let queue = Queue::at(home.join("queue"));
1555            let mut run = RunState::new(
1556                home.into(),
1557                "main".into(),
1558                "base".into(),
1559                "work".into(),
1560                Config::default(),
1561            );
1562            run.reserve_under(home).unwrap();
1563            run.status = RunStatus::Blocked;
1564            run.driver_exited = true;
1565            run.pr = Some(PrRecord {
1566                url: "https://example.test/pull/1".into(),
1567                number: 1,
1568                state: "open".into(),
1569                checks: "green".into(),
1570                round: 1,
1571                rounds: 2,
1572                red_at_merge: vec![],
1573            });
1574            let mut q = Question::new(
1575                run.id.clone(),
1576                crate::land::APPROVAL_NODE.into(),
1577                "land".into(),
1578                "Stop landing".into(),
1579                String::new(),
1580                vec![choice.into()],
1581            );
1582            q.merge_target = Some(Target {
1583                pr: run.pr.as_ref().unwrap().url.clone(),
1584                head: "head".into(),
1585                language: "en".into(),
1586            });
1587            if choice != crate::land::HOLD {
1588                q.actions.insert(
1589                    choice.into(),
1590                    ChoiceAction::Resume {
1591                        run: run.id.clone(),
1592                    },
1593                );
1594            }
1595            q.answer(Answer::Choice(choice.into())).unwrap();
1596            // The old run consumed the Resume transport, but closure may fail.
1597            run.next_pass_inquiries = vec![q.id.clone()];
1598            run.begin_pass();
1599            run.save_under(home).unwrap();
1600            let mut task = Task::new("work".into(), "work".into(), home.into(), Source::Human);
1601            task.runs.push(run.id.clone());
1602            task.hold_manual(Some("landing stopped".into()));
1603            task.mark_action_applied(&q.id);
1604            queue.put(&mut task).unwrap();
1605            let mut record = history_record(&q, Some(&task));
1606            let mut decision = Decision::awaiting(q.summary.clone());
1607            decision.accept(&format!("decision: {choice}")).unwrap();
1608            record.decision = Some(decision);
1609            record.archived = false;
1610            Outbox::at(home).enqueue(record).unwrap();
1611            let check = |expected| {
1612                sync_effect_receipt(home, &Queue::at(home.join("queue")), &q);
1613                assert_eq!(
1614                    Outbox::at(home)
1615                        .get(&q.id)
1616                        .unwrap()
1617                        .decision
1618                        .unwrap()
1619                        .status,
1620                    expected
1621                );
1622            };
1623            check(Status::Queued);
1624            run.merge_decision = Some(md::Decision {
1625                question: q.id.clone(),
1626                target: q.merge_target.clone().unwrap(),
1627                choice: choice.into(),
1628                closed: false,
1629                replacement_run: None,
1630                replacement_pr: None,
1631            });
1632            run.save_under(home).unwrap();
1633            if choice == crate::land::HOLD {
1634                // A checkpoint alone is insufficient until the task hold commits.
1635                task.actions_applied.clear();
1636                task.status = TaskStatus::Running;
1637                queue.put(&mut task).unwrap();
1638                check(Status::Queued);
1639                task.hold_manual(Some("landing stopped".into()));
1640                task.mark_action_applied(&q.id);
1641                queue.put(&mut task).unwrap();
1642                // A later release must not erase the already committed hold.
1643                task.release_operator("chat", None);
1644                queue.put(&mut task).unwrap();
1645                assert!(
1646                    effect_receipt(home, &queue, &q, Some(&task.id))
1647                        .unwrap()
1648                        .is_some()
1649                );
1650                // New receipts also survive reopening/removing the run checkpoint.
1651                task.decision_effects
1652                    .insert(q.id.clone(), format!("decision: {choice}"));
1653                queue.put(&mut task).unwrap();
1654                run.merge_decision = None;
1655                run.save_under(home).unwrap();
1656                check(Status::Resolved);
1657            } else {
1658                check(Status::Queued); // Failed closure, despite the old pass marker.
1659                run.merge_decision.as_mut().unwrap().closed = true;
1660                run.status = RunStatus::Superseded;
1661                run.pr.as_mut().unwrap().state = "closed".into();
1662                run.save_under(home).unwrap();
1663                check(Status::Queued); // Closure and queueing are not replacement execution.
1664                let mut next = RunState::new(
1665                    home.into(),
1666                    "main".into(),
1667                    "base".into(),
1668                    "replacement".into(),
1669                    Config::default(),
1670                );
1671                next.reserve_under(home).unwrap();
1672                next.replaces = Some(Replacement {
1673                    question: q.id.clone(),
1674                    run: run.id.clone(),
1675                    pr: q.merge_target.as_ref().unwrap().pr.clone(),
1676                    agent: "beta".into(),
1677                    context: String::new(),
1678                });
1679                next.save_under(home).unwrap();
1680                run.merge_decision.as_mut().unwrap().replacement_run = Some(next.id.clone());
1681                run.save_under(home).unwrap();
1682                task.start(next.id.clone());
1683                queue.put(&mut task).unwrap();
1684                check(Status::Queued); // Crash before the replacement enters execution.
1685                next.next_pass_task_entry = true;
1686                next.begin_pass();
1687                next.save_under(home).unwrap();
1688                check(Status::Resolved);
1689            }
1690            check(Status::Resolved);
1691        }
1692    }
1693
1694    #[test]
1695    fn quiet_release_receipts_resolve_pending_decisions_after_restart() {
1696        use crate::{
1697            task_decision::{Decision, Status},
1698            task_inquiry::Outbox,
1699        };
1700        for choice in [crate::release_watch::HOLD, crate::release_watch::LEAVE_IT] {
1701            let dir = tempfile::tempdir().unwrap();
1702            let home = dir.path();
1703            let queue = Queue::at(home.join("queue"));
1704            let mut task = Task::new(
1705                "release".into(),
1706                "release".into(),
1707                home.into(),
1708                crate::queue::Source::Human,
1709            );
1710            queue.put(&mut task).unwrap();
1711            let mut q = Question::new(
1712                "run".into(),
1713                crate::bump::NOTICE_NODE.into(),
1714                "release-watch".into(),
1715                "release stalled".into(),
1716                String::new(),
1717                vec![choice.into()],
1718            );
1719            q.answer(Answer::Choice(choice.into())).unwrap();
1720            let mut record = history_record(&q, Some(&task));
1721            let mut decision = Decision::awaiting(q.summary.clone());
1722            decision.accept(&format!("decision: {choice}")).unwrap();
1723            record.decision = Some(decision);
1724            record.archived = false;
1725            Outbox::at(home).enqueue(record).unwrap();
1726            sync_effect_receipt(home, &queue, &q);
1727            assert_eq!(
1728                Outbox::at(home)
1729                    .get(&q.id)
1730                    .unwrap()
1731                    .decision
1732                    .unwrap()
1733                    .status,
1734                Status::Queued
1735            );
1736            let receipts = home.join("release-watch-receipts");
1737            std::fs::create_dir_all(&receipts).unwrap();
1738            let st = crate::release_watch::WatchState {
1739                applied: vec![q.id.clone()],
1740                ..Default::default()
1741            };
1742            std::fs::write(
1743                receipts.join(format!("{}.json", q.id)),
1744                serde_json::to_vec(&st).unwrap(),
1745            )
1746            .unwrap();
1747            for _ in 0..2 {
1748                sync_effect_receipt(home, &Queue::at(home.join("queue")), &q);
1749                assert_eq!(
1750                    Outbox::at(home)
1751                        .get(&q.id)
1752                        .unwrap()
1753                        .decision
1754                        .unwrap()
1755                        .status,
1756                    Status::Resolved
1757                );
1758            }
1759        }
1760    }
1761
1762    #[test]
1763    fn dismiss_receipt_resolves_done_tasks_and_later_attempts_without_task_markers() {
1764        use crate::{
1765            ask::Answer,
1766            queue::{Source, Task, TaskStatus},
1767            run::{LandApproval, PrRecord, RunState, RunStatus},
1768            task_decision::{Decision, Status},
1769            task_inquiry::Outbox,
1770        };
1771        for (later_attempt, incomplete) in [(false, false), (true, false), (false, true)] {
1772            let temp = tempfile::tempdir().unwrap();
1773            let home = temp.path();
1774            let queue = Queue::at(home.join("queue"));
1775            let mut state = RunState::new(
1776                home.into(),
1777                "main".into(),
1778                "base".into(),
1779                "work".into(),
1780                Config::default(),
1781            );
1782            state.reserve_under(home).unwrap();
1783            state.status = RunStatus::Blocked;
1784            state.driver_exited = true;
1785            let mut q = Question::new(
1786                state.id.clone(),
1787                crate::land::APPROVAL_NODE.into(),
1788                "land".into(),
1789                "Obsolete approval".into(),
1790                String::new(),
1791                vec![crate::merge_decision::DISMISS.into()],
1792            );
1793            state.land_approval = Some(LandApproval {
1794                question: q.id.clone(),
1795                head: "head".into(),
1796            });
1797            state.pr = Some(PrRecord {
1798                url: "https://example.test/pull/1".into(),
1799                number: 1,
1800                state: "open".into(),
1801                checks: "green".into(),
1802                round: 1,
1803                rounds: 2,
1804                red_at_merge: vec![],
1805            });
1806            state.save_under(home).unwrap();
1807            let mut task = Task::new("work".into(), "work".into(), home.into(), Source::Human);
1808            task.runs.push(state.id.clone());
1809            task.status = TaskStatus::Done;
1810            if later_attempt {
1811                task.runs.push("later-run".into());
1812                task.status = TaskStatus::Queued;
1813            }
1814            if incomplete {
1815                task.status = TaskStatus::Parked;
1816            }
1817            queue.put(&mut task).unwrap();
1818            q.answer(Answer::Choice(crate::merge_decision::DISMISS.into()))
1819                .unwrap();
1820            let outbox = Outbox::at(home);
1821            let mut record = history_record(&q, Some(&task));
1822            let mut decision = Decision::awaiting(q.summary.clone());
1823            decision.accept("decision: dismiss").unwrap();
1824            record.decision = Some(decision);
1825            record.archived = false;
1826            outbox.enqueue(record).unwrap();
1827            if incomplete {
1828                // Crash window: the run stop was saved, but the latest
1829                // task transition has not yet committed.
1830                state.merge_decision = Some(crate::merge_decision::Decision {
1831                    question: q.id.clone(),
1832                    target: crate::merge_decision::Target {
1833                        pr: state.pr.as_ref().unwrap().url.clone(),
1834                        head: "head".into(),
1835                        language: "en".into(),
1836                    },
1837                    choice: crate::merge_decision::DISMISS.into(),
1838                    closed: false,
1839                    replacement_run: None,
1840                    replacement_pr: None,
1841                });
1842                state.save_under(home).unwrap();
1843                sync_effect_receipt(home, &queue, &q);
1844                assert_eq!(
1845                    outbox.get(&q.id).unwrap().decision.unwrap().status,
1846                    Status::Queued
1847                );
1848            }
1849            crate::merge_decision::dismiss(home, &q).unwrap();
1850            let after = std::fs::read(queue.path_of(&task.id)).unwrap();
1851            assert_eq!(
1852                queue.get(&task.id).unwrap().action_applied(&q.id),
1853                incomplete
1854            );
1855            for _ in 0..2 {
1856                sync_effect_receipt(home, &queue, &q);
1857                assert_eq!(
1858                    Outbox::at(home)
1859                        .get(&q.id)
1860                        .unwrap()
1861                        .decision
1862                        .unwrap()
1863                        .status,
1864                    Status::Resolved
1865                );
1866                assert_eq!(std::fs::read(queue.path_of(&task.id)).unwrap(), after);
1867            }
1868            assert_eq!(
1869                RunState::load_under(&q.run, home)
1870                    .unwrap()
1871                    .pr
1872                    .unwrap()
1873                    .state,
1874                "open"
1875            );
1876        }
1877    }
1878}