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/// Build task-owned discussion and control guidance for current intent.
135pub(crate) fn live_record(home: &Path, task: &Task, q: &Question) -> crate::task_inquiry::Inquiry {
136    let run = if q.run == task.id {
137        task.runs.last().map(String::as_str).unwrap_or("none")
138    } else {
139        &q.run
140    };
141    let facts = crate::chat_notify::run_facts(home, run);
142    let clean = |s: &str| -> String {
143        crate::prompt::defuse(&crate::scrub::scrub(s, &crate::scrub::Identity::current()))
144            .chars()
145            .take(12_000)
146            .collect()
147    };
148    let pr = q
149        .merge_target
150        .as_ref()
151        .map(|t| t.pr.as_str())
152        .or(facts.pr.as_deref())
153        .unwrap_or("none");
154    let body = format!(
155        "# {}\n\n{}\n\n{}\n\nTask: {}\nRun: {}\nPR: {}\nState: {}\n",
156        crate::prompt::TASK_MESSAGE_HEADING,
157        clean(&q.summary),
158        clean(&q.detail),
159        task.id,
160        run,
161        clean(pr),
162        task.status.as_str()
163    );
164    let instructions = if let Some(target) = &q.merge_target {
165        format!(
166            "\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",
167            q.id, target.pr, target.head, q.id, q.id
168        )
169    } else if awaits_decision(q) {
170        let offered = if q.choices.is_empty() {
171            String::new()
172        } else {
173            format!(
174                " The recorded options are: {}.",
175                q.choices
176                    .iter()
177                    .map(|c| format!("`{c}`"))
178                    .collect::<Vec<_>>()
179                    .join(", ")
180            )
181        };
182        format!(
183            "\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",
184            q.id, q.id
185        )
186    } else {
187        "\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()
188    };
189    let legacy_answer = q.resolution().map(|answer| format!(
190        "\nHistorical saved reply (evidence only, never a new owner request): {}. Inspect the operation receipt; do not replay it.\n", clean(&answer)
191    )).unwrap_or_default();
192    let text = format!(
193        "{body}\nThis automatic report is not an owner instruction. Investigate and report; it authorizes neither repository edits nor new tasks.\n{instructions}{legacy_answer}"
194    );
195    crate::task_inquiry::Inquiry {
196        schema: 1,
197        id: q.id.clone(),
198        task: task.id.clone(),
199        run: task.runs.contains(&q.run).then(|| q.run.clone()),
200        repo: task.repo.clone(),
201        source: format!("{}:{}:{}", q.node, q.seat, q.run),
202        occurrence: None,
203        text,
204        display: format!("{body}{legacy_answer}"),
205        key: format!("question:{}", q.id),
206        evidence: Some(crate::notice_semantics::question(home, task, run, q)),
207        created_at: q.asked_at,
208        delivered_to: None,
209        decision: Some(crate::task_decision::Decision::awaiting(q.summary.clone())),
210        delivery_error: None,
211        archived: false,
212    }
213}
214
215/// Reserve the destination under the task lock, then deliver without it.
216/// A stable creation id and persisted link let retries recover interrupted delivery.
217/// Never wait for a talk lock while holding the task write lock.
218pub fn post(
219    queue: &Queue,
220    talks: &Talks,
221    home: &Path,
222    task_id: &str,
223    q: &Question,
224) -> Result<String> {
225    post_in(queue, talks, home, task_id, q, &InquiryOwnership::default())
226}
227
228fn post_in(
229    queue: &Queue,
230    talks: &Talks,
231    home: &Path,
232    task_id: &str,
233    q: &Question,
234    ownership: &InquiryOwnership,
235) -> Result<String> {
236    let task = queue.get(task_id)?;
237    let outbox = crate::task_inquiry::Outbox::at(home);
238    outbox.enqueue(live_record(home, &task, q))?;
239    // Fresh consent can predate task ownership. Once the inquiry has its
240    // owner, bind that exact response before chat creation/delivery can fail.
241    // Saved replies without the live acceptance generation remain history.
242    if q.resolution().is_some()
243        && q.accepted_answer_at.is_some()
244        && q.accepted_answer_at == q.answered_at
245    {
246        accept_fresh_reply(home, q, ownership)?;
247    }
248    outbox.deliver(queue, talks, &q.id)
249}
250
251/// Snapshot reader for the finite legacy population. New operational records
252/// follow the ordinary route below; history is processed once and never wakes
253/// a conversation just because an upgrade or scheduler restart occurred.
254#[derive(serde::Serialize, serde::Deserialize)]
255struct Migration {
256    schema: u32,
257    /// Finite, restartable correction of imports made by the reopening view.
258    #[serde(default)]
259    classification_revision: u32,
260    pending: Vec<String>,
261    /// Immutable boundary, retained after individual imports finish.
262    #[serde(default)]
263    sources: Option<std::collections::BTreeSet<String>>,
264    #[serde(default)]
265    errors: std::collections::BTreeMap<String, String>,
266}
267
268/// Whether a saved source belongs to the finite history import. A corrupt
269/// boundary is a hold, never evidence that its replies may be executed.
270pub(crate) fn migration_sources(home: &Path) -> Result<Option<std::collections::BTreeSet<String>>> {
271    let path = home.join("notifications/task-chat-migration-v1/state.json");
272    let bytes = match std::fs::read(path) {
273        Ok(bytes) => bytes,
274        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
275            return Ok(Some(Default::default()));
276        }
277        Err(error) => return Err(error.into()),
278    };
279    let state: Migration = serde_json::from_slice(&bytes)?;
280    anyhow::ensure!(state.schema == 1, "unsupported inquiry migration");
281    Ok(state.sources)
282}
283
284/// Ownership evidence scoped to one scan, with no process-wide cache.
285#[derive(Default)]
286pub(crate) struct InquiryOwnership {
287    /// Task id / run id -> the distinct tasks naming it, built from one queue
288    /// read.
289    owned: std::cell::OnceCell<std::collections::HashMap<String, Vec<String>>>,
290    origins: std::cell::RefCell<std::collections::HashMap<String, (bool, bool)>>,
291}
292
293impl InquiryOwnership {
294    pub(crate) fn from_tasks(tasks: &[Task]) -> Self {
295        let index = Self::default();
296        let _ = index.owned.set(Self::owned_ids(tasks));
297        index
298    }
299
300    fn owned_ids(tasks: &[Task]) -> std::collections::HashMap<String, Vec<String>> {
301        let mut map: std::collections::HashMap<String, Vec<String>> =
302            std::collections::HashMap::new();
303        for task in tasks {
304            let mut seen = std::collections::HashSet::new();
305            for key in std::iter::once(&task.id).chain(task.runs.iter()) {
306                if seen.insert(key.as_str()) {
307                    map.entry(key.clone()).or_default().push(task.id.clone());
308                }
309            }
310        }
311        map
312    }
313
314    fn index(&self, home: &Path) -> &std::collections::HashMap<String, Vec<String>> {
315        self.owned
316            .get_or_init(|| Self::owned_ids(&Queue::at(home.join("queue")).list()))
317    }
318
319    /// Same decision as [`task_of`], answered from the shared index.
320    pub(crate) fn task_of(&self, home: &Path, q: &Question) -> Option<String> {
321        match self.index(home).get(&q.run)?.as_slice() {
322            [only] => Some(only.clone()),
323            _ => None,
324        }
325    }
326}
327
328/// A foreground ask without run/task attribution retains legacy ownership.
329/// Release-watch inquiries may have an empty run but still belong to a task.
330pub(crate) fn standalone_inquiry(home: &Path, q: &Question) -> bool {
331    standalone_inquiry_in(home, q, &InquiryOwnership::default())
332}
333
334pub(crate) fn standalone_inquiry_in(
335    home: &Path,
336    q: &Question,
337    ownership: &InquiryOwnership,
338) -> bool {
339    if q.routed_task.is_some() || (q.node == crate::bump::NOTICE_NODE && q.seat == "release-watch")
340    {
341        return false;
342    }
343    if q.legacy_foreground || q.run.is_empty() {
344        return true;
345    }
346    // Older foreground asks have no explicit route marker. Recognize only
347    // positive legacy provenance, never infer it from a missing task alone.
348    if ownership.index(home).contains_key(&q.run) {
349        return false;
350    }
351    let (task_origin, foreground_origin) = *ownership
352        .origins
353        .borrow_mut()
354        .entry(q.run.clone())
355        .or_insert_with(|| {
356            let run = crate::run::RunState::load_under(&q.run, home).ok();
357            let origin = run.as_ref().and_then(|run| run.origin.as_ref());
358            (
359                origin.is_some_and(|origin| origin.task.is_some()),
360                origin.is_some_and(|origin| origin.task.is_none()),
361            )
362        });
363    if task_origin {
364        return false;
365    }
366    (q.node == "ask" && q.seat == "operator") || (q.cwd.is_some() && foreground_origin)
367}
368
369pub(crate) fn migrated_source(home: &Path, id: &str) -> bool {
370    migrated_source_in(home, id, &InquiryOwnership::default())
371}
372
373pub(crate) fn migrated_source_in(home: &Path, id: &str, ownership: &InquiryOwnership) -> bool {
374    // Also repairs the effective scope of older, overbroad journals without
375    // decoding the entire history on each scheduler lap.
376    if Questions::at(home.join("questions"))
377        .read_history(id)
378        .is_ok_and(|q| standalone_inquiry_in(home, &q, ownership))
379    {
380        return false;
381    }
382    migration_sources(home).map_or_else(
383        |error| {
384            tracing::warn!("source {id} stays held: {error:#}");
385            true
386        },
387        |sources| sources.as_ref().is_none_or(|ids| ids.contains(id)),
388    )
389}
390
391/// A live answer update is distinct from importing a saved reply. Persist its
392/// exact generation before Questions exposes it to an effect consumer, even
393/// when the first migration sweep has not run yet. Queuing is not resolution.
394pub(crate) fn accept_fresh_reply(
395    home: &Path,
396    q: &Question,
397    ownership: &InquiryOwnership,
398) -> Result<()> {
399    if standalone_inquiry_in(home, q, ownership) {
400        return Ok(());
401    }
402    let outbox = crate::task_inquiry::Outbox::at(home);
403    match outbox.get(&q.id) {
404        Ok(record)
405            if record.decision.as_ref().is_some_and(|decision| {
406                decision.status == crate::task_decision::Status::Resolved
407            }) =>
408        {
409            return Ok(());
410        }
411        Ok(_) => {}
412        Err(error)
413            if error
414                .downcast_ref::<std::io::Error>()
415                .is_some_and(|error| error.kind() == std::io::ErrorKind::NotFound) =>
416        {
417            let tasks = Queue::at(home.join("queue")).list();
418            let watches = crate::release_watch::states_for_questions(home, std::slice::from_ref(q));
419            let task_id = task_of_with_watches(q, &tasks, &watches);
420            let Some(task) = tasks.iter().find(|task| Some(&task.id) == task_id.as_ref()) else {
421                return Ok(());
422            };
423            let mut inquiry = history_record(q, Some(task));
424            inquiry.run = task.runs.contains(&q.run).then(|| q.run.clone());
425            inquiry.archived = false;
426            inquiry.display = format!("{}\n\n{}", q.summary, q.detail);
427            inquiry.text = format!(
428                "{}\n\nAn owner response was recorded. Its effect is not yet confirmed; do not replay it.",
429                inquiry.display
430            );
431            inquiry.decision = Some(crate::task_decision::Decision::awaiting(q.summary.clone()));
432            outbox.enqueue(inquiry)?;
433        }
434        Err(error) => return Err(error),
435    }
436    outbox.update_decision(&q.id, |decision| {
437        let accepted =
438            decision.accept(&format!("decision: {}", q.resolution().unwrap_or_default()))?;
439        let changed = decision.source_answer_at != q.answered_at;
440        decision.source_answer_at = q.answered_at;
441        Ok(accepted || changed)
442    })?;
443    Ok(())
444}
445
446/// Import never turns a saved reply into an executable request. Only a fresh
447/// owner answer can authorize consumption of a quarantined source reply.
448pub(crate) fn saved_reply_requires_confirmation(home: &Path, q: &Question) -> bool {
449    migrated_source(home, &q.id) && source_reply_needs_confirmation(home, q)
450}
451
452pub(crate) fn source_reply_needs_confirmation(home: &Path, q: &Question) -> bool {
453    if q.answer.is_none()
454        || (q.accepted_answer_at.is_some() && q.accepted_answer_at == q.answered_at)
455    {
456        return false;
457    }
458    let request = format!("decision: {}", q.resolution().unwrap_or_default());
459    !crate::task_inquiry::Outbox::at(home)
460        .get(&q.id)
461        .is_ok_and(|record| {
462            record.decision.as_ref().is_some_and(|decision| {
463                decision.request.as_deref() == Some(request.as_str())
464                    && decision.source_answer_at.is_some()
465                    && decision.source_answer_at == q.answered_at
466            })
467        })
468}
469
470/// A migration source which still needs operator reconciliation. Reading the
471/// pending list never acknowledges or removes these failures.
472#[derive(serde::Serialize)]
473pub struct MigrationIssue {
474    /// Exact source identity; ownership may be unknowable until it is repaired.
475    pub id: String,
476    /// Why import remains pending. No action or approval has been executed.
477    pub reason: String,
478}
479
480/// Report persistent import failures alongside readable native inquiries.
481/// Even a damaged migration journal must not hide the rest of the pending list.
482pub fn migration_issues(home: &Path) -> Vec<MigrationIssue> {
483    let read = || -> Result<Vec<MigrationIssue>> {
484        let path = home.join("notifications/task-chat-migration-v1/state.json");
485        let bytes = match std::fs::read(path) {
486            Ok(bytes) => bytes,
487            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(vec![]),
488            Err(error) => return Err(error.into()),
489        };
490        let migration: Migration = serde_json::from_slice(&bytes)?;
491        anyhow::ensure!(migration.schema == 1, "unsupported inquiry migration");
492        Ok(migration
493            .errors
494            .into_iter()
495            .map(|(id, reason)| MigrationIssue { id, reason })
496            .collect())
497    };
498    let mut issues = read().unwrap_or_else(|error| {
499        vec![MigrationIssue {
500            id: "migration".into(),
501            reason: format!(
502                "Migration journal needs reconciliation: {error:#}. No approval was inferred."
503            ),
504        }]
505    });
506    if !issues.iter().any(|issue| issue.id == "migration") {
507        match std::fs::read_to_string(
508            home.join("notifications/task-chat-migration-v1/last-error.txt"),
509        ) {
510            Ok(reason) => issues.push(MigrationIssue {
511                id: "migration".into(),
512                reason,
513            }),
514            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
515            Err(error) => issues.push(MigrationIssue {
516                id: "migration".into(),
517                reason: format!("Migration diagnostic is unreadable: {error:#}"),
518            }),
519        }
520    }
521    issues
522}
523
524pub(crate) fn migration_pending(home: &Path) -> Result<std::collections::BTreeSet<String>> {
525    let path = home.join("notifications/task-chat-migration-v1/state.json");
526    let bytes = match std::fs::read(path) {
527        Ok(bytes) => bytes,
528        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Default::default()),
529        Err(error) => return Err(error.into()),
530    };
531    let migration: Migration = serde_json::from_slice(&bytes)?;
532    anyhow::ensure!(migration.schema == 1, "unsupported inquiry migration");
533    Ok(migration.pending.into_iter().collect())
534}
535
536fn migrate_batch(
537    queue: &Queue,
538    talks: &Talks,
539    questions: &Questions,
540    home: &Path,
541    watches: &[crate::release_watch::WatchState],
542) -> Result<()> {
543    let dir = home.join("notifications/task-chat-migration-v1");
544    std::fs::create_dir_all(&dir)?;
545    let lock = std::fs::OpenOptions::new()
546        .create(true)
547        .truncate(false)
548        .write(true)
549        .open(dir.join("migration.lock"))?;
550    if let Err(error) = crate::pr_head::try_lock_file(&lock) {
551        if error.kind() == std::io::ErrorKind::WouldBlock || error.raw_os_error() == Some(33) {
552            return Ok(());
553        }
554        return Err(error.into());
555    }
556    let path = dir.join("state.json");
557    let mut migration: Migration = if path.exists() {
558        serde_json::from_slice(&std::fs::read(&path)?)?
559    } else {
560        Migration {
561            schema: 1,
562            classification_revision: 0,
563            // list() intentionally skips unreadable records for the old UI.
564            // A finite migration boundary must include their filenames too.
565            pending: {
566                let mut ids = std::collections::BTreeSet::new();
567                match std::fs::read_dir(questions.root()) {
568                    Ok(entries) => {
569                        for entry in entries {
570                            let path = entry?.path();
571                            if path.extension().is_some_and(|ext| ext == "json") {
572                                let id = path
573                                    .file_stem()
574                                    .and_then(|name| name.to_str())
575                                    .context("saved inquiry filename is not UTF-8")?;
576                                ids.insert(id.to_owned());
577                            }
578                        }
579                    }
580                    Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
581                    Err(error) => return Err(error.into()),
582                }
583                ids.into_iter().collect()
584            },
585            sources: None,
586            errors: Default::default(),
587        }
588    };
589    let needs_boundary = migration.sources.is_none();
590    if needs_boundary {
591        let mut sources: std::collections::BTreeSet<_> =
592            migration.pending.iter().cloned().collect();
593        match std::fs::read_dir(questions.root()) {
594            Ok(entries) => {
595                for entry in entries {
596                    let path = entry?.path();
597                    if path
598                        .extension()
599                        .is_some_and(|extension| extension == "json")
600                    {
601                        let id = path
602                            .file_stem()
603                            .and_then(|stem| stem.to_str())
604                            .context("saved inquiry filename is not UTF-8")?;
605                        sources.insert(id.to_owned());
606                    }
607                }
608            }
609            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
610            Err(error) => return Err(error.into()),
611        }
612        migration.pending = sources.iter().cloned().collect();
613        migration.sources = Some(sources);
614    }
615    anyhow::ensure!(migration.schema == 1, "unsupported task inquiry migration");
616    let save = |state: &Migration| -> Result<()> {
617        let temp = path.with_extension("tmp");
618        std::fs::write(&temp, serde_json::to_vec(state)?)?;
619        std::fs::rename(temp, &path)?;
620        Ok(())
621    };
622    let needs_correction = migration.classification_revision < 1;
623    if needs_correction {
624        // Revisit exactly the saved boundary, including already imported
625        // sources. Never discover a new generation during compatibility repair.
626        let mut pending: std::collections::BTreeSet<_> =
627            migration.pending.iter().cloned().collect();
628        pending.extend(migration.sources.iter().flatten().cloned());
629        migration.pending = pending.into_iter().collect();
630        migration.classification_revision = 1;
631    }
632    // Persist the boundary before delivering anything. Receipt loss can repeat
633    // a batch, but the original inquiry/transcript keys make that repeat inert.
634    if !path.exists() || needs_boundary || needs_correction {
635        save(&migration)?;
636    }
637    if migration.pending.is_empty() {
638        return Ok(());
639    }
640    let batch: Vec<_> = migration
641        .pending
642        .drain(..migration.pending.len().min(64))
643        .collect();
644    let tasks = queue.list();
645    let ownership = InquiryOwnership::from_tasks(&tasks);
646    for id in batch {
647        let result = (|| -> Result<()> {
648            let q = questions.read_history(&id)?;
649            if standalone_inquiry_in(home, &q, &ownership) {
650                if let Some(sources) = &mut migration.sources {
651                    sources.remove(&id);
652                }
653                return Ok(());
654            }
655            if q.node == crate::bump::NOTICE_NODE && q.choices.is_empty() {
656                return Ok(());
657            }
658            let task = task_of_with_watches(&q, &tasks, watches)
659                .and_then(|id| tasks.iter().find(|task| task.id == id));
660            let outbox = crate::task_inquiry::Outbox::at(home);
661            let receipt = effect_receipt(home, queue, &q, task.map(|task| task.id.as_str()));
662            let mut record = history_record(&q, task);
663            match receipt {
664                Ok(Some(receipt)) => {
665                    let mut decision = crate::task_decision::Decision::awaiting(q.summary.clone());
666                    decision.applied(&receipt)?;
667                    record.decision = Some(decision);
668                }
669                outcome if pending_intent(home, &q, task, watches) || outcome.is_err() => {
670                    if q.status.open()
671                        && let Some(task) = task
672                    {
673                        record = live_record(home, task, &q);
674                    }
675                    record.archived = false;
676                    let mut decision = crate::task_decision::Decision::awaiting(q.summary.clone());
677                    if let Err(error) = outcome {
678                        decision
679                            .fail(&format!("Source receipt needs reconciliation: {error:#}"))?;
680                    } else if q.answer.is_some() {
681                        decision.fail("Saved reply has no confirmed effect receipt. Use reconcile-decision to check durable evidence, or settle-decision with an explicit reason. Import authorized no operation.")?;
682                    }
683                    record.decision = Some(decision);
684                    record.text.push_str("\n\nImported history authorizes no operation. Saved replies require evidence reconciliation or explicit owner settlement; never replay them.");
685                    if task.is_none() {
686                        record.delivery_error = Some("Owning task is missing or ambiguous. Restore the original ownership, or use task control settle-decision with this inquiry ID and a reason. Import executed no operation.".into());
687                    }
688                }
689                _ => {}
690            }
691            let current = questions.read_history(&id)?;
692            anyhow::ensure!(
693                (current.status, &current.answer, current.answered_at)
694                    == (q.status, &q.answer, q.answered_at),
695                "source changed while classifying saved history; retry with its current generation"
696            );
697            outbox.reclassify_history(record)?;
698            sync_effect_receipt_in(home, queue, &q, &ownership);
699            let imported = outbox.get(&q.id)?;
700            if imported.archived
701                || imported
702                    .decision
703                    .as_ref()
704                    .is_some_and(|d| d.status == crate::task_decision::Status::Resolved)
705            {
706                return Ok(());
707            }
708            // Only genuinely unanswered intent retains legacy task routing.
709            // Saved answers and their source JSON remain immutable history.
710            if q.status.open()
711                && let Some(task) = task
712            {
713                if q.routed_task.as_ref() != Some(&task.id) {
714                    questions.update_in(&q.id, &ownership, |source| {
715                        source.routed_task = Some(task.id.clone());
716                        Ok(())
717                    })?;
718                }
719                post_in(queue, talks, home, &task.id, &q, &ownership)?;
720            } else if task.is_some() {
721                // Native discussion of unknown effects is supported without
722                // reopening or rerouting the immutable answered source.
723                outbox.deliver(queue, talks, &q.id)?;
724            }
725            Ok(())
726        })();
727        if let Err(error) = result {
728            tracing::warn!("legacy inquiry {id} import: {error:#}");
729            migration.errors.insert(
730                id.clone(),
731                format!(
732                    "Saved inquiry needs reconciliation: {error:#}. Import executed no action."
733                ),
734            );
735            migration.pending.push(id);
736        } else {
737            migration.errors.remove(&id);
738        }
739    }
740    save(&migration)
741}
742
743fn pending_intent(
744    home: &Path,
745    q: &Question,
746    task: Option<&Task>,
747    watches: &[crate::release_watch::WatchState],
748) -> bool {
749    if q.status.open() || (q.answer.is_some() && awaits_decision(q)) {
750        return true;
751    }
752    if watches
753        .iter()
754        .any(|watch| watch.question.as_deref() == Some(q.id.as_str()))
755    {
756        return true;
757    }
758    let Some(task) = task else {
759        return q.answer.is_none() || awaits_decision(q);
760    };
761    if task.blocked_by.contains(&q.id) {
762        return true;
763    }
764    if task.status == crate::queue::TaskStatus::Done {
765        return false;
766    }
767    if q.run != task.id && task.runs.last() != Some(&q.run) {
768        return false;
769    }
770    if q.node == crate::github_text::ASK_NODE {
771        return crate::run::RunState::load_under(&q.run, home).is_ok_and(|run| {
772            run.github_text
773                .as_ref()
774                .is_some_and(|gate| gate.question.as_ref() == Some(&q.id))
775                && (run.pr_publication_pending || run.merge.as_ref().is_none_or(|out| !out.ok))
776        });
777    }
778    awaits_decision(q) || (q.routed_chat.is_some() && q.answer.is_none())
779}
780
781fn history_record(q: &Question, task: Option<&Task>) -> crate::task_inquiry::Inquiry {
782    let saved_reply = q.answer.as_ref().map(|answer| match answer {
783        crate::ask::Answer::Choice(text) | crate::ask::Answer::Text(text) => text.as_str(),
784    });
785    let display = format!(
786        "{}\n\n{}\n\nSaved status: {}\nSaved reply (history only): {}",
787        q.summary,
788        q.detail,
789        q.status.as_str(),
790        saved_reply.unwrap_or("none")
791    );
792    crate::task_inquiry::Inquiry {
793        schema: 1,
794        id: q.id.clone(),
795        task: task.map(|task| task.id.clone()).unwrap_or_default(),
796        run: (!q.run.is_empty() && !q.run_names_task()).then(|| q.run.clone()),
797        repo: task.map(|task| task.repo.clone()).unwrap_or_default(),
798        source: format!("{}:{}:{}", q.node, q.seat, q.run),
799        occurrence: None,
800        text: display.clone(),
801        display,
802        key: format!("question:{}", q.id),
803        evidence: None,
804        created_at: q.asked_at,
805        delivered_to: None,
806        decision: None,
807        delivery_error: None,
808        archived: true,
809    }
810}
811
812/// Queue once before retiring the ordinary question. Merge records stay open
813/// as the existing land/release consent authority, including their deadlines.
814pub fn sweep(queue: &Queue, talks: &Talks, questions: &Questions, home: &Path) {
815    let tasks = queue.list();
816    let all = questions.list();
817    let watches = crate::release_watch::states_for_questions(home, &all);
818    let migration_error = home.join("notifications/task-chat-migration-v1/last-error.txt");
819    if let Err(error) = migrate_batch(queue, talks, questions, home, &watches) {
820        tracing::warn!("legacy inquiry migration remains pending: {error:#}");
821        if let Err(save) = std::fs::write(
822            &migration_error,
823            format!("Migration remains pending: {error:#}. No approval was inferred."),
824        ) {
825            tracing::warn!("cannot persist migration failure: {save:#}");
826        }
827    } else if let Err(error) = std::fs::remove_file(&migration_error)
828        && error.kind() != std::io::ErrorKind::NotFound
829    {
830        tracing::warn!("cannot clear migration diagnostic: {error:#}");
831    }
832    let deferred = migration_pending(home).unwrap_or_else(|error| {
833        tracing::warn!("legacy delivery boundary is unreadable: {error:#}");
834        all.iter().map(|q| q.id.clone()).collect()
835    });
836    let outbox = crate::task_inquiry::Outbox::at(home);
837    let ownership = InquiryOwnership::from_tasks(&tasks);
838    for q in &all {
839        if deferred.contains(&q.id) {
840            continue;
841        }
842        if let Ok(record) = outbox.get(&q.id) {
843            // Execution views quarantine imported replies. Receipt projection
844            // needs their original payload, without making it executable.
845            match questions.read_history(&q.id) {
846                Ok(source) => sync_effect_receipt_in(home, queue, &source, &ownership),
847                Err(error) => {
848                    tracing::warn!("decision {} source history: {error:#}", q.id);
849                    let _ = outbox.update_decision(&q.id, |d| {
850                        d.fail(&format!("Source history needs reconciliation: {error:#}"))
851                    });
852                }
853            }
854            // Missing ownership is recoverable, but never guessed or routed
855            // around the compatibility policy while its consumer still exists.
856            if record.task.is_empty()
857                && chat_routable(q)
858                && let Some(task) = task_of_with_watches(q, &tasks, &watches)
859            {
860                if let Err(error) = post_in(queue, talks, home, &task, q, &ownership) {
861                    tracing::warn!("decision {} owner recovery: {error:#}", q.id);
862                }
863            }
864        }
865    }
866    for q in all.into_iter().filter(|q| {
867        q.status.open()
868            && chat_routable(q)
869            && !standalone_inquiry_in(home, q, &ownership)
870            && !deferred.contains(&q.id)
871    }) {
872        // The pre-migration scan may have projected a not-yet-imported source
873        // as open. Recheck the native result before scheduling delivery: the
874        // batch may just have classified it as passive completed history.
875        if outbox.get(&q.id).is_ok_and(|record| {
876            record.archived
877                || record.decision.is_some_and(|decision| {
878                    decision.status == crate::task_decision::Status::Resolved
879                })
880        }) {
881            continue;
882        }
883        let Some(task_id) = q
884            .routed_task
885            .clone()
886            .or_else(|| task_of_with_watches(&q, &tasks, &watches))
887        else {
888            continue;
889        };
890        // A delivered decision that waits for the owner is left alone: it is
891        // rewritten only while it still lacks its task link (R2-1-1 / R2-2-1:
892        // every poll used to lock and rewrite it).
893        let needs_task = chat_routable(&q) && q.routed_task.as_deref() != Some(task_id.as_str());
894        if q.routed_chat.is_some() && !needs_task {
895            continue;
896        }
897        let result = (|| -> Result<()> {
898            let q = if needs_task {
899                questions
900                    .update(&q.id, |r| {
901                        if chat_routable(r) && r.routed_task.as_deref() != Some(task_id.as_str()) {
902                            r.routed_task = Some(task_id.clone());
903                        }
904                        Ok(())
905                    })?
906                    .0
907            } else {
908                q.clone()
909            };
910            // Already queued approvals must not reopen a chat on every poll.
911            if q.routed_chat.is_some() {
912                return Ok(());
913            }
914            let chat = post_in(queue, talks, home, &task_id, &q, &ownership)?;
915            questions.update_in(&q.id, &ownership, |r| {
916                r.routed_chat = Some(chat.clone());
917                if awaits_decision(r) {
918                    // Its answer is still read by the machinery behind it; the
919                    // consultation link keeps compatibility consumers and
920                    // conversation context associated with the decision.
921                    r.consult.get_or_insert_with(|| crate::ask::ChatConsult {
922                        talk: chat.clone(),
923                        at: jiff::Timestamp::now(),
924                    });
925                } else if chat_routable(r) && r.merge_target.is_none() {
926                    r.abandon(format!("forwarded to task chat {chat}"));
927                }
928                Ok(())
929            })?;
930            Ok(())
931        })();
932        if let Err(e) = result {
933            tracing::warn!("task decision {} delivery: {e:#}", q.id);
934        }
935    }
936}
937
938/// Project only authoritative durable application evidence. Answered, delivered
939/// and read fields are deliberately not treated as effect receipts.
940pub(crate) fn sync_effect_receipt(home: &Path, queue: &Queue, q: &Question) {
941    sync_effect_receipt_in(home, queue, q, &InquiryOwnership::default())
942}
943
944fn sync_effect_receipt_in(home: &Path, queue: &Queue, q: &Question, ownership: &InquiryOwnership) {
945    if q.answer.is_some()
946        && q.accepted_answer_at.is_some()
947        && q.accepted_answer_at == q.answered_at
948        && let Err(error) = accept_fresh_reply(home, q, ownership)
949    {
950        tracing::warn!("decision {} acceptance: {error:#}", q.id);
951        return;
952    }
953    let outbox = crate::task_inquiry::Outbox::at(home);
954    let Ok(record) = outbox.get(&q.id) else {
955        return;
956    };
957    let Some(decision) = record.decision else {
958        return;
959    };
960    if decision.status == crate::task_decision::Status::Resolved {
961        return;
962    }
963    let result = match effect_receipt(home, queue, q, Some(&record.task)) {
964        Ok(Some(receipt)) => outbox.update_decision(&q.id, |d| d.applied(&receipt)),
965        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.")),
966        Ok(None) => Ok(()),
967        Err(error) => outbox.update_decision(&q.id, |d| d.fail(&format!("Source receipt needs reconciliation: {error:#}"))),
968    };
969    if let Err(error) = result {
970        tracing::warn!("decision {} projection: {error:#}", q.id);
971    }
972}
973
974pub(crate) fn effect_receipt(
975    home: &Path,
976    queue: &Queue,
977    q: &Question,
978    task: Option<&str>,
979) -> Result<Option<String>> {
980    if let Some(task) = task.and_then(|id| queue.get(id).ok())
981        && crate::repair_budget::reconcile::superseded_question(&task, q)
982    {
983        return Ok(Some(format!(
984            "task {}: unanswered dependency question {} superseded by explicit repair receipt reconciliation; no generic resume applied",
985            task.id, q.id
986        )));
987    }
988    if q.resolution().is_none() {
989        return Ok(None);
990    }
991
992    if q.node == crate::land::APPROVAL_NODE
993        && q.resolution().as_deref() == Some(crate::land::REPAIR)
994    {
995        let run = crate::run::RunState::load_under(&q.run, home)?;
996        let Some(repair) = run.merge_repairs.iter().find(|r| r.question == q.id) else {
997            return Ok(None);
998        };
999        anyhow::ensure!(
1000            q.merge_target
1001                .as_ref()
1002                .is_none_or(|target| { target.pr == repair.pr && target.head == repair.head }),
1003            "repair receipt targets a different PR or head"
1004        );
1005        return match repair.phase {
1006            crate::run::MergeRepairPhase::Complete => Ok(Some(format!(
1007                "run {}: repair and re-review {} completed for {} at {}",
1008                q.run, q.id, repair.pr, repair.head
1009            ))),
1010            crate::run::MergeRepairPhase::Failed => anyhow::bail!(
1011                "repair {} failed: {}",
1012                q.id,
1013                repair
1014                    .failure
1015                    .as_deref()
1016                    .unwrap_or("inspect the run's repair evidence before retrying")
1017            ),
1018            // A Resume pass is only transport; even a finished fixer still
1019            // owes the requested fresh review and gate.
1020            _ => Ok(None),
1021        };
1022    }
1023
1024    if q.node == crate::land::APPROVAL_NODE
1025        && q.resolution().as_deref() == Some(crate::merge_decision::WITHDRAW)
1026    {
1027        let run = crate::run::RunState::load_under(&q.run, home)?;
1028        if let Some(receipt) = &run.merge_decision
1029            && receipt.question == q.id
1030            && receipt.choice == crate::merge_decision::WITHDRAW
1031            && receipt.closed
1032            && run.status == crate::run::RunStatus::Superseded
1033            && run.pr.as_ref().is_some_and(|pr| {
1034                pr.url == receipt.target.pr && pr.state.eq_ignore_ascii_case("closed")
1035            })
1036            && q.merge_target
1037                .as_ref()
1038                .is_none_or(|target| target == &receipt.target)
1039        {
1040            return Ok(Some(format!(
1041                "run {}: withdrawal {} confirmed PR closure and retired execution",
1042                q.run, q.id
1043            )));
1044        }
1045        // Resume is only this legacy choice's transport. Its execution-start
1046        // marker cannot confirm closure or complete a withdrawal decision.
1047        return Ok(None);
1048    }
1049
1050    if crate::release_watch::quiet_effect_applied(home, q)? {
1051        return Ok(Some(format!(
1052            "release watch {}: owner choice applied",
1053            q.id
1054        )));
1055    }
1056    if matches!(
1057        q.node.as_str(),
1058        crate::triage::NODE | crate::triage::DEPS_NODE
1059    ) && let Some(id) = task
1060        .filter(|id| !id.is_empty())
1061        .or_else(|| (!q.run.is_empty()).then_some(q.run.as_str()))
1062        && queue.triage_discard_applied(id, &q.id)?
1063    {
1064        return Ok(Some(format!(
1065            "task {id}: triage discard {} committed",
1066            q.id
1067        )));
1068    }
1069
1070    let task = task
1071        .filter(|id| !id.is_empty())
1072        .map(|id| queue.get(id))
1073        .transpose()?;
1074    if q.node == crate::land::APPROVAL_NODE
1075        && let Some(choice) = q.resolution()
1076        && (choice.eq_ignore_ascii_case(crate::land::HOLD)
1077            || crate::merge_decision::selected_agent(&choice).is_some())
1078    {
1079        // New holds carry a receipt in the same task write as the effect,
1080        // independent even of reopening the old run's landing checkpoint.
1081        if choice.eq_ignore_ascii_case(crate::land::HOLD)
1082            && let Some(task) = &task
1083            && task.decision_effects.get(&q.id) == Some(&format!("decision: {choice}"))
1084        {
1085            return Ok(Some(format!(
1086                "task {}: landing hold {} committed",
1087                task.id, q.id
1088            )));
1089        }
1090        let run = crate::run::RunState::load_under(&q.run, home)?;
1091        let Some(receipt) = run.merge_decision.as_ref().filter(|receipt| {
1092            receipt.question == q.id
1093                && receipt.choice == choice
1094                && q.merge_target
1095                    .as_ref()
1096                    .is_none_or(|target| target == &receipt.target)
1097        }) else {
1098            return Ok(None);
1099        };
1100        if choice.eq_ignore_ascii_case(crate::land::HOLD) {
1101            return Ok(task
1102                .filter(|task| task.action_applied(&q.id))
1103                .map(|task| format!("task {}: landing hold {} committed", task.id, q.id)));
1104        }
1105        // Resume only transports a replacement request to the old driver.
1106        // Neither that pass nor a queued replacement proves dispatch occurred.
1107        if receipt.closed
1108            && run.status == crate::run::RunStatus::Superseded
1109            && run.pr.as_ref().is_some_and(|pr| {
1110                pr.url == receipt.target.pr && pr.state.eq_ignore_ascii_case("closed")
1111            })
1112            && let Some(next) = &receipt.replacement_run
1113            && let Some(task) = &task
1114            && task.runs.contains(next)
1115        {
1116            let replacement = crate::run::RunState::load_under(next, home)?;
1117            if replacement.repo == task.repo
1118                && replacement.replaces.as_ref().is_some_and(|r| {
1119                    r.question == q.id
1120                        && r.run == q.run
1121                        && r.pr == receipt.target.pr
1122                        && Some(r.agent.as_str()) == crate::merge_decision::selected_agent(&choice)
1123                })
1124                && replacement.passes.iter().any(|pass| pass.task_entry)
1125            {
1126                return Ok(Some(format!(
1127                    "run {}: PR closure confirmed; replacement {next} started for {}",
1128                    q.run, q.id
1129                )));
1130            }
1131        }
1132        return Ok(None);
1133    }
1134    if matches!(
1135        q.chosen_action(),
1136        Some(crate::ask::ChoiceAction::RecoverBase { .. })
1137    ) {
1138        return crate::base_recovery_control::effect_receipt(
1139            home,
1140            task.as_ref()
1141                .context("base recovery decision has no owning task")?,
1142            q,
1143        );
1144    }
1145    if let Some(action) = q.chosen_action().filter(|a| a.maintenance()) {
1146        let path = home.join("choice-actions").join(format!("{}.json", q.id));
1147        let bytes = match std::fs::read(path) {
1148            Ok(bytes) => bytes,
1149            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
1150            Err(error) => return Err(error.into()),
1151        };
1152        let value: serde_json::Value = serde_json::from_slice(&bytes)?;
1153        anyhow::ensure!(
1154            value["action"] == serde_json::to_value(action)?,
1155            "maintenance receipt targets a different action"
1156        );
1157        anyhow::ensure!(
1158            value["status"] == "applied",
1159            "maintenance outcome is not confirmed: {}",
1160            value["status"]
1161        );
1162        return Ok(Some(format!("choice-actions/{}.json: applied", q.id)));
1163    }
1164    if q.node == crate::triage::NODE || q.node == crate::triage::DEPS_NODE {
1165        if let Some(task) = &task
1166            && let Some(evidence) = task.decision_effects.get(&q.id)
1167        {
1168            if evidence.starts_with("repair-receipt-blocked:") {
1169                anyhow::ensure!(
1170                    evidence == &crate::repair_budget::reconcile::blocked_resume(q)?,
1171                    "blocked resume source changed"
1172                );
1173                return Ok(Some(format!(
1174                    "task {}: generic resume {} consumed without release; retained repair receipt requires explicit reconcile-repair-grant",
1175                    task.id, q.id
1176                )));
1177            }
1178            let (source, _, _, application): (
1179                String,
1180                Option<jiff::Timestamp>,
1181                String,
1182                crate::queue::Resumption,
1183            ) = serde_json::from_str(evidence)
1184                .context("triage application receipt is unreadable")?;
1185            anyhow::ensure!(
1186                source == crate::repair_budget::reconcile::source(q)?
1187                    && task
1188                        .resumption
1189                        .iter()
1190                        .chain(&task.resumption_history)
1191                        .any(|r| crate::repair_budget::reconcile::application_identity(r)
1192                            == application),
1193                "triage source or application evidence changed"
1194            );
1195        }
1196        return Ok(task.filter(|task| task.triage_applied(&q.id)).map(|_| {
1197            format!(
1198                "task triage {} settled by durable application/supersession evidence",
1199                q.id
1200            )
1201        }));
1202    }
1203    if let Some(task) = &task
1204        && task.action_applied(&q.id)
1205    {
1206        if matches!(
1207            q.chosen_action(),
1208            Some(
1209                crate::ask::ChoiceAction::Done
1210                    | crate::ask::ChoiceAction::Hold
1211                    | crate::ask::ChoiceAction::Requeue
1212            )
1213        ) && task.decision_effects.get(&q.id)
1214            == Some(&format!(
1215                "decision: {}",
1216                q.resolution().expect("answered action")
1217            ))
1218        {
1219            return Ok(Some(format!(
1220                "task {}: exact choice effect {} committed",
1221                task.id, q.id
1222            )));
1223        }
1224        let applied = match q.chosen_action() {
1225            Some(crate::ask::ChoiceAction::Resume { run }) => {
1226                crate::chat_control::resume_started(home, task, &q.id, run)?
1227            }
1228            Some(crate::ask::ChoiceAction::Done) => task.status == crate::queue::TaskStatus::Done,
1229            Some(crate::ask::ChoiceAction::Hold) => {
1230                task.status == crate::queue::TaskStatus::Held
1231                    && task.hold_reason.as_ref() == Some(&q.summary)
1232            }
1233            Some(crate::ask::ChoiceAction::Requeue) => task.fresh_start,
1234            _ => false,
1235        };
1236        if applied {
1237            return Ok(Some(format!(
1238                "task {}: intended effect {} confirmed",
1239                task.id, q.id
1240            )));
1241        }
1242    }
1243    if q.node == crate::github_text::ASK_NODE {
1244        let run = crate::run::RunState::load_under(&q.run, home)?;
1245        if let Some(gate) = &run.github_text
1246            && let Some(next) = &gate.question
1247            && next != &q.id
1248            && crate::ask::Questions::at(home.join("questions"))
1249                .get(next)
1250                .is_ok_and(|successor| {
1251                    successor.run == q.run
1252                        && successor.node == q.node
1253                        && successor.asked_at >= q.asked_at
1254                })
1255        {
1256            return Ok(Some(format!(
1257                "publication inquiry {} explicitly superseded by active source gate {next}; original reply will not be consumed",
1258                q.id
1259            )));
1260        }
1261        if let Some(gate) = &run.github_text
1262            && let Some(receipt) = &gate.publication
1263        {
1264            let expected = match crate::github_text::read_reply(q) {
1265                crate::github_text::Reply::Original => crate::run::GithubTextChoice::Original,
1266                crate::github_text::Reply::Rewrite => crate::run::GithubTextChoice::Rewrite,
1267                crate::github_text::Reply::Title(_) => crate::run::GithubTextChoice::MyTitle,
1268                crate::github_text::Reply::Fallback => crate::run::GithubTextChoice::Fallback,
1269            };
1270            if q.resolution().is_some()
1271                && receipt.inquiry == q.id
1272                && receipt.fingerprint == gate.fingerprint
1273            {
1274                anyhow::ensure!(
1275                    receipt.choice == expected,
1276                    "publication applied a different payload than the saved reply"
1277                );
1278                return Ok(Some(format!(
1279                    "publication {} for {}: {:?} applied",
1280                    receipt.url, q.id, receipt.choice
1281                )));
1282            }
1283        }
1284    }
1285    if q.node == crate::land::APPROVAL_NODE
1286        && q.resolution().as_deref() == Some(crate::merge_decision::DISMISS)
1287    {
1288        // The durable run stop is the dismissal receipt. Done tasks and
1289        // later attempts deliberately retain their existing task outcome.
1290        let run = crate::run::RunState::load_under(&q.run, home)?;
1291        let stopped = run
1292            .merge_decision
1293            .as_ref()
1294            .is_some_and(|d| d.question == q.id && d.choice == crate::merge_decision::DISMISS);
1295        // A still-active latest owner needs its queue transition too. A
1296        // crash after saving the stop but before that write is not completion.
1297        let settled = queue.list().iter().all(|task| {
1298            task.runs.last() != Some(&q.run)
1299                || task.status == crate::queue::TaskStatus::Done
1300                || task.action_applied(&q.id)
1301        });
1302        if stopped && settled {
1303            return Ok(Some(format!(
1304                "run {}: obsolete approval {} dismissed; PR unchanged",
1305                q.run, q.id
1306            )));
1307        }
1308    }
1309    if q.node == crate::land::APPROVAL_NODE
1310        && let Some(target) = &q.merge_target
1311        && q.resolution().as_deref() == Some(crate::land::APPROVE)
1312    {
1313        let run = crate::run::RunState::load_under(&q.run, home)?;
1314        if run.pr_merged_head.as_deref() == Some(target.head.as_str())
1315            && run
1316                .pr
1317                .as_ref()
1318                .is_some_and(|pr| pr.url == target.pr && pr.state.eq_ignore_ascii_case("merged"))
1319        {
1320            return Ok(Some(format!(
1321                "run {}: merged {} at {}",
1322                q.run, target.pr, target.head
1323            )));
1324        }
1325    }
1326    Ok(None)
1327}
1328
1329/// Buttons are offered by a real persona reply after the persisted delivery.
1330/// Generated reports and owner free text can never offer approval themselves.
1331pub fn approval_offered(talk: &talk::Talk, q: &Question) -> bool {
1332    talk.status.open()
1333        && q.status.open()
1334        && q.merge_target.is_some()
1335        && q.routed_chat.as_deref() == Some(talk.id.as_str())
1336        && talk.notified.contains(&format!("question:{}", q.id))
1337        && talk.turns.iter().any(|turn| {
1338            talk::sender(turn, None) == talk::Sender::Persona && turn.body.contains(&q.id)
1339        })
1340}
1341
1342fn task_of_with_watches(
1343    q: &Question,
1344    tasks: &[Task],
1345    watches: &[crate::release_watch::WatchState],
1346) -> Option<String> {
1347    let mut ids = std::collections::BTreeSet::new();
1348    if let Some(id) = task_of(q, tasks) {
1349        ids.insert(id);
1350    }
1351    for reference in crate::consult::question_task_refs(q, watches) {
1352        for task in tasks.iter().filter(|t| match reference {
1353            crate::consult::QuestionTaskRef::Task(id) => t.id == id,
1354            crate::consult::QuestionTaskRef::Run(id) => t.runs.iter().any(|r| r == id),
1355        }) {
1356            ids.insert(task.id.clone());
1357        }
1358    }
1359    if ids.len() == 1 {
1360        ids.pop_first()
1361    } else {
1362        None
1363    }
1364}
1365
1366#[cfg(test)]
1367mod tests {
1368    use super::*;
1369    use crate::ask::{Answer, QuestionStatus};
1370
1371    #[tokio::test]
1372    async fn release_2029_stays_answered_across_partial_import_and_restart() {
1373        use crate::{task_decision::Status, task_inquiry::Outbox};
1374        let home = tempfile::tempdir().unwrap();
1375        let home = home.path();
1376        let questions = Questions::at(home.join("questions"));
1377        let queue = Queue::at(home.join("queue"));
1378        let talks = Talks::at(home.join("talks"));
1379        let outbox = Outbox::at(home);
1380        let mut saved = Vec::new();
1381        for index in 0..66 {
1382            let mut q = Question::new(
1383                String::new(),
1384                crate::bump::NOTICE_NODE.into(),
1385                "release-watch".into(),
1386                "Release approval".into(),
1387                "Saved reviewed head".into(),
1388                vec!["merge".into(), "hold".into()],
1389            );
1390            q.id = format!(
1391                "20261109-014940-871849981cd969b1-0000000000000000-{}",
1392                1964 + index
1393            );
1394            q.merge_target = Some(crate::merge_decision::Target {
1395                pr: "https://example.test/mebae/pull/100".into(),
1396                head: "4d5a46f99a678608d2b883498d8bebd9399c0261".into(),
1397                language: "en".into(),
1398            });
1399            q.answer(Answer::Choice(
1400                if index == 0 { "hold" } else { "merge" }.into(),
1401            ))
1402            .unwrap();
1403            q.answered_at = Some("2026-11-08T17:03:30.66862Z".parse().unwrap());
1404            q.answer_delivered = true;
1405            questions.put(&mut q).unwrap();
1406            saved.push(q);
1407        }
1408        // A real effect receipt is different from answer delivery or missing ownership.
1409        let receipts = home.join("release-watch-receipts");
1410        std::fs::create_dir_all(&receipts).unwrap();
1411        let receipt = crate::release_watch::WatchState {
1412            applied: vec![saved[0].id.clone()],
1413            ..Default::default()
1414        };
1415        std::fs::write(
1416            receipts.join(format!("{}.json", saved[0].id)),
1417            serde_json::to_vec(&receipt).unwrap(),
1418        )
1419        .unwrap();
1420        // Simulate a partially completed v1 import, including a mistaken passive
1421        // classification that is no longer in pending.
1422        outbox.enqueue(history_record(&saved[1], None)).unwrap();
1423        let dir = home.join("notifications/task-chat-migration-v1");
1424        std::fs::create_dir_all(&dir).unwrap();
1425        std::fs::write(
1426            dir.join("state.json"),
1427            serde_json::to_vec(&serde_json::json!({
1428                "schema": 1, "sources": saved.iter().map(|q| &q.id).collect::<Vec<_>>(),
1429                "pending": saved[64..].iter().map(|q| &q.id).collect::<Vec<_>>()
1430            }))
1431            .unwrap(),
1432        )
1433        .unwrap();
1434        let source = &saved[65];
1435        assert!(source.id.ends_with("2029"));
1436        let bytes = std::fs::read(questions.path_of(&source.id)).unwrap();
1437        let assert_history = || {
1438            let read = questions.get(&source.id).unwrap();
1439            assert_eq!(read.status, QuestionStatus::Answered);
1440            assert_eq!(read.resolution().as_deref(), Some("merge"));
1441            assert_eq!(read.answered_at, source.answered_at);
1442            assert_eq!(
1443                questions.list().iter().filter(|q| q.status.open()).count(),
1444                0
1445            );
1446            assert!(
1447                questions
1448                    .get_for_effects(&source.id)
1449                    .unwrap()
1450                    .resolution()
1451                    .is_none()
1452            );
1453            assert!(
1454                questions
1455                    .update(&source.id, |q| q.answer(Answer::Choice("merge".into())))
1456                    .is_err()
1457            );
1458            let mut operational = questions.get_for_effects(&source.id).unwrap();
1459            operational.abandon("old deadline");
1460            assert!(
1461                questions.put(&mut operational).is_err(),
1462                "quarantine must not activate a default on timeout"
1463            );
1464            assert_eq!(std::fs::read(questions.path_of(&source.id)).unwrap(), bytes);
1465        };
1466        assert_history();
1467        assert_eq!(
1468            questions
1469                .abandon_for_run("", "retired source owner")
1470                .unwrap(),
1471            0
1472        );
1473        assert_history();
1474        let mut waiting = source.clone();
1475        assert!(matches!(
1476            crate::ask::resume_wait(&mut waiting, &questions, std::time::Duration::ZERO)
1477                .await
1478                .unwrap(),
1479            crate::ask::Wait::Pending
1480        ));
1481        assert_history();
1482        sweep(&queue, &talks, &questions, home);
1483        assert_history();
1484        assert_eq!(migration_pending(home).unwrap().len(), 2);
1485        assert!(
1486            outbox.get(&source.id).is_err(),
1487            "2029 is beyond the first batch"
1488        );
1489        assert_eq!(
1490            outbox.get(&saved[0].id).unwrap().decision.unwrap().status,
1491            Status::Resolved
1492        );
1493        let repaired = outbox.get(&saved[1].id).unwrap();
1494        assert!(!repaired.archived);
1495        assert_eq!(repaired.decision.unwrap().status, Status::RetryNeeded);
1496        // Reopening all stores exercises the persisted correction cursor.
1497        for _ in 0..2 {
1498            sweep(
1499                &Queue::at(home.join("queue")),
1500                &Talks::at(home.join("talks")),
1501                &Questions::at(home.join("questions")),
1502                home,
1503            );
1504            assert_history();
1505        }
1506        assert!(migration_pending(home).unwrap().is_empty());
1507        let imported = outbox.get(&source.id).unwrap();
1508        assert!(!imported.archived);
1509        assert!(imported.task.is_empty());
1510        assert!(
1511            imported
1512                .delivery_error
1513                .unwrap()
1514                .contains("missing or ambiguous")
1515        );
1516        let decision = imported.decision.unwrap();
1517        assert_eq!(decision.status, Status::RetryNeeded);
1518        assert!(decision.request.is_none());
1519        assert!(decision.source_answer_at.is_none());
1520        assert!(queue.list().is_empty());
1521        assert!(talks.list().is_empty());
1522        let mut later = saved[1].clone();
1523        later.id = "outside-boundary".into();
1524        questions.put(&mut later).unwrap();
1525        sweep(&queue, &talks, &questions, home);
1526        assert!(
1527            outbox.get(&later.id).is_err(),
1528            "correction must not expand its boundary"
1529        );
1530    }
1531
1532    #[test]
1533    fn history_correction_preserves_accepted_and_completed_decisions() {
1534        let home = tempfile::tempdir().unwrap();
1535        let outbox = crate::task_inquiry::Outbox::at(home.path());
1536        for completed in [false, true] {
1537            let q = Question::new(
1538                String::new(),
1539                crate::bump::NOTICE_NODE.into(),
1540                "release-watch".into(),
1541                "Saved release".into(),
1542                String::new(),
1543                vec!["hold".into()],
1544            );
1545            let mut record = history_record(&q, None);
1546            record.archived = false;
1547            record.decision = Some(crate::task_decision::Decision::awaiting(q.summary.clone()));
1548            outbox.enqueue(record).unwrap();
1549            outbox
1550                .update_decision(&q.id, |d| {
1551                    if completed {
1552                        d.applied("explicit durable effect receipt")
1553                    } else {
1554                        d.accept("decision: hold")
1555                    }
1556                })
1557                .unwrap();
1558            let before = outbox.get(&q.id).unwrap();
1559            outbox.reclassify_history(history_record(&q, None)).unwrap();
1560            assert_eq!(outbox.get(&q.id).unwrap(), before);
1561        }
1562    }
1563
1564    #[test]
1565    fn routed_merge_accepts_direct_answers_and_checks_optional_button_binding() {
1566        let mut q = Question::new(
1567            "run".into(),
1568            crate::land::APPROVAL_NODE.into(),
1569            "land".into(),
1570            "Merge?".into(),
1571            String::new(),
1572            vec!["merge".into(), "hold".into()],
1573        );
1574        q.routed_task = Some("task".into());
1575        q.routed_chat = Some("chat".into());
1576        q.merge_target = Some(crate::merge_decision::Target {
1577            pr: "https://example.test/pull/1".into(),
1578            head: "head-a".into(),
1579            language: "en".into(),
1580        });
1581        assert!(q.clone().answer(Answer::Choice("merge".into())).is_ok());
1582        assert!(
1583            q.settle_by_deputy("seat", "merge", None).is_err(),
1584            "a routed decision is the task chat's, never a deputy's"
1585        );
1586        assert!(
1587            q.answer_chat_button(Answer::Choice("merge".into()), "other-chat", "head-a")
1588                .is_err()
1589        );
1590        assert!(
1591            q.answer_chat_button(Answer::Choice("merge".into()), "chat", "old-head")
1592                .is_err()
1593        );
1594        assert!(
1595            q.answer_chat_button(Answer::Text("merge".into()), "chat", "head-a")
1596                .is_err()
1597        );
1598        assert_eq!(q.status, QuestionStatus::Open);
1599        q.answer_chat_button(Answer::Choice("merge".into()), "chat", "head-a")
1600            .unwrap();
1601        assert_eq!(q.resolution().as_deref(), Some("merge"));
1602        assert!(
1603            q.answer_chat_button(Answer::Choice("merge".into()), "chat", "head-a")
1604                .is_err()
1605        );
1606    }
1607
1608    #[test]
1609    fn gate_divergence_and_release_questions_route_and_await_a_decision() {
1610        let q = |node: &str, seat: &str, choices: Vec<String>| {
1611            Question::new(
1612                "run".into(),
1613                node.into(),
1614                seat.into(),
1615                "s".into(),
1616                String::new(),
1617                choices,
1618            )
1619        };
1620        let gate = q(
1621            crate::github_text::ASK_NODE,
1622            "posting-gate",
1623            vec!["use fallback".into()],
1624        );
1625        assert!(chat_routable(&gate) && awaits_decision(&gate));
1626        // Triage discard / dependency decisions are applied by the daemon from
1627        // the recorded answer, so they stay open until the chat settles them.
1628        for node in [crate::triage::NODE, crate::triage::DEPS_NODE] {
1629            let triage = q(node, "triage", vec!["hold".into(), "discard".into()]);
1630            assert!(chat_routable(&triage) && awaits_decision(&triage));
1631        }
1632        let mut acted = q("conduct", "conductor", vec!["finish".into(), "hold".into()]);
1633        acted
1634            .actions
1635            .insert("finish".into(), crate::ask::ChoiceAction::Done);
1636        assert!(chat_routable(&acted) && awaits_decision(&acted));
1637        let diverged = q(
1638            crate::reconcile::NODE,
1639            crate::reconcile::SEAT,
1640            vec!["a".into()],
1641        );
1642        assert!(chat_routable(&diverged) && awaits_decision(&diverged));
1643        let release = q(
1644            crate::bump::NOTICE_NODE,
1645            "release-watch",
1646            vec!["hold".into()],
1647        );
1648        assert!(chat_routable(&release) && awaits_decision(&release));
1649        let legacy_release = q(
1650            crate::bump::NOTICE_NODE,
1651            "release-watch",
1652            vec![crate::land::APPROVE.into(), crate::land::HOLD.into()],
1653        );
1654        assert!(chat_routable(&legacy_release));
1655        assert!(awaits_decision(&legacy_release));
1656        // A choice-less bump notice is informational; a targetless approval
1657        // still needs an owner discussion and safe recovery in its chat.
1658        assert!(!chat_routable(&q(crate::bump::NOTICE_NODE, "bump", vec![])));
1659        assert!(chat_routable(&q(
1660            crate::land::APPROVAL_NODE,
1661            "land",
1662            vec!["merge".into()]
1663        )));
1664        let q = |node: &str| q(node, "seat", vec![]);
1665        assert!(chat_routable(&q("conduct")) && !awaits_decision(&q("conduct")));
1666        let mut m = q(crate::bump::NOTICE_NODE);
1667        m.merge_target = Some(crate::merge_decision::Target {
1668            pr: "https://example.test/pull/1".into(),
1669            head: "h".into(),
1670            language: "en".into(),
1671        });
1672        assert!(chat_routable(&m));
1673    }
1674
1675    #[test]
1676    fn unreadable_repository_config_keeps_task_routing_and_pending_delivery() {
1677        let home = tempfile::tempdir().unwrap();
1678        let queue = Queue::at(home.path().join("queue"));
1679        let repo = home.path().join("repo");
1680        std::fs::create_dir(&repo).unwrap();
1681        std::fs::write(repo.join("magi.toml"), "this is = [not toml").unwrap();
1682        let mut task = Task::new("t".into(), "i".into(), repo, crate::queue::Source::Human);
1683        queue.put(&mut task).unwrap();
1684        let questions = Questions::at(home.path().join("questions"));
1685        let mut q = Question::new(
1686            task.id.clone(),
1687            "conduct".into(),
1688            "seat".into(),
1689            "s".into(),
1690            String::new(),
1691            vec![],
1692        );
1693        questions.put(&mut q).unwrap();
1694        assert_eq!(q.routed_task.as_deref(), Some(task.id.as_str()));
1695        assert_eq!(
1696            questions.get(&q.id).unwrap().routed_task.as_deref(),
1697            Some(task.id.as_str())
1698        );
1699        let talks = Talks::at(home.path().join("talks"));
1700        sweep(&queue, &talks, &questions, home.path());
1701        let outbox = crate::task_inquiry::Outbox::at(home.path());
1702        outbox.sweep(&queue, &talks).unwrap();
1703        assert!(
1704            migration_issues(home.path())
1705                .iter()
1706                .any(|issue| issue.id == q.id)
1707        );
1708        let pending = outbox.get(&q.id).unwrap();
1709        assert!(pending.delivered_to.is_none());
1710        assert!(talks.list().is_empty());
1711        assert_eq!(
1712            pending.decision.unwrap().status,
1713            crate::task_decision::Status::AwaitingOwner
1714        );
1715    }
1716
1717    #[test]
1718    fn a_delivered_decision_is_not_rewritten_on_every_sweep() {
1719        let home = tempfile::tempdir().unwrap();
1720        let queue = Queue::at(home.path().join("queue"));
1721        let talks = talk::Talks::at(home.path().join("talks"));
1722        let questions = Questions::at(home.path().join("questions"));
1723        let mut task = Task::new(
1724            "t".into(),
1725            "i".into(),
1726            home.path().to_path_buf(),
1727            crate::queue::Source::Human,
1728        );
1729        queue.put(&mut task).unwrap();
1730        let mut q = Question::new(
1731            task.id.clone(),
1732            "conduct".into(),
1733            "conductor".into(),
1734            "Finish?".into(),
1735            String::new(),
1736            vec!["finish".into(), "hold".into()],
1737        );
1738        q.actions
1739            .insert("finish".into(), crate::ask::ChoiceAction::Done);
1740        q.routed_task = Some(task.id.clone());
1741        q.routed_chat = Some("chat".into());
1742        questions.put(&mut q).unwrap();
1743        assert!(awaits_decision(&q));
1744        let path = questions.path_of(&q.id);
1745        let before = std::fs::read(&path).unwrap();
1746        let written = std::fs::metadata(&path).unwrap().modified().unwrap();
1747        // A rewrite of identical bytes still replaces the file; give it a
1748        // timestamp it could not share with the original write.
1749        std::thread::sleep(std::time::Duration::from_millis(50));
1750        sweep(&queue, &talks, &questions, home.path());
1751        sweep(&queue, &talks, &questions, home.path());
1752        assert_eq!(std::fs::read(&path).unwrap(), before);
1753        assert_eq!(
1754            std::fs::metadata(&path).unwrap().modified().unwrap(),
1755            written
1756        );
1757    }
1758    #[test]
1759    fn repair_receipts_keep_transport_and_failed_repairs_pending() {
1760        use crate::{
1761            ask::ChoiceAction,
1762            run::{MergeRepair, MergeRepairPhase as Phase, RunState},
1763            task_decision::{Decision, Status},
1764            task_inquiry::Outbox,
1765        };
1766        let temp = tempfile::tempdir().unwrap();
1767        let home = temp.path();
1768        let queue = Queue::at(home.join("queue"));
1769        let mut run = RunState::new(
1770            home.into(),
1771            "main".into(),
1772            "base".into(),
1773            "work".into(),
1774            Config::default(),
1775        );
1776        run.reserve_under(home).unwrap();
1777        let mut q = Question::new(
1778            run.id.clone(),
1779            crate::land::APPROVAL_NODE.into(),
1780            "land".into(),
1781            "Repair findings".into(),
1782            String::new(),
1783            vec![crate::land::REPAIR.into()],
1784        );
1785        q.merge_target = Some(crate::merge_decision::Target {
1786            pr: "https://example.test/pull/1".into(),
1787            head: "head".into(),
1788            language: "en".into(),
1789        });
1790        q.actions.insert(
1791            crate::land::REPAIR.into(),
1792            ChoiceAction::Resume {
1793                run: run.id.clone(),
1794            },
1795        );
1796        q.answer(Answer::Choice(crate::land::REPAIR.into()))
1797            .unwrap();
1798        run.next_pass_inquiries = vec![q.id.clone()];
1799        run.begin_pass();
1800        run.save_under(home).unwrap();
1801        let mut task = Task::new(
1802            "work".into(),
1803            "work".into(),
1804            home.into(),
1805            crate::queue::Source::Human,
1806        );
1807        task.runs.push(run.id.clone());
1808        task.mark_action_applied(&q.id);
1809        queue.put(&mut task).unwrap();
1810        let outbox = Outbox::at(home);
1811        let mut record = history_record(&q, Some(&task));
1812        let mut decision = Decision::awaiting(q.summary.clone());
1813        decision
1814            .accept(&format!("decision: {}", crate::land::REPAIR))
1815            .unwrap();
1816        record.decision = Some(decision);
1817        record.archived = false;
1818        outbox.enqueue(record).unwrap();
1819        let check = |expected| {
1820            sync_effect_receipt(home, &Queue::at(home.join("queue")), &q);
1821            let decision = Outbox::at(home).get(&q.id).unwrap().decision.unwrap();
1822            assert_eq!(decision.status, expected);
1823            decision
1824        };
1825        check(Status::Queued); // Resume started; no repair request was consumed yet.
1826        run.merge_repairs.push(MergeRepair {
1827            question: "unrelated".into(),
1828            head: "head".into(),
1829            pr: q.merge_target.as_ref().unwrap().pr.clone(),
1830            reviews: vec![],
1831            gate: vec![],
1832            gate_head: None,
1833            gate_fixes: vec![],
1834            pre_gate: vec![],
1835            phase: Phase::Complete,
1836            failure: None,
1837        });
1838        run.save_under(home).unwrap();
1839        check(Status::Queued);
1840        run.merge_repairs[0].question = q.id.clone();
1841        for phase in [
1842            Phase::Requested,
1843            Phase::Fixing,
1844            Phase::Reviewing,
1845            Phase::Failed,
1846        ] {
1847            run.merge_repairs[0].phase = phase;
1848            run.merge_repairs[0].failure =
1849                (phase == Phase::Failed).then(|| "dirty worktree; inspect before retry".into());
1850            run.save_under(home).unwrap();
1851            let decision = check(if phase == Phase::Failed {
1852                Status::RetryNeeded
1853            } else {
1854                Status::Queued
1855            });
1856            if phase == Phase::Failed {
1857                assert!(decision.error.unwrap().contains("dirty worktree"));
1858                assert!(
1859                    !decision.retry_safe,
1860                    "a repair failure cannot authorize blind replay"
1861                );
1862            }
1863        }
1864        run.merge_repairs[0].phase = Phase::Complete;
1865        run.merge_repairs[0].head = "different-head".into();
1866        run.save_under(home).unwrap();
1867        check(Status::RetryNeeded);
1868        run.merge_repairs[0].head = "head".into();
1869        run.merge_repairs[0].failure = None;
1870        run.save_under(home).unwrap();
1871        check(Status::Resolved);
1872        check(Status::Resolved);
1873    }
1874
1875    #[test]
1876    fn landing_stop_receipts_require_the_intended_effect_after_restart() {
1877        use crate::{
1878            ask::ChoiceAction,
1879            merge_decision::{self as md, Replacement, Target},
1880            queue::{Source, TaskStatus},
1881            run::{PrRecord, RunState, RunStatus},
1882            task_decision::{Decision, Status},
1883            task_inquiry::Outbox,
1884        };
1885        for choice in [crate::land::HOLD, "reimplement:beta"] {
1886            let temp = tempfile::tempdir().unwrap();
1887            let home = temp.path();
1888            let queue = Queue::at(home.join("queue"));
1889            let mut run = RunState::new(
1890                home.into(),
1891                "main".into(),
1892                "base".into(),
1893                "work".into(),
1894                Config::default(),
1895            );
1896            run.reserve_under(home).unwrap();
1897            run.status = RunStatus::Blocked;
1898            run.driver_exited = true;
1899            run.pr = Some(PrRecord {
1900                url: "https://example.test/pull/1".into(),
1901                number: 1,
1902                state: "open".into(),
1903                checks: "green".into(),
1904                round: 1,
1905                rounds: 2,
1906                red_at_merge: vec![],
1907            });
1908            let mut q = Question::new(
1909                run.id.clone(),
1910                crate::land::APPROVAL_NODE.into(),
1911                "land".into(),
1912                "Stop landing".into(),
1913                String::new(),
1914                vec![choice.into()],
1915            );
1916            q.merge_target = Some(Target {
1917                pr: run.pr.as_ref().unwrap().url.clone(),
1918                head: "head".into(),
1919                language: "en".into(),
1920            });
1921            if choice != crate::land::HOLD {
1922                q.actions.insert(
1923                    choice.into(),
1924                    ChoiceAction::Resume {
1925                        run: run.id.clone(),
1926                    },
1927                );
1928            }
1929            q.answer(Answer::Choice(choice.into())).unwrap();
1930            // The old run consumed the Resume transport, but closure may fail.
1931            run.next_pass_inquiries = vec![q.id.clone()];
1932            run.begin_pass();
1933            run.save_under(home).unwrap();
1934            let mut task = Task::new("work".into(), "work".into(), home.into(), Source::Human);
1935            task.runs.push(run.id.clone());
1936            task.hold_manual(Some("landing stopped".into()));
1937            task.mark_action_applied(&q.id);
1938            queue.put(&mut task).unwrap();
1939            let mut record = history_record(&q, Some(&task));
1940            let mut decision = Decision::awaiting(q.summary.clone());
1941            decision.accept(&format!("decision: {choice}")).unwrap();
1942            record.decision = Some(decision);
1943            record.archived = false;
1944            Outbox::at(home).enqueue(record).unwrap();
1945            let check = |expected| {
1946                sync_effect_receipt(home, &Queue::at(home.join("queue")), &q);
1947                assert_eq!(
1948                    Outbox::at(home)
1949                        .get(&q.id)
1950                        .unwrap()
1951                        .decision
1952                        .unwrap()
1953                        .status,
1954                    expected
1955                );
1956            };
1957            check(Status::Queued);
1958            run.merge_decision = Some(md::Decision {
1959                question: q.id.clone(),
1960                target: q.merge_target.clone().unwrap(),
1961                choice: choice.into(),
1962                closed: false,
1963                replacement_run: None,
1964                replacement_pr: None,
1965            });
1966            run.save_under(home).unwrap();
1967            if choice == crate::land::HOLD {
1968                // A checkpoint alone is insufficient until the task hold commits.
1969                task.actions_applied.clear();
1970                task.status = TaskStatus::Running;
1971                queue.put(&mut task).unwrap();
1972                check(Status::Queued);
1973                task.hold_manual(Some("landing stopped".into()));
1974                task.mark_action_applied(&q.id);
1975                queue.put(&mut task).unwrap();
1976                // A later release must not erase the already committed hold.
1977                task.release_operator("chat", None);
1978                queue.put(&mut task).unwrap();
1979                assert!(
1980                    effect_receipt(home, &queue, &q, Some(&task.id))
1981                        .unwrap()
1982                        .is_some()
1983                );
1984                // New receipts also survive reopening/removing the run checkpoint.
1985                task.decision_effects
1986                    .insert(q.id.clone(), format!("decision: {choice}"));
1987                queue.put(&mut task).unwrap();
1988                run.merge_decision = None;
1989                run.save_under(home).unwrap();
1990                check(Status::Resolved);
1991            } else {
1992                check(Status::Queued); // Failed closure, despite the old pass marker.
1993                run.merge_decision.as_mut().unwrap().closed = true;
1994                run.status = RunStatus::Superseded;
1995                run.pr.as_mut().unwrap().state = "closed".into();
1996                run.save_under(home).unwrap();
1997                check(Status::Queued); // Closure and queueing are not replacement execution.
1998                let mut next = RunState::new(
1999                    home.into(),
2000                    "main".into(),
2001                    "base".into(),
2002                    "replacement".into(),
2003                    Config::default(),
2004                );
2005                next.reserve_under(home).unwrap();
2006                next.replaces = Some(Replacement {
2007                    question: q.id.clone(),
2008                    run: run.id.clone(),
2009                    pr: q.merge_target.as_ref().unwrap().pr.clone(),
2010                    agent: "beta".into(),
2011                    context: String::new(),
2012                });
2013                next.save_under(home).unwrap();
2014                run.merge_decision.as_mut().unwrap().replacement_run = Some(next.id.clone());
2015                run.save_under(home).unwrap();
2016                task.start(next.id.clone());
2017                queue.put(&mut task).unwrap();
2018                check(Status::Queued); // Crash before the replacement enters execution.
2019                next.next_pass_task_entry = true;
2020                next.begin_pass();
2021                next.save_under(home).unwrap();
2022                check(Status::Resolved);
2023            }
2024            check(Status::Resolved);
2025        }
2026    }
2027
2028    #[test]
2029    fn quiet_release_receipts_resolve_pending_decisions_after_restart() {
2030        use crate::{
2031            task_decision::{Decision, Status},
2032            task_inquiry::Outbox,
2033        };
2034        for choice in [crate::release_watch::HOLD, crate::release_watch::LEAVE_IT] {
2035            let dir = tempfile::tempdir().unwrap();
2036            let home = dir.path();
2037            let queue = Queue::at(home.join("queue"));
2038            let mut task = Task::new(
2039                "release".into(),
2040                "release".into(),
2041                home.into(),
2042                crate::queue::Source::Human,
2043            );
2044            queue.put(&mut task).unwrap();
2045            let mut q = Question::new(
2046                "run".into(),
2047                crate::bump::NOTICE_NODE.into(),
2048                "release-watch".into(),
2049                "release stalled".into(),
2050                String::new(),
2051                vec![choice.into()],
2052            );
2053            q.answer(Answer::Choice(choice.into())).unwrap();
2054            let mut record = history_record(&q, Some(&task));
2055            let mut decision = Decision::awaiting(q.summary.clone());
2056            decision.accept(&format!("decision: {choice}")).unwrap();
2057            record.decision = Some(decision);
2058            record.archived = false;
2059            Outbox::at(home).enqueue(record).unwrap();
2060            sync_effect_receipt(home, &queue, &q);
2061            assert_eq!(
2062                Outbox::at(home)
2063                    .get(&q.id)
2064                    .unwrap()
2065                    .decision
2066                    .unwrap()
2067                    .status,
2068                Status::Queued
2069            );
2070            let receipts = home.join("release-watch-receipts");
2071            std::fs::create_dir_all(&receipts).unwrap();
2072            let st = crate::release_watch::WatchState {
2073                applied: vec![q.id.clone()],
2074                ..Default::default()
2075            };
2076            std::fs::write(
2077                receipts.join(format!("{}.json", q.id)),
2078                serde_json::to_vec(&st).unwrap(),
2079            )
2080            .unwrap();
2081            for _ in 0..2 {
2082                sync_effect_receipt(home, &Queue::at(home.join("queue")), &q);
2083                assert_eq!(
2084                    Outbox::at(home)
2085                        .get(&q.id)
2086                        .unwrap()
2087                        .decision
2088                        .unwrap()
2089                        .status,
2090                    Status::Resolved
2091                );
2092            }
2093        }
2094    }
2095
2096    #[test]
2097    fn dismiss_receipt_resolves_done_tasks_and_later_attempts_without_task_markers() {
2098        use crate::{
2099            ask::Answer,
2100            queue::{Source, Task, TaskStatus},
2101            run::{LandApproval, PrRecord, RunState, RunStatus},
2102            task_decision::{Decision, Status},
2103            task_inquiry::Outbox,
2104        };
2105        for (later_attempt, incomplete) in [(false, false), (true, false), (false, true)] {
2106            let temp = tempfile::tempdir().unwrap();
2107            let home = temp.path();
2108            let queue = Queue::at(home.join("queue"));
2109            let mut state = RunState::new(
2110                home.into(),
2111                "main".into(),
2112                "base".into(),
2113                "work".into(),
2114                Config::default(),
2115            );
2116            state.reserve_under(home).unwrap();
2117            state.status = RunStatus::Blocked;
2118            state.driver_exited = true;
2119            let mut q = Question::new(
2120                state.id.clone(),
2121                crate::land::APPROVAL_NODE.into(),
2122                "land".into(),
2123                "Obsolete approval".into(),
2124                String::new(),
2125                vec![crate::merge_decision::DISMISS.into()],
2126            );
2127            state.land_approval = Some(LandApproval {
2128                question: q.id.clone(),
2129                head: "head".into(),
2130            });
2131            state.pr = Some(PrRecord {
2132                url: "https://example.test/pull/1".into(),
2133                number: 1,
2134                state: "open".into(),
2135                checks: "green".into(),
2136                round: 1,
2137                rounds: 2,
2138                red_at_merge: vec![],
2139            });
2140            state.save_under(home).unwrap();
2141            let mut task = Task::new("work".into(), "work".into(), home.into(), Source::Human);
2142            task.runs.push(state.id.clone());
2143            task.status = TaskStatus::Done;
2144            if later_attempt {
2145                task.runs.push("later-run".into());
2146                task.status = TaskStatus::Queued;
2147            }
2148            if incomplete {
2149                task.status = TaskStatus::Parked;
2150            }
2151            queue.put(&mut task).unwrap();
2152            q.answer(Answer::Choice(crate::merge_decision::DISMISS.into()))
2153                .unwrap();
2154            let outbox = Outbox::at(home);
2155            let mut record = history_record(&q, Some(&task));
2156            let mut decision = Decision::awaiting(q.summary.clone());
2157            decision.accept("decision: dismiss").unwrap();
2158            record.decision = Some(decision);
2159            record.archived = false;
2160            outbox.enqueue(record).unwrap();
2161            if incomplete {
2162                // Crash window: the run stop was saved, but the latest
2163                // task transition has not yet committed.
2164                state.merge_decision = Some(crate::merge_decision::Decision {
2165                    question: q.id.clone(),
2166                    target: crate::merge_decision::Target {
2167                        pr: state.pr.as_ref().unwrap().url.clone(),
2168                        head: "head".into(),
2169                        language: "en".into(),
2170                    },
2171                    choice: crate::merge_decision::DISMISS.into(),
2172                    closed: false,
2173                    replacement_run: None,
2174                    replacement_pr: None,
2175                });
2176                state.save_under(home).unwrap();
2177                sync_effect_receipt(home, &queue, &q);
2178                assert_eq!(
2179                    outbox.get(&q.id).unwrap().decision.unwrap().status,
2180                    Status::Queued
2181                );
2182            }
2183            crate::merge_decision::dismiss(home, &q).unwrap();
2184            let after = std::fs::read(queue.path_of(&task.id)).unwrap();
2185            assert_eq!(
2186                queue.get(&task.id).unwrap().action_applied(&q.id),
2187                incomplete
2188            );
2189            for _ in 0..2 {
2190                sync_effect_receipt(home, &queue, &q);
2191                assert_eq!(
2192                    Outbox::at(home)
2193                        .get(&q.id)
2194                        .unwrap()
2195                        .decision
2196                        .unwrap()
2197                        .status,
2198                    Status::Resolved
2199                );
2200                assert_eq!(std::fs::read(queue.path_of(&task.id)).unwrap(), after);
2201            }
2202            assert_eq!(
2203                RunState::load_under(&q.run, home)
2204                    .unwrap()
2205                    .pr
2206                    .unwrap()
2207                    .state,
2208                "open"
2209            );
2210        }
2211    }
2212}