1use crate::task_inquiry::HistoryResolution;
4use anyhow::{Context, Result};
5use std::path::Path;
6
7use crate::{
8 ask::{Question, Questions},
9 config::Config,
10 queue::{Queue, Task},
11 talk::{self, Talks},
12};
13
14pub fn task_of(q: &Question, tasks: &[Task]) -> Option<String> {
16 let mut matching = tasks
17 .iter()
18 .filter(|t| t.id == q.run || t.runs.contains(&q.run));
19 let task = matching.next()?;
20 matching.next().is_none().then(|| task.id.clone())
21}
22
23pub(crate) fn chat_routable(q: &Question) -> bool {
26 q.node != crate::bump::NOTICE_NODE
27 || q.merge_target.is_some()
28 || (q.seat == "release-watch" && !q.choices.is_empty())
29}
30
31pub fn awaits_decision(q: &Question) -> bool {
37 q.node == crate::land::APPROVAL_NODE
38 || q.merge_target.is_some()
39 || (chat_routable(q)
40 && (!q.actions.is_empty()
43 || q.node == crate::github_text::ASK_NODE
44 || q.node == crate::triage::NODE
45 || q.node == crate::triage::DEPS_NODE
46 || (q.node == crate::reconcile::NODE && q.seat == crate::reconcile::SEAT)
47 || (q.node == crate::bump::NOTICE_NODE && q.seat == "release-watch")))
48}
49
50pub(crate) fn routes(q: &Question, home: &Path) -> bool {
52 if q.routed_task.is_some() {
53 return true;
54 }
55 if standalone_inquiry(home, q) {
56 return false;
57 }
58 if !q.status.open() || !chat_routable(q) {
59 return false;
60 }
61 let tasks = Queue::at(home.join("queue")).list();
62 let watches = crate::release_watch::states_for_questions(home, std::slice::from_ref(q));
63 task_of_with_watches(q, &tasks, &watches).is_some()
64}
65
66pub(crate) fn destination(
68 queue: &Queue,
69 talks: &Talks,
70 task_id: &str,
71) -> Result<(Task, talk::Talk)> {
72 destination_checked(queue, talks, task_id, |_| Ok(()))
73}
74
75pub(crate) fn destination_checked(
77 queue: &Queue,
78 talks: &Talks,
79 task_id: &str,
80 check: impl FnOnce(&Task) -> Result<()>,
81) -> Result<(Task, talk::Talk)> {
82 let mut reserved = None;
83 let mut invalid = None;
84 queue.modify(task_id, |task| {
85 if let Err(error) = check(task) {
86 invalid = Some(error);
87 return false;
88 }
89 let associated = task
90 .chat
91 .clone()
92 .or_else(|| task.filed_by_chat().map(str::to_owned))
93 .or_else(|| crate::consult::chat_talk_of(&queue.list(), task));
94 let id = associated.unwrap_or_else(|| format!("task-{}", task.id));
97 let changed = task.chat.as_ref() != Some(&id);
98 task.chat = Some(id.clone());
99 reserved = Some((task.clone(), id));
100 changed
101 })?;
102 if let Some(error) = invalid {
103 return Err(error);
104 }
105 let (task, id) = reserved.context("task chat destination was not reserved")?;
106 let chat = destination_in(talks, &task.repo, &id)?;
107 Ok((task, chat))
108}
109
110pub(crate) fn destination_in(talks: &Talks, repo: &Path, id: &str) -> Result<talk::Talk> {
113 let load = |id: &str| -> Result<talk::Talk> {
114 if talks.path_of(id).exists() {
115 talks.get(id)
116 } else {
117 let (cfg, _) = Config::discover(repo, None)?;
118 talk::begin_with_id(
119 talks,
120 &cfg,
121 repo.to_path_buf(),
122 None,
123 &talk::Preferred {
124 agent: None,
125 persona: None,
126 implementers: Some(1),
127 },
128 Some(id.to_owned()),
129 )
130 }
131 };
132 load(id)
133}
134
135pub(crate) fn live_record(home: &Path, task: &Task, q: &Question) -> crate::task_inquiry::Inquiry {
137 let run = if q.run == task.id {
138 task.runs.last().map(String::as_str).unwrap_or("none")
139 } else {
140 &q.run
141 };
142 let facts = crate::chat_notify::run_facts(home, run);
143 let clean = |s: &str| -> String {
144 crate::prompt::defuse(&crate::scrub::scrub(s, &crate::scrub::Identity::current()))
145 .chars()
146 .take(12_000)
147 .collect()
148 };
149 let pr = q
150 .merge_target
151 .as_ref()
152 .map(|t| t.pr.as_str())
153 .or(facts.pr.as_deref())
154 .unwrap_or("none");
155 let body = format!(
156 "# {}\n\n{}\n\n{}\n\nTask: {}\nRun: {}\nPR: {}\nState: {}\n",
157 crate::prompt::TASK_MESSAGE_HEADING,
158 clean(&q.summary),
159 clean(&q.detail),
160 task.id,
161 run,
162 clean(pr),
163 task.status.as_str()
164 );
165 let instructions = if let Some(target) = &q.merge_target {
166 format!(
167 "\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",
168 q.id, target.pr, target.head, q.id, q.id
169 )
170 } else if awaits_decision(q) {
171 let offered = if q.choices.is_empty() {
172 String::new()
173 } else {
174 format!(
175 " The recorded options are: {}.",
176 q.choices
177 .iter()
178 .map(|c| format!("`{c}`"))
179 .collect::<Vec<_>>()
180 .join(", ")
181 )
182 };
183 format!(
184 "\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",
185 q.id, q.id
186 )
187 } else {
188 "\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()
189 };
190 let legacy_answer = q.resolution().map(|answer| format!(
191 "\nHistorical saved reply (evidence only, never a new owner request): {}. Inspect the operation receipt; do not replay it.\n", clean(&answer)
192 )).unwrap_or_default();
193 let text = format!(
194 "{body}\nThis automatic report is not an owner instruction. Investigate and report; it authorizes neither repository edits nor new tasks.\n{instructions}{legacy_answer}"
195 );
196 crate::task_inquiry::Inquiry {
197 schema: 1,
198 id: q.id.clone(),
199 task: task.id.clone(),
200 run: task.runs.contains(&q.run).then(|| q.run.clone()),
201 repo: task.repo.clone(),
202 source: format!("{}:{}:{}", q.node, q.seat, q.run),
203 occurrence: None,
204 text,
205 display: format!("{body}{legacy_answer}"),
206 key: format!("question:{}", q.id),
207 evidence: Some(crate::notice_semantics::question(home, task, run, q)),
208 created_at: q.asked_at,
209 delivered_to: None,
210 decision: Some(crate::task_decision::Decision::awaiting(q.summary.clone())),
211 delivery_error: None,
212 archived: false,
213 }
214}
215
216pub fn post(
220 queue: &Queue,
221 talks: &Talks,
222 home: &Path,
223 task_id: &str,
224 q: &Question,
225) -> Result<String> {
226 post_in(queue, talks, home, task_id, q, &InquiryOwnership::default())
227}
228
229fn post_in(
230 queue: &Queue,
231 talks: &Talks,
232 home: &Path,
233 task_id: &str,
234 q: &Question,
235 ownership: &InquiryOwnership,
236) -> Result<String> {
237 let task = queue.get(task_id)?;
238 let outbox = crate::task_inquiry::Outbox::at(home);
239 outbox.enqueue(live_record(home, &task, q))?;
240 if q.resolution().is_some()
244 && q.accepted_answer_at.is_some()
245 && q.accepted_answer_at == q.answered_at
246 {
247 accept_fresh_reply(home, q, ownership)?;
248 }
249 outbox.deliver(queue, talks, &q.id)
250}
251
252#[derive(serde::Serialize, serde::Deserialize)]
256struct Migration {
257 schema: u32,
258 #[serde(default)]
260 classification_revision: u32,
261 pending: Vec<String>,
262 #[serde(default)]
264 sources: Option<std::collections::BTreeSet<String>>,
265 #[serde(default)]
266 errors: std::collections::BTreeMap<String, String>,
267}
268
269pub(crate) fn migration_sources(home: &Path) -> Result<Option<std::collections::BTreeSet<String>>> {
272 let path = home.join("notifications/task-chat-migration-v1/state.json");
273 let bytes = match std::fs::read(path) {
274 Ok(bytes) => bytes,
275 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
276 return Ok(Some(Default::default()));
277 }
278 Err(error) => return Err(error.into()),
279 };
280 let state: Migration = serde_json::from_slice(&bytes)?;
281 anyhow::ensure!(state.schema == 1, "unsupported inquiry migration");
282 Ok(state.sources)
283}
284
285#[derive(Default)]
287pub(crate) struct InquiryOwnership {
288 owned: std::cell::OnceCell<std::collections::HashMap<String, Vec<String>>>,
291 origins: std::cell::RefCell<std::collections::HashMap<String, (bool, bool)>>,
292}
293
294impl InquiryOwnership {
295 pub(crate) fn from_tasks(tasks: &[Task]) -> Self {
296 let index = Self::default();
297 let _ = index.owned.set(Self::owned_ids(tasks));
298 index
299 }
300
301 fn owned_ids(tasks: &[Task]) -> std::collections::HashMap<String, Vec<String>> {
302 let mut map: std::collections::HashMap<String, Vec<String>> =
303 std::collections::HashMap::new();
304 for task in tasks {
305 let mut seen = std::collections::HashSet::new();
306 for key in std::iter::once(&task.id).chain(task.runs.iter()) {
307 if seen.insert(key.as_str()) {
308 map.entry(key.clone()).or_default().push(task.id.clone());
309 }
310 }
311 }
312 map
313 }
314
315 fn index(&self, home: &Path) -> &std::collections::HashMap<String, Vec<String>> {
316 self.owned
317 .get_or_init(|| Self::owned_ids(&Queue::at(home.join("queue")).list()))
318 }
319
320 pub(crate) fn task_of(&self, home: &Path, q: &Question) -> Option<String> {
322 match self.index(home).get(&q.run)?.as_slice() {
323 [only] => Some(only.clone()),
324 _ => None,
325 }
326 }
327}
328
329pub(crate) fn standalone_inquiry(home: &Path, q: &Question) -> bool {
332 standalone_inquiry_in(home, q, &InquiryOwnership::default())
333}
334
335pub(crate) fn standalone_inquiry_in(
336 home: &Path,
337 q: &Question,
338 ownership: &InquiryOwnership,
339) -> bool {
340 if q.routed_task.is_some() || (q.node == crate::bump::NOTICE_NODE && q.seat == "release-watch")
341 {
342 return false;
343 }
344 if q.legacy_foreground || q.run.is_empty() {
345 return true;
346 }
347 if ownership.index(home).contains_key(&q.run) {
350 return false;
351 }
352 let (task_origin, foreground_origin) = *ownership
353 .origins
354 .borrow_mut()
355 .entry(q.run.clone())
356 .or_insert_with(|| {
357 let run = crate::run::RunState::load_under(&q.run, home).ok();
358 let origin = run.as_ref().and_then(|run| run.origin.as_ref());
359 (
360 origin.is_some_and(|origin| origin.task.is_some()),
361 origin.is_some_and(|origin| origin.task.is_none()),
362 )
363 });
364 if task_origin {
365 return false;
366 }
367 (q.node == "ask" && q.seat == "operator") || (q.cwd.is_some() && foreground_origin)
368}
369
370pub(crate) fn migrated_source(home: &Path, id: &str) -> bool {
371 migrated_source_in(home, id, &InquiryOwnership::default())
372}
373
374pub(crate) fn migrated_source_in(home: &Path, id: &str, ownership: &InquiryOwnership) -> bool {
375 if Questions::at(home.join("questions"))
378 .read_history(id)
379 .is_ok_and(|q| standalone_inquiry_in(home, &q, ownership))
380 {
381 return false;
382 }
383 migration_sources(home).map_or_else(
384 |error| {
385 tracing::warn!("source {id} stays held: {error:#}");
386 true
387 },
388 |sources| sources.as_ref().is_none_or(|ids| ids.contains(id)),
389 )
390}
391
392pub(crate) fn accept_fresh_reply(
396 home: &Path,
397 q: &Question,
398 ownership: &InquiryOwnership,
399) -> Result<()> {
400 if standalone_inquiry_in(home, q, ownership) {
401 return Ok(());
402 }
403 let outbox = crate::task_inquiry::Outbox::at(home);
404 match outbox.get(&q.id) {
405 Ok(record)
406 if record.decision.as_ref().is_some_and(|decision| {
407 decision.status == crate::task_decision::Status::Resolved
408 }) =>
409 {
410 return Ok(());
411 }
412 Ok(_) => {}
413 Err(error)
414 if error
415 .downcast_ref::<std::io::Error>()
416 .is_some_and(|error| error.kind() == std::io::ErrorKind::NotFound) =>
417 {
418 let tasks = Queue::at(home.join("queue")).list();
419 let watches = crate::release_watch::states_for_questions(home, std::slice::from_ref(q));
420 let task_id = task_of_with_watches(q, &tasks, &watches);
421 let Some(task) = tasks.iter().find(|task| Some(&task.id) == task_id.as_ref()) else {
422 return Ok(());
423 };
424 let mut inquiry = history_record(q, Some(task));
425 inquiry.run = task.runs.contains(&q.run).then(|| q.run.clone());
426 inquiry.archived = false;
427 inquiry.display = format!("{}\n\n{}", q.summary, q.detail);
428 inquiry.text = format!(
429 "{}\n\nAn owner response was recorded. Its effect is not yet confirmed; do not replay it.",
430 inquiry.display
431 );
432 inquiry.decision = Some(crate::task_decision::Decision::awaiting(q.summary.clone()));
433 outbox.enqueue(inquiry)?;
434 }
435 Err(error) => return Err(error),
436 }
437 outbox.update_decision(&q.id, |decision| {
438 let accepted =
439 decision.accept(&format!("decision: {}", q.resolution().unwrap_or_default()))?;
440 let changed = decision.source_answer_at != q.answered_at;
441 decision.source_answer_at = q.answered_at;
442 Ok(accepted || changed)
443 })?;
444 Ok(())
445}
446
447pub(crate) fn saved_reply_requires_confirmation(home: &Path, q: &Question) -> bool {
450 migrated_source(home, &q.id) && source_reply_needs_confirmation(home, q)
451}
452
453pub(crate) fn source_reply_needs_confirmation(home: &Path, q: &Question) -> bool {
454 if q.answer.is_none()
455 || (q.accepted_answer_at.is_some() && q.accepted_answer_at == q.answered_at)
456 {
457 return false;
458 }
459 let request = format!("decision: {}", q.resolution().unwrap_or_default());
460 !crate::task_inquiry::Outbox::at(home)
461 .get(&q.id)
462 .is_ok_and(|record| {
463 record.decision.as_ref().is_some_and(|decision| {
464 decision.request.as_deref() == Some(request.as_str())
465 && decision.source_answer_at.is_some()
466 && decision.source_answer_at == q.answered_at
467 })
468 })
469}
470
471#[derive(serde::Serialize)]
474pub struct MigrationIssue {
475 pub id: String,
477 pub reason: String,
479}
480
481pub fn migration_issues(home: &Path) -> Vec<MigrationIssue> {
484 let read = || -> Result<Vec<MigrationIssue>> {
485 let path = home.join("notifications/task-chat-migration-v1/state.json");
486 let bytes = match std::fs::read(path) {
487 Ok(bytes) => bytes,
488 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(vec![]),
489 Err(error) => return Err(error.into()),
490 };
491 let migration: Migration = serde_json::from_slice(&bytes)?;
492 anyhow::ensure!(migration.schema == 1, "unsupported inquiry migration");
493 Ok(migration
494 .errors
495 .into_iter()
496 .map(|(id, reason)| MigrationIssue { id, reason })
497 .collect())
498 };
499 let mut issues = read().unwrap_or_else(|error| {
500 vec![MigrationIssue {
501 id: "migration".into(),
502 reason: format!(
503 "Migration journal needs reconciliation: {error:#}. No approval was inferred."
504 ),
505 }]
506 });
507 if !issues.iter().any(|issue| issue.id == "migration") {
508 match std::fs::read_to_string(
509 home.join("notifications/task-chat-migration-v1/last-error.txt"),
510 ) {
511 Ok(reason) => issues.push(MigrationIssue {
512 id: "migration".into(),
513 reason,
514 }),
515 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
516 Err(error) => issues.push(MigrationIssue {
517 id: "migration".into(),
518 reason: format!("Migration diagnostic is unreadable: {error:#}"),
519 }),
520 }
521 }
522 issues
523}
524
525pub(crate) fn migration_pending(home: &Path) -> Result<std::collections::BTreeSet<String>> {
526 let path = home.join("notifications/task-chat-migration-v1/state.json");
527 let bytes = match std::fs::read(path) {
528 Ok(bytes) => bytes,
529 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Default::default()),
530 Err(error) => return Err(error.into()),
531 };
532 let migration: Migration = serde_json::from_slice(&bytes)?;
533 anyhow::ensure!(migration.schema == 1, "unsupported inquiry migration");
534 Ok(migration.pending.into_iter().collect())
535}
536
537const CLASSIFICATION_REVISION: u32 = 2;
538
539fn migrate_batch(
540 queue: &Queue,
541 talks: &Talks,
542 questions: &Questions,
543 home: &Path,
544 watches: &[crate::release_watch::WatchState],
545) -> Result<()> {
546 let dir = home.join("notifications/task-chat-migration-v1");
547 std::fs::create_dir_all(&dir)?;
548 let lock = std::fs::OpenOptions::new()
549 .create(true)
550 .truncate(false)
551 .write(true)
552 .open(dir.join("migration.lock"))?;
553 if let Err(error) = crate::pr_head::try_lock_file(&lock) {
554 if error.kind() == std::io::ErrorKind::WouldBlock || error.raw_os_error() == Some(33) {
555 return Ok(());
556 }
557 return Err(error.into());
558 }
559 let path = dir.join("state.json");
560 let mut migration: Migration = if path.exists() {
561 serde_json::from_slice(&std::fs::read(&path)?)?
562 } else {
563 Migration {
564 schema: 1,
565 classification_revision: 0,
566 pending: {
569 let mut ids = std::collections::BTreeSet::new();
570 match std::fs::read_dir(questions.root()) {
571 Ok(entries) => {
572 for entry in entries {
573 let path = entry?.path();
574 if path.extension().is_some_and(|ext| ext == "json") {
575 let id = path
576 .file_stem()
577 .and_then(|name| name.to_str())
578 .context("saved inquiry filename is not UTF-8")?;
579 ids.insert(id.to_owned());
580 }
581 }
582 }
583 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
584 Err(error) => return Err(error.into()),
585 }
586 ids.into_iter().collect()
587 },
588 sources: None,
589 errors: Default::default(),
590 }
591 };
592 let needs_boundary = migration.sources.is_none();
593 if needs_boundary {
594 let mut sources: std::collections::BTreeSet<_> =
595 migration.pending.iter().cloned().collect();
596 match std::fs::read_dir(questions.root()) {
597 Ok(entries) => {
598 for entry in entries {
599 let path = entry?.path();
600 if path
601 .extension()
602 .is_some_and(|extension| extension == "json")
603 {
604 let id = path
605 .file_stem()
606 .and_then(|stem| stem.to_str())
607 .context("saved inquiry filename is not UTF-8")?;
608 sources.insert(id.to_owned());
609 }
610 }
611 }
612 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
613 Err(error) => return Err(error.into()),
614 }
615 migration.pending = sources.iter().cloned().collect();
616 migration.sources = Some(sources);
617 }
618 anyhow::ensure!(migration.schema == 1, "unsupported task inquiry migration");
619 let save = |state: &Migration| -> Result<()> {
620 let temp = path.with_extension("tmp");
621 std::fs::write(&temp, serde_json::to_vec(state)?)?;
622 std::fs::rename(temp, &path)?;
623 Ok(())
624 };
625 let needs_correction = migration.classification_revision < CLASSIFICATION_REVISION;
626 if needs_correction {
627 let mut pending: std::collections::BTreeSet<_> =
630 migration.pending.iter().cloned().collect();
631 pending.extend(migration.sources.iter().flatten().cloned());
632 migration.pending = pending.into_iter().collect();
633 migration.classification_revision = CLASSIFICATION_REVISION;
634 }
635 if !path.exists() || needs_boundary || needs_correction {
638 save(&migration)?;
639 }
640 if migration.pending.is_empty() {
641 return Ok(());
642 }
643 let batch: Vec<_> = migration
644 .pending
645 .drain(..migration.pending.len().min(64))
646 .collect();
647 let tasks = queue.list();
648 let ownership = InquiryOwnership::from_tasks(&tasks);
649 for id in batch {
650 let result = (|| -> Result<()> {
651 let q = retire_finished_triage(queue, questions, home, &questions.read_history(&id)?)?;
652 if standalone_inquiry_in(home, &q, &ownership) {
653 if let Some(sources) = &mut migration.sources {
654 sources.remove(&id);
655 }
656 return Ok(());
657 }
658 if q.node == crate::bump::NOTICE_NODE && q.choices.is_empty() {
659 return Ok(());
660 }
661 let task = task_of_with_watches(&q, &tasks, watches)
662 .and_then(|id| tasks.iter().find(|task| task.id == id));
663 let outbox = crate::task_inquiry::Outbox::at(home);
664 let receipt = effect_receipt(home, queue, &q, task.map(|task| task.id.as_str()));
665 let mut record = history_record(&q, task);
666 let history = history_reason(home, &q);
667 let mut resolution = history
668 .as_ref()
669 .map(|(_, kind)| *kind)
670 .unwrap_or(HistoryResolution::Applied);
671 match (receipt, history) {
672 (Ok(Some(receipt)), _) => {
673 resolution = HistoryResolution::Applied;
674 let mut decision = crate::task_decision::Decision::awaiting(q.summary.clone());
675 decision.applied(&receipt)?;
676 record.decision = Some(decision);
677 }
678 (_, Some((reason, retire))) => {
679 let mut decision = crate::task_decision::Decision::awaiting(q.summary.clone());
680 if retire == HistoryResolution::Retired {
681 decision.retire(&reason)?;
682 } else {
683 decision.applied(&reason)?;
684 }
685 record.decision = Some(decision);
686 }
687 (outcome, None) if pending_intent(home, &q, task, watches) || outcome.is_err() => {
688 if q.status.open()
689 && let Some(task) = task
690 {
691 record = live_record(home, task, &q);
692 }
693 record.archived = false;
694 let mut decision = crate::task_decision::Decision::awaiting(q.summary.clone());
695 if let Err(error) = outcome {
696 decision
697 .fail(&format!("Source receipt needs reconciliation: {error:#}"))?;
698 } else if q.answer.is_some() {
699 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.")?;
700 }
701 record.decision = Some(decision);
702 record.text.push_str("\n\nImported history authorizes no operation. Saved replies require evidence reconciliation or explicit owner settlement; never replay them.");
703 if task.is_none() {
704 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());
705 }
706 }
707 _ => {}
708 }
709 let current = questions.read_history(&id)?;
710 anyhow::ensure!(
711 (current.status, ¤t.answer, current.answered_at)
712 == (q.status, &q.answer, q.answered_at),
713 "source changed while classifying saved history; retry with its current generation"
714 );
715 outbox.reclassify_history(record, resolution)?;
716 sync_effect_receipt_in(home, queue, &q, &ownership);
717 let imported = outbox.get(&q.id)?;
718 if imported.archived
719 || imported
720 .decision
721 .as_ref()
722 .is_some_and(|d| d.status == crate::task_decision::Status::Resolved)
723 {
724 return Ok(());
725 }
726 if q.status.open()
729 && let Some(task) = task
730 {
731 if q.routed_task.as_ref() != Some(&task.id) {
732 questions.update_in(&q.id, &ownership, |source| {
733 source.routed_task = Some(task.id.clone());
734 Ok(())
735 })?;
736 }
737 post_in(queue, talks, home, &task.id, &q, &ownership)?;
738 } else if task.is_some() {
739 outbox.deliver(queue, talks, &q.id)?;
742 }
743 Ok(())
744 })();
745 if let Err(error) = result {
746 tracing::warn!("legacy inquiry {id} import: {error:#}");
747 migration.errors.insert(
748 id.clone(),
749 format!(
750 "Saved inquiry needs reconciliation: {error:#}. Import executed no action."
751 ),
752 );
753 migration.pending.push(id);
754 } else {
755 migration.errors.remove(&id);
756 }
757 }
758 save(&migration)
759}
760
761fn history_reason(_home: &Path, q: &Question) -> Option<(String, HistoryResolution)> {
764 if q.answer.is_none() && q.status == crate::ask::QuestionStatus::Abandoned {
767 return Some(("Source abandoned: silence already settled as a hold; existing task holds and blocks are unchanged".into(), HistoryResolution::Retired));
768 }
769 None
770}
771
772enum TaskState {
777 Done,
778 Other,
779 Missing,
780 Unknown,
781}
782
783fn task_state(queue: &Queue, id: &str) -> Result<TaskState> {
784 match std::fs::read(queue.path_of(id)) {
785 Ok(bytes) => match serde_json::from_slice::<Task>(&bytes) {
786 Ok(task) if task.id == id => Ok(if task.status == crate::queue::TaskStatus::Done {
787 TaskState::Done
788 } else {
789 TaskState::Other
790 }),
791 _ => Ok(TaskState::Unknown),
792 },
793 Err(error) if error.kind() == std::io::ErrorKind::NotFound => match queue.resolve_id(id) {
794 Err(error) if error.to_string().starts_with("no task matches") => {
795 Ok(TaskState::Missing)
796 }
797 _ => Ok(TaskState::Unknown),
798 },
799 Err(error) => Err(error.into()),
800 }
801}
802
803fn retire_finished_triage(
804 queue: &Queue,
805 questions: &Questions,
806 home: &Path,
807 q: &Question,
808) -> Result<Question> {
809 if !matches!(
810 q.node.as_str(),
811 crate::triage::NODE | crate::triage::DEPS_NODE
812 ) || !q.status.open()
813 || q.answer.is_some()
814 {
815 return Ok(q.clone());
816 }
817 if !q.run_names_task()
821 || matches!(q.run.as_str(), "" | "." | "..")
822 || q.run.contains(['/', '\\'])
823 || q.routed_task.as_ref().is_some_and(|task| task != &q.run)
824 {
825 return Ok(q.clone());
826 }
827 let outbox = crate::task_inquiry::Outbox::at(home);
828 match outbox.get(&q.id) {
829 Ok(record)
830 if (!record.task.is_empty() && record.task != q.run)
831 || record
832 .decision
833 .as_ref()
834 .is_some_and(|d| d.request.is_some()) =>
835 {
836 return Ok(q.clone());
837 }
838 Err(error)
839 if !error
840 .downcast_ref::<std::io::Error>()
841 .is_some_and(|e| e.kind() == std::io::ErrorKind::NotFound) =>
842 {
843 return Err(error);
844 }
845 _ => {}
846 }
847 let reason = match task_state(queue, &q.run)? {
848 TaskState::Done => format!("task {} is done; nothing left to decide", q.run),
849 TaskState::Missing => format!(
850 "task {} is no longer in the queue; nothing left to decide",
851 q.run
852 ),
853 TaskState::Other | TaskState::Unknown => return Ok(q.clone()),
854 };
855 let mut preview = q.clone();
859 preview.abandon(&reason);
860 let mut record = history_record(&preview, None);
861 let mut decision = crate::task_decision::Decision::awaiting(preview.summary.clone());
862 decision.retire(&reason)?;
863 record.decision = Some(decision);
864 outbox.reclassify_history(record, HistoryResolution::Retired)?;
865 let source = questions
866 .update(&q.id, |source| {
867 if source.status.open()
868 && source.answer.is_none()
869 && source.run == q.run
870 && source.routed_task == q.routed_task
871 {
872 source.abandon(&reason);
873 }
874 Ok(())
875 })?
876 .0;
877 Ok(source)
878}
879
880fn pending_intent(
881 home: &Path,
882 q: &Question,
883 task: Option<&Task>,
884 watches: &[crate::release_watch::WatchState],
885) -> bool {
886 if q.status.open() || (q.answer.is_some() && awaits_decision(q)) {
887 return true;
888 }
889 if watches
890 .iter()
891 .any(|watch| watch.question.as_deref() == Some(q.id.as_str()))
892 {
893 return true;
894 }
895 let Some(task) = task else {
896 return q.answer.is_none() || awaits_decision(q);
897 };
898 if task.blocked_by.contains(&q.id) {
899 return true;
900 }
901 if task.status == crate::queue::TaskStatus::Done {
902 return false;
903 }
904 if q.run != task.id && task.runs.last() != Some(&q.run) {
905 return false;
906 }
907 if q.node == crate::github_text::ASK_NODE {
908 return crate::run::RunState::load_under(&q.run, home).is_ok_and(|run| {
909 run.github_text
910 .as_ref()
911 .is_some_and(|gate| gate.question.as_ref() == Some(&q.id))
912 && (run.pr_publication_pending || run.merge.as_ref().is_none_or(|out| !out.ok))
913 });
914 }
915 awaits_decision(q) || (q.routed_chat.is_some() && q.answer.is_none())
916}
917
918fn history_record(q: &Question, task: Option<&Task>) -> crate::task_inquiry::Inquiry {
919 let saved_reply = q.answer.as_ref().map(|answer| match answer {
920 crate::ask::Answer::Choice(text) | crate::ask::Answer::Text(text) => text.as_str(),
921 });
922 let display = format!(
923 "{}\n\n{}\n\nSaved status: {}\nSaved reply (history only): {}",
924 q.summary,
925 q.detail,
926 q.status.as_str(),
927 saved_reply.unwrap_or("none")
928 );
929 crate::task_inquiry::Inquiry {
930 schema: 1,
931 id: q.id.clone(),
932 task: task.map(|task| task.id.clone()).unwrap_or_default(),
933 run: (!q.run.is_empty() && !q.run_names_task()).then(|| q.run.clone()),
934 repo: task.map(|task| task.repo.clone()).unwrap_or_default(),
935 source: format!("{}:{}:{}", q.node, q.seat, q.run),
936 occurrence: None,
937 text: display.clone(),
938 display,
939 key: format!("question:{}", q.id),
940 evidence: None,
941 created_at: q.asked_at,
942 delivered_to: None,
943 decision: None,
944 delivery_error: None,
945 archived: true,
946 }
947}
948
949pub fn sweep(queue: &Queue, talks: &Talks, questions: &Questions, home: &Path) {
952 let tasks = queue.list();
953 let all: Vec<_> = questions
954 .list()
955 .into_iter()
956 .map(|q| {
957 retire_finished_triage(queue, questions, home, &q).unwrap_or_else(|error| {
958 tracing::warn!("triage {} retirement: {error:#}", q.id);
959 q
960 })
961 })
962 .collect();
963 let watches = crate::release_watch::states_for_questions(home, &all);
964 let migration_error = home.join("notifications/task-chat-migration-v1/last-error.txt");
965 if let Err(error) = migrate_batch(queue, talks, questions, home, &watches) {
966 tracing::warn!("legacy inquiry migration remains pending: {error:#}");
967 if let Err(save) = std::fs::write(
968 &migration_error,
969 format!("Migration remains pending: {error:#}. No approval was inferred."),
970 ) {
971 tracing::warn!("cannot persist migration failure: {save:#}");
972 }
973 } else if let Err(error) = std::fs::remove_file(&migration_error)
974 && error.kind() != std::io::ErrorKind::NotFound
975 {
976 tracing::warn!("cannot clear migration diagnostic: {error:#}");
977 }
978 let deferred = migration_pending(home).unwrap_or_else(|error| {
979 tracing::warn!("legacy delivery boundary is unreadable: {error:#}");
980 all.iter().map(|q| q.id.clone()).collect()
981 });
982 let outbox = crate::task_inquiry::Outbox::at(home);
983 let ownership = InquiryOwnership::from_tasks(&tasks);
984 for q in &all {
985 if deferred.contains(&q.id) {
986 continue;
987 }
988 if let Ok(record) = outbox.get(&q.id) {
989 if record.archived
992 || record.decision.as_ref().is_some_and(|decision| {
993 decision.status == crate::task_decision::Status::Resolved
994 })
995 {
996 continue;
997 }
998 if let Ok(_execution) = outbox.execution_claim(&q.id)
1001 && let Ok(_claim) = queue.claim(&record.task)
1002 {
1003 match questions.read_history(&q.id) {
1004 Ok(source) => sync_effect_receipt_in(home, queue, &source, &ownership),
1005 Err(error) => tracing::warn!("decision {} source history: {error:#}", q.id),
1006 }
1007 }
1008 if record.task.is_empty()
1011 && chat_routable(q)
1012 && let Some(task) = task_of_with_watches(q, &tasks, &watches)
1013 {
1014 if let Err(error) = post_in(queue, talks, home, &task, q, &ownership) {
1015 tracing::warn!("decision {} owner recovery: {error:#}", q.id);
1016 }
1017 }
1018 }
1019 }
1020 for q in all.into_iter().filter(|q| {
1021 q.status.open()
1022 && chat_routable(q)
1023 && !standalone_inquiry_in(home, q, &ownership)
1024 && !deferred.contains(&q.id)
1025 }) {
1026 if outbox.get(&q.id).is_ok_and(|record| {
1030 record.archived
1031 || record.decision.is_some_and(|decision| {
1032 decision.status == crate::task_decision::Status::Resolved
1033 })
1034 }) {
1035 continue;
1036 }
1037 let Some(task_id) = q
1038 .routed_task
1039 .clone()
1040 .or_else(|| task_of_with_watches(&q, &tasks, &watches))
1041 else {
1042 continue;
1043 };
1044 let needs_task = chat_routable(&q) && q.routed_task.as_deref() != Some(task_id.as_str());
1048 if q.routed_chat.is_some() && !needs_task {
1049 continue;
1050 }
1051 let result = (|| -> Result<()> {
1052 let q = if needs_task {
1053 questions
1054 .update(&q.id, |r| {
1055 if chat_routable(r) && r.routed_task.as_deref() != Some(task_id.as_str()) {
1056 r.routed_task = Some(task_id.clone());
1057 }
1058 Ok(())
1059 })?
1060 .0
1061 } else {
1062 q.clone()
1063 };
1064 if q.routed_chat.is_some() {
1066 return Ok(());
1067 }
1068 let chat = post_in(queue, talks, home, &task_id, &q, &ownership)?;
1069 questions.update_in(&q.id, &ownership, |r| {
1070 r.routed_chat = Some(chat.clone());
1071 if awaits_decision(r) {
1072 r.consult.get_or_insert_with(|| crate::ask::ChatConsult {
1076 talk: chat.clone(),
1077 at: jiff::Timestamp::now(),
1078 });
1079 } else if chat_routable(r) && r.merge_target.is_none() {
1080 r.abandon(format!("forwarded to task chat {chat}"));
1081 }
1082 Ok(())
1083 })?;
1084 Ok(())
1085 })();
1086 if let Err(e) = result {
1087 tracing::warn!("task decision {} delivery: {e:#}", q.id);
1088 }
1089 }
1090}
1091
1092pub(crate) fn source_retired(home: &Path, id: &str) -> bool {
1093 crate::task_inquiry::Outbox::at(home)
1094 .get(id)
1095 .is_ok_and(|record| {
1096 record.decision.is_some_and(|d| {
1097 d.status == crate::task_decision::Status::Resolved && d.source_retired
1098 })
1099 })
1100}
1101
1102pub(crate) fn sync_effect_receipt(home: &Path, queue: &Queue, q: &Question) {
1105 sync_effect_receipt_in(home, queue, q, &InquiryOwnership::default())
1106}
1107
1108fn sync_effect_receipt_in(home: &Path, queue: &Queue, q: &Question, ownership: &InquiryOwnership) {
1109 if q.answer.is_some()
1110 && q.accepted_answer_at.is_some()
1111 && q.accepted_answer_at == q.answered_at
1112 && let Err(error) = accept_fresh_reply(home, q, ownership)
1113 {
1114 tracing::warn!("decision {} acceptance: {error:#}", q.id);
1115 return;
1116 }
1117 let outbox = crate::task_inquiry::Outbox::at(home);
1118 let Ok(record) = outbox.get(&q.id) else {
1119 return;
1120 };
1121 let Some(decision) = record.decision else {
1122 return;
1123 };
1124 if decision.status == crate::task_decision::Status::Resolved {
1125 return;
1126 }
1127 if let Some(request) = &decision.request
1128 && (q
1129 .resolution()
1130 .is_none_or(|reply| request != &format!("decision: {reply}"))
1131 || decision
1132 .source_answer_at
1133 .is_some_and(|at| Some(at) != q.answered_at))
1134 {
1135 return;
1136 }
1137 let result = match effect_receipt(home, queue, q, Some(&record.task)) {
1138 Ok(Some(receipt)) => outbox.update_decision(&q.id, |d| d.applied(&receipt)),
1139 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.")),
1140 Ok(None) => Ok(()),
1141 Err(_) if decision.retry_safe => Ok(()),
1142 Err(error) => outbox.update_decision(&q.id, |d| d.fail(&format!("Source receipt needs reconciliation: {error:#}"))),
1143 };
1144 if let Err(error) = result {
1145 tracing::warn!("decision {} projection: {error:#}", q.id);
1146 }
1147}
1148
1149pub(crate) fn effect_receipt(
1150 home: &Path,
1151 queue: &Queue,
1152 q: &Question,
1153 task: Option<&str>,
1154) -> Result<Option<String>> {
1155 if let Some(task) = task.and_then(|id| queue.get(id).ok())
1156 && crate::repair_budget::reconcile::superseded_question(&task, q)
1157 {
1158 return Ok(Some(format!(
1159 "task {}: unanswered dependency question {} superseded by explicit repair receipt reconciliation; no generic resume applied",
1160 task.id, q.id
1161 )));
1162 }
1163 if q.resolution().is_none() {
1164 return Ok(None);
1165 }
1166
1167 if q.node == crate::land::APPROVAL_NODE
1168 && q.resolution().as_deref() == Some(crate::land::REPAIR)
1169 {
1170 let run = crate::run::RunState::load_under(&q.run, home)?;
1171 let Some(repair) = run.merge_repairs.iter().find(|r| r.question == q.id) else {
1172 return Ok(None);
1173 };
1174 anyhow::ensure!(
1175 q.merge_target
1176 .as_ref()
1177 .is_none_or(|target| { target.pr == repair.pr && target.head == repair.head }),
1178 "repair receipt targets a different PR or head"
1179 );
1180 return match repair.phase {
1181 crate::run::MergeRepairPhase::Complete => Ok(Some(format!(
1182 "run {}: repair and re-review {} completed for {} at {}",
1183 q.run, q.id, repair.pr, repair.head
1184 ))),
1185 crate::run::MergeRepairPhase::Failed => anyhow::bail!(
1186 "repair {} failed: {}",
1187 q.id,
1188 repair
1189 .failure
1190 .as_deref()
1191 .unwrap_or("inspect the run's repair evidence before retrying")
1192 ),
1193 _ => Ok(None),
1196 };
1197 }
1198
1199 if q.node == crate::land::APPROVAL_NODE
1200 && q.resolution().as_deref() == Some(crate::merge_decision::WITHDRAW)
1201 {
1202 let run = crate::run::RunState::load_under(&q.run, home)?;
1203 if let Some(receipt) = &run.merge_decision
1204 && receipt.question == q.id
1205 && receipt.choice == crate::merge_decision::WITHDRAW
1206 && receipt.closed
1207 && run.status == crate::run::RunStatus::Superseded
1208 && run.pr.as_ref().is_some_and(|pr| {
1209 pr.url == receipt.target.pr && pr.state.eq_ignore_ascii_case("closed")
1210 })
1211 && q.merge_target
1212 .as_ref()
1213 .is_none_or(|target| target == &receipt.target)
1214 {
1215 return Ok(Some(format!(
1216 "run {}: withdrawal {} confirmed PR closure and retired execution",
1217 q.run, q.id
1218 )));
1219 }
1220 return Ok(None);
1223 }
1224
1225 if crate::release_watch::quiet_effect_applied(home, q)? {
1226 return Ok(Some(format!(
1227 "release watch {}: owner choice applied",
1228 q.id
1229 )));
1230 }
1231 if matches!(
1232 q.node.as_str(),
1233 crate::triage::NODE | crate::triage::DEPS_NODE
1234 ) && let Some(id) = task
1235 .filter(|id| !id.is_empty())
1236 .or_else(|| (!q.run.is_empty()).then_some(q.run.as_str()))
1237 && queue.triage_discard_applied(id, &q.id)?
1238 {
1239 return Ok(Some(format!(
1240 "task {id}: triage discard {} committed",
1241 q.id
1242 )));
1243 }
1244
1245 let task = task
1246 .filter(|id| !id.is_empty())
1247 .map(|id| queue.get(id))
1248 .transpose()?;
1249 if q.node == crate::land::APPROVAL_NODE
1250 && let Some(choice) = q.resolution()
1251 && (choice.eq_ignore_ascii_case(crate::land::HOLD)
1252 || crate::merge_decision::selected_agent(&choice).is_some())
1253 {
1254 if choice.eq_ignore_ascii_case(crate::land::HOLD)
1257 && let Some(task) = &task
1258 && task.decision_effects.get(&q.id) == Some(&format!("decision: {choice}"))
1259 {
1260 return Ok(Some(format!(
1261 "task {}: landing hold {} committed",
1262 task.id, q.id
1263 )));
1264 }
1265 let run = crate::run::RunState::load_under(&q.run, home)?;
1266 let Some(receipt) = run.merge_decision.as_ref().filter(|receipt| {
1267 receipt.question == q.id
1268 && receipt.choice == choice
1269 && q.merge_target
1270 .as_ref()
1271 .is_none_or(|target| target == &receipt.target)
1272 }) else {
1273 return Ok(None);
1274 };
1275 if choice.eq_ignore_ascii_case(crate::land::HOLD) {
1276 return Ok(task
1277 .filter(|task| task.action_applied(&q.id))
1278 .map(|task| format!("task {}: landing hold {} committed", task.id, q.id)));
1279 }
1280 if receipt.closed
1283 && run.status == crate::run::RunStatus::Superseded
1284 && run.pr.as_ref().is_some_and(|pr| {
1285 pr.url == receipt.target.pr && pr.state.eq_ignore_ascii_case("closed")
1286 })
1287 && let Some(next) = &receipt.replacement_run
1288 && let Some(task) = &task
1289 && task.runs.contains(next)
1290 {
1291 let replacement = crate::run::RunState::load_under(next, home)?;
1292 if replacement.repo == task.repo
1293 && replacement.replaces.as_ref().is_some_and(|r| {
1294 r.question == q.id
1295 && r.run == q.run
1296 && r.pr == receipt.target.pr
1297 && Some(r.agent.as_str()) == crate::merge_decision::selected_agent(&choice)
1298 })
1299 && replacement.passes.iter().any(|pass| pass.task_entry)
1300 {
1301 return Ok(Some(format!(
1302 "run {}: PR closure confirmed; replacement {next} started for {}",
1303 q.run, q.id
1304 )));
1305 }
1306 }
1307 return Ok(None);
1308 }
1309 if matches!(
1310 q.chosen_action(),
1311 Some(crate::ask::ChoiceAction::RecoverBase { .. })
1312 ) {
1313 return crate::base_recovery_control::effect_receipt(
1314 home,
1315 task.as_ref()
1316 .context("base recovery decision has no owning task")?,
1317 q,
1318 );
1319 }
1320 if let Some(action) = q.chosen_action().filter(|a| a.maintenance()) {
1321 let path = home.join("choice-actions").join(format!("{}.json", q.id));
1322 let bytes = match std::fs::read(path) {
1323 Ok(bytes) => bytes,
1324 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
1325 Err(error) => return Err(error.into()),
1326 };
1327 let value: serde_json::Value = serde_json::from_slice(&bytes)?;
1328 anyhow::ensure!(
1329 value["action"] == serde_json::to_value(action)?,
1330 "maintenance receipt targets a different action"
1331 );
1332 anyhow::ensure!(
1333 value["status"] == "applied",
1334 "maintenance outcome is not confirmed: {}",
1335 value["status"]
1336 );
1337 return Ok(Some(format!("choice-actions/{}.json: applied", q.id)));
1338 }
1339 if q.node == crate::triage::NODE || q.node == crate::triage::DEPS_NODE {
1340 if let Some(task) = &task
1341 && let Some(evidence) = task.decision_effects.get(&q.id)
1342 {
1343 if evidence.starts_with("repair-receipt-blocked:") {
1344 anyhow::ensure!(
1345 evidence == &crate::repair_budget::reconcile::blocked_resume(q)?,
1346 "blocked resume source changed"
1347 );
1348 return Ok(Some(format!(
1349 "task {}: generic resume {} consumed without release; retained repair receipt requires explicit reconcile-repair-grant",
1350 task.id, q.id
1351 )));
1352 }
1353 let (source, _, _, application): (
1354 String,
1355 Option<jiff::Timestamp>,
1356 String,
1357 crate::queue::Resumption,
1358 ) = serde_json::from_str(evidence)
1359 .context("triage application receipt is unreadable")?;
1360 anyhow::ensure!(
1361 source == crate::repair_budget::reconcile::source(q)?
1362 && task
1363 .resumption
1364 .iter()
1365 .chain(&task.resumption_history)
1366 .any(|r| crate::repair_budget::reconcile::application_identity(r)
1367 == application),
1368 "triage source or application evidence changed"
1369 );
1370 }
1371 return Ok(task.filter(|task| task.triage_applied(&q.id)).map(|_| {
1372 format!(
1373 "task triage {} settled by durable application/supersession evidence",
1374 q.id
1375 )
1376 }));
1377 }
1378 if let Some(task) = &task
1379 && task.action_applied(&q.id)
1380 {
1381 if matches!(
1382 q.chosen_action(),
1383 Some(
1384 crate::ask::ChoiceAction::Done
1385 | crate::ask::ChoiceAction::Hold
1386 | crate::ask::ChoiceAction::Requeue
1387 )
1388 ) && task.decision_effects.get(&q.id)
1389 == Some(&format!(
1390 "decision: {}",
1391 q.resolution().expect("answered action")
1392 ))
1393 {
1394 return Ok(Some(format!(
1395 "task {}: exact choice effect {} committed",
1396 task.id, q.id
1397 )));
1398 }
1399 let applied = match q.chosen_action() {
1400 Some(crate::ask::ChoiceAction::Resume { run }) => {
1401 crate::chat_control::resume_started(home, task, &q.id, run)?
1402 }
1403 Some(crate::ask::ChoiceAction::Done) => task.status == crate::queue::TaskStatus::Done,
1404 Some(crate::ask::ChoiceAction::Hold) => {
1405 task.status == crate::queue::TaskStatus::Held
1406 && task.hold_reason.as_ref() == Some(&q.summary)
1407 }
1408 Some(crate::ask::ChoiceAction::Requeue) => task.fresh_start,
1409 _ => false,
1410 };
1411 if applied {
1412 return Ok(Some(format!(
1413 "task {}: intended effect {} confirmed",
1414 task.id, q.id
1415 )));
1416 }
1417 }
1418 if q.node == crate::github_text::ASK_NODE {
1419 let run = crate::run::RunState::load_under(&q.run, home)?;
1420 if let Some(gate) = &run.github_text
1421 && let Some(next) = &gate.question
1422 && next != &q.id
1423 && crate::ask::Questions::at(home.join("questions"))
1424 .get(next)
1425 .is_ok_and(|successor| {
1426 successor.run == q.run
1427 && successor.node == q.node
1428 && successor.asked_at >= q.asked_at
1429 })
1430 {
1431 return Ok(Some(format!(
1432 "publication inquiry {} explicitly superseded by active source gate {next}; original reply will not be consumed",
1433 q.id
1434 )));
1435 }
1436 if let Some(gate) = &run.github_text
1437 && let Some(receipt) = &gate.publication
1438 {
1439 let expected = match crate::github_text::read_reply(q) {
1440 crate::github_text::Reply::Original => crate::run::GithubTextChoice::Original,
1441 crate::github_text::Reply::Rewrite => crate::run::GithubTextChoice::Rewrite,
1442 crate::github_text::Reply::Title(_) => crate::run::GithubTextChoice::MyTitle,
1443 crate::github_text::Reply::Fallback => crate::run::GithubTextChoice::Fallback,
1444 };
1445 if q.resolution().is_some()
1446 && receipt.inquiry == q.id
1447 && receipt.fingerprint == gate.fingerprint
1448 {
1449 anyhow::ensure!(
1450 receipt.choice == expected,
1451 "publication applied a different payload than the saved reply"
1452 );
1453 return Ok(Some(format!(
1454 "publication {} for {}: {:?} applied",
1455 receipt.url, q.id, receipt.choice
1456 )));
1457 }
1458 }
1459 }
1460 if q.node == crate::land::APPROVAL_NODE
1461 && q.resolution().as_deref() == Some(crate::merge_decision::DISMISS)
1462 {
1463 let run = crate::run::RunState::load_under(&q.run, home)?;
1466 let stopped = run
1467 .merge_decision
1468 .as_ref()
1469 .is_some_and(|d| d.question == q.id && d.choice == crate::merge_decision::DISMISS);
1470 let settled = queue.list().iter().all(|task| {
1473 task.runs.last() != Some(&q.run)
1474 || task.status == crate::queue::TaskStatus::Done
1475 || task.action_applied(&q.id)
1476 });
1477 if stopped && settled {
1478 return Ok(Some(format!(
1479 "run {}: obsolete approval {} dismissed; PR unchanged",
1480 q.run, q.id
1481 )));
1482 }
1483 }
1484 if q.node == crate::land::APPROVAL_NODE
1485 && let Some(target) = &q.merge_target
1486 && q.resolution().as_deref() == Some(crate::land::APPROVE)
1487 {
1488 let run = crate::run::RunState::load_under(&q.run, home)?;
1489 if run
1490 .land_approval
1491 .as_ref()
1492 .is_some_and(|binding| binding.question == q.id && binding.head == target.head)
1493 && run.pr_merged_head.as_deref() == Some(target.head.as_str())
1494 && run.pr.as_ref().is_some_and(|pr| {
1495 pr.url == target.pr
1496 && pr.state.eq_ignore_ascii_case("merged")
1497 && run.merge.as_ref().is_some_and(|merge| {
1498 merge.ok
1499 && !merge.empty
1500 && merge.mode == crate::config::MergeMode::Pr
1501 && merge
1502 .detail
1503 .starts_with(&format!("gh pr merge {} ", pr.number))
1504 && merge
1505 .detail
1506 .ends_with(&format!(" --match-head-commit {}", target.head))
1507 })
1508 })
1509 {
1510 return Ok(Some(format!(
1511 "run {}: merged {} at {}",
1512 q.run, target.pr, target.head
1513 )));
1514 }
1515 }
1516 Ok(None)
1517}
1518
1519pub fn approval_offered(talk: &talk::Talk, q: &Question) -> bool {
1522 talk.status.open()
1523 && q.status.open()
1524 && q.merge_target.is_some()
1525 && q.routed_chat.as_deref() == Some(talk.id.as_str())
1526 && talk.notified.contains(&format!("question:{}", q.id))
1527 && talk.turns.iter().any(|turn| {
1528 talk::sender(turn, None) == talk::Sender::Persona && turn.body.contains(&q.id)
1529 })
1530}
1531
1532fn task_of_with_watches(
1533 q: &Question,
1534 tasks: &[Task],
1535 watches: &[crate::release_watch::WatchState],
1536) -> Option<String> {
1537 let mut ids = std::collections::BTreeSet::new();
1538 if let Some(id) = task_of(q, tasks) {
1539 ids.insert(id);
1540 }
1541 for reference in crate::consult::question_task_refs(q, watches) {
1542 for task in tasks.iter().filter(|t| match reference {
1543 crate::consult::QuestionTaskRef::Task(id) => t.id == id,
1544 crate::consult::QuestionTaskRef::Run(id) => t.runs.iter().any(|r| r == id),
1545 }) {
1546 ids.insert(task.id.clone());
1547 }
1548 }
1549 if ids.len() == 1 {
1550 ids.pop_first()
1551 } else {
1552 None
1553 }
1554}
1555
1556#[cfg(test)]
1557mod tests {
1558 use super::*;
1559 use crate::ask::{Answer, QuestionStatus};
1560
1561 #[tokio::test]
1562 async fn release_2029_stays_answered_across_partial_import_and_restart() {
1563 use crate::{task_decision::Status, task_inquiry::Outbox};
1564 let home = tempfile::tempdir().unwrap();
1565 let home = home.path();
1566 let questions = Questions::at(home.join("questions"));
1567 let queue = Queue::at(home.join("queue"));
1568 let talks = Talks::at(home.join("talks"));
1569 let outbox = Outbox::at(home);
1570 let mut saved = Vec::new();
1571 for index in 0..66 {
1572 let mut q = Question::new(
1573 String::new(),
1574 crate::bump::NOTICE_NODE.into(),
1575 "release-watch".into(),
1576 "Release approval".into(),
1577 "Saved reviewed head".into(),
1578 vec!["merge".into(), "hold".into()],
1579 );
1580 q.id = format!(
1581 "20261109-014940-871849981cd969b1-0000000000000000-{}",
1582 1964 + index
1583 );
1584 q.merge_target = Some(crate::merge_decision::Target {
1585 pr: "https://example.test/mebae/pull/100".into(),
1586 head: "4d5a46f99a678608d2b883498d8bebd9399c0261".into(),
1587 language: "en".into(),
1588 });
1589 q.answer(Answer::Choice(
1590 if index == 0 { "hold" } else { "merge" }.into(),
1591 ))
1592 .unwrap();
1593 q.answered_at = Some("2026-11-08T17:03:30.66862Z".parse().unwrap());
1594 q.answer_delivered = true;
1595 questions.put(&mut q).unwrap();
1596 saved.push(q);
1597 }
1598 let receipts = home.join("release-watch-receipts");
1600 std::fs::create_dir_all(&receipts).unwrap();
1601 let receipt = crate::release_watch::WatchState {
1602 applied: vec![saved[0].id.clone()],
1603 ..Default::default()
1604 };
1605 std::fs::write(
1606 receipts.join(format!("{}.json", saved[0].id)),
1607 serde_json::to_vec(&receipt).unwrap(),
1608 )
1609 .unwrap();
1610 outbox.enqueue(history_record(&saved[1], None)).unwrap();
1613 let dir = home.join("notifications/task-chat-migration-v1");
1614 std::fs::create_dir_all(&dir).unwrap();
1615 std::fs::write(
1616 dir.join("state.json"),
1617 serde_json::to_vec(&serde_json::json!({
1618 "schema": 1, "sources": saved.iter().map(|q| &q.id).collect::<Vec<_>>(),
1619 "pending": saved[64..].iter().map(|q| &q.id).collect::<Vec<_>>()
1620 }))
1621 .unwrap(),
1622 )
1623 .unwrap();
1624 let source = &saved[65];
1625 assert!(source.id.ends_with("2029"));
1626 let bytes = std::fs::read(questions.path_of(&source.id)).unwrap();
1627 let assert_history = || {
1628 let read = questions.get(&source.id).unwrap();
1629 assert_eq!(read.status, QuestionStatus::Answered);
1630 assert_eq!(read.resolution().as_deref(), Some("merge"));
1631 assert_eq!(read.answered_at, source.answered_at);
1632 assert_eq!(
1633 questions.list().iter().filter(|q| q.status.open()).count(),
1634 0
1635 );
1636 assert!(
1637 questions
1638 .get_for_effects(&source.id)
1639 .unwrap()
1640 .resolution()
1641 .is_none()
1642 );
1643 assert!(
1644 questions
1645 .update(&source.id, |q| q.answer(Answer::Choice("merge".into())))
1646 .is_err()
1647 );
1648 let mut operational = questions.get_for_effects(&source.id).unwrap();
1649 operational.abandon("old deadline");
1650 assert!(
1651 questions.put(&mut operational).is_err(),
1652 "quarantine must not activate a default on timeout"
1653 );
1654 assert_eq!(std::fs::read(questions.path_of(&source.id)).unwrap(), bytes);
1655 };
1656 assert_history();
1657 assert_eq!(
1658 questions
1659 .abandon_for_run("", "retired source owner")
1660 .unwrap(),
1661 0
1662 );
1663 assert_history();
1664 let mut waiting = source.clone();
1665 assert!(matches!(
1666 crate::ask::resume_wait(&mut waiting, &questions, std::time::Duration::ZERO)
1667 .await
1668 .unwrap(),
1669 crate::ask::Wait::Pending
1670 ));
1671 assert_history();
1672 sweep(&queue, &talks, &questions, home);
1673 assert_history();
1674 assert_eq!(migration_pending(home).unwrap().len(), 2);
1675 assert!(
1676 outbox.get(&source.id).is_err(),
1677 "2029 is beyond the first batch"
1678 );
1679 assert_eq!(
1680 outbox.get(&saved[0].id).unwrap().decision.unwrap().status,
1681 Status::Resolved
1682 );
1683 let repaired = outbox.get(&saved[1].id).unwrap();
1684 assert!(!repaired.archived);
1685 assert_eq!(repaired.decision.unwrap().status, Status::RetryNeeded);
1686 for _ in 0..2 {
1688 sweep(
1689 &Queue::at(home.join("queue")),
1690 &Talks::at(home.join("talks")),
1691 &Questions::at(home.join("questions")),
1692 home,
1693 );
1694 assert_history();
1695 }
1696 assert!(migration_pending(home).unwrap().is_empty());
1697 let imported = outbox.get(&source.id).unwrap();
1698 assert!(!imported.archived);
1699 assert!(imported.task.is_empty());
1700 assert!(
1701 imported
1702 .delivery_error
1703 .unwrap()
1704 .contains("missing or ambiguous")
1705 );
1706 let decision = imported.decision.unwrap();
1707 assert_eq!(decision.status, Status::RetryNeeded);
1708 assert!(decision.request.is_none());
1709 assert!(decision.source_answer_at.is_none());
1710 assert!(queue.list().is_empty());
1711 assert!(talks.list().is_empty());
1712 let mut later = saved[1].clone();
1713 later.id = "outside-boundary".into();
1714 questions.put(&mut later).unwrap();
1715 sweep(&queue, &talks, &questions, home);
1716 assert!(
1717 outbox.get(&later.id).is_err(),
1718 "correction must not expand its boundary"
1719 );
1720 }
1721
1722 #[test]
1723 fn migration_revision_retires_proven_and_abandoned_history() {
1724 use crate::{
1725 ask::Answer,
1726 queue::{Source, TaskStatus},
1727 run::{MergeOutcome, RunState, RunStatus},
1728 task_decision::{Decision, Status},
1729 task_inquiry::Outbox,
1730 };
1731 let temp = tempfile::tempdir().unwrap();
1732 let home = temp.path();
1733 let queue = Queue::at(home.join("queue"));
1734 let questions = Questions::at(home.join("questions"));
1735 let talks = Talks::at(home.join("talks"));
1736 let outbox = Outbox::at(home);
1737 let mut run = RunState::new(
1738 home.into(),
1739 "main".into(),
1740 "base".into(),
1741 "work".into(),
1742 Config::default(),
1743 );
1744 run.reserve_under(home).unwrap();
1745 run.status = RunStatus::Merged;
1746 run.merge = Some(MergeOutcome {
1747 mode: crate::config::MergeMode::Local,
1748 ok: true,
1749 empty: false,
1750 detail: String::new(),
1751 });
1752 run.save_under(home).unwrap();
1753 let mut task = Task::new("work".into(), "work".into(), home.into(), Source::Human);
1754 task.status = TaskStatus::Done;
1755 task.runs.push(run.id.clone());
1756 queue.put(&mut task).unwrap();
1757 let mut sources = Vec::new();
1758 for (node, run_id, answered) in [
1759 (crate::land::APPROVAL_NODE, run.id.as_str(), true),
1760 (crate::land::APPROVAL_NODE, "unproven", true),
1761 (crate::conduct::NODE, task.id.as_str(), false),
1762 (crate::triage::NODE, task.id.as_str(), false),
1763 ] {
1764 let mut q = Question::new(
1765 run_id.into(),
1766 node.into(),
1767 "seat".into(),
1768 "Decision".into(),
1769 String::new(),
1770 vec!["yes".into()],
1771 );
1772 if answered {
1773 q.answer(Answer::Choice("yes".into())).unwrap();
1774 } else if node == crate::conduct::NODE {
1775 q.abandon("expired; held");
1776 }
1777 questions.put(&mut q).unwrap();
1778 sources.push(q);
1779 }
1780 for q in &sources {
1782 let mut record = history_record(q, None);
1783 record.archived = false;
1784 let mut decision = Decision::awaiting(q.summary.clone());
1785 decision
1786 .fail("Saved reply has no confirmed effect receipt")
1787 .unwrap();
1788 record.decision = Some(decision);
1789 outbox.enqueue(record).unwrap();
1790 }
1791 let mut settled = sources[0].clone();
1793 settled.id = "settled-history".into();
1794 questions.put(&mut settled).unwrap();
1795 let mut record = history_record(&settled, None);
1796 let mut decision = Decision::awaiting(settled.summary.clone());
1797 decision.settle("owner settled after inspection").unwrap();
1798 record.decision = Some(decision);
1799 record.archived = false;
1800 outbox.enqueue(record).unwrap();
1801 let settled_before = outbox.get(&settled.id).unwrap();
1802 sources.push(settled);
1803 let dir = home.join("notifications/task-chat-migration-v1");
1804 std::fs::create_dir_all(&dir).unwrap();
1805 std::fs::write(
1806 dir.join("state.json"),
1807 serde_json::to_vec(&serde_json::json!({
1808 "schema": 1, "classification_revision": 1, "pending": [],
1809 "sources": sources.iter().map(|q| &q.id).collect::<Vec<_>>()
1810 }))
1811 .unwrap(),
1812 )
1813 .unwrap();
1814 for _ in 0..2 {
1815 sweep(&queue, &talks, &questions, home);
1816 }
1817 for index in [2, 3] {
1818 let record = outbox.get(&sources[index].id).unwrap();
1819 assert!(record.archived);
1820 let decision = record.decision.unwrap();
1821 assert_eq!(decision.status, Status::Resolved);
1822 assert!(decision.error.is_none());
1823 assert!(!decision.legacy_settled);
1824 }
1825 assert_eq!(
1826 outbox.get(&sources[1].id).unwrap().decision.unwrap().status,
1827 Status::RetryNeeded
1828 );
1829 assert_eq!(
1830 outbox.get(&sources[0].id).unwrap().decision.unwrap().status,
1831 Status::RetryNeeded
1832 );
1833 let triage = questions.read_history(&sources[3].id).unwrap();
1834 assert_eq!(triage.status, crate::ask::QuestionStatus::Abandoned);
1835 assert!(triage.detail.contains("nothing left to decide"));
1836 assert_eq!(outbox.get(&sources[4].id).unwrap(), settled_before);
1837 run.merge.as_mut().unwrap().empty = true;
1839 run.save_under(home).unwrap();
1840 assert!(history_reason(home, &sources[0]).is_none());
1841 run.merge.as_mut().unwrap().empty = false;
1842 run.merge.as_mut().unwrap().mode = crate::config::MergeMode::Pr;
1843 run.pr = Some(crate::run::PrRecord {
1844 url: "https://example.test/project/repo/pull/1".into(),
1845 number: 1,
1846 state: "open".into(),
1847 checks: "green".into(),
1848 round: 1,
1849 rounds: 1,
1850 red_at_merge: vec![],
1851 });
1852 run.save_under(home).unwrap();
1853 assert!(
1854 history_reason(home, &sources[0]).is_none(),
1855 "publication alone is insufficient"
1856 );
1857 run.pr.as_mut().unwrap().state = "merged".into();
1858 run.pr_merged_head = Some("merged-head".into());
1859 run.save_under(home).unwrap();
1860 let mut bound = sources[0].clone();
1861 bound.merge_target = Some(crate::merge_decision::Target {
1862 pr: run.pr.as_ref().unwrap().url.clone(),
1863 head: "merged-head".into(),
1864 language: "en".into(),
1865 });
1866 assert!(history_reason(home, &bound).is_none());
1867 bound.merge_target.as_mut().unwrap().head = "other-head".into();
1868 assert!(history_reason(home, &bound).is_none());
1869 }
1870
1871 #[test]
1872 fn triage_retirement_preserves_ambiguous_ownership_and_forwarded_discussion() {
1873 let temp = tempfile::tempdir().unwrap();
1874 let home = temp.path();
1875 let queue = Queue::at(home.join("queue"));
1876 let questions = Questions::at(home.join("questions"));
1877 let mut q = Question::new(
1878 "missing-task".into(),
1879 crate::triage::NODE.into(),
1880 "triage".into(),
1881 "Decide".into(),
1882 String::new(),
1883 vec![],
1884 );
1885 q.routed_task = Some("another-task".into());
1886 questions.put(&mut q).unwrap();
1887 assert!(
1888 retire_finished_triage(&queue, &questions, home, &q)
1889 .unwrap()
1890 .status
1891 .open()
1892 );
1893 q = questions
1894 .update(&q.id, |q| {
1895 q.routed_task = None;
1896 Ok(())
1897 })
1898 .unwrap()
1899 .0;
1900 assert_eq!(
1901 retire_finished_triage(&queue, &questions, home, &q)
1902 .unwrap()
1903 .status,
1904 crate::ask::QuestionStatus::Abandoned
1905 );
1906 assert!(matches!(
1908 task_state(&queue, "abc").unwrap(),
1909 TaskState::Missing
1910 ));
1911 std::fs::create_dir_all(home.join("queue")).unwrap();
1912 std::fs::write(home.join("queue").join("abcdef.json"), "{}").unwrap();
1913 assert!(matches!(
1914 task_state(&queue, "abc").unwrap(),
1915 TaskState::Unknown
1916 ));
1917 let mut forwarded = Question::new(
1918 "task".into(),
1919 "implement".into(),
1920 "seat".into(),
1921 "Discuss".into(),
1922 String::new(),
1923 vec![],
1924 );
1925 forwarded.routed_chat = Some("chat".into());
1926 forwarded.abandon("forwarded to task chat");
1927 assert!(history_reason(home, &forwarded).is_some());
1928 }
1929
1930 #[test]
1931 fn release_watch_history_requires_readable_existing_store() {
1932 use crate::ask::Answer;
1933 let temp = tempfile::tempdir().unwrap();
1934 let home = temp.path();
1935 let mut q = Question::new(
1936 "run".into(),
1937 crate::bump::NOTICE_NODE.into(),
1938 "release-watch".into(),
1939 "Release".into(),
1940 String::new(),
1941 vec!["merge".into()],
1942 );
1943 q.merge_target = Some(crate::merge_decision::Target {
1944 pr: "https://example.test/project/repo/pull/1".into(),
1945 head: "head".into(),
1946 language: "en".into(),
1947 });
1948 q.answer(Answer::Choice("merge".into())).unwrap();
1949 assert!(history_reason(home, &q).is_none());
1950 let dir = home.join("release-watch");
1951 std::fs::create_dir(&dir).unwrap();
1952 assert!(history_reason(home, &q).is_none());
1953 let active = dir.join(format!("{}.json", crate::notices::id_of("project/repo#1")));
1954 std::fs::write(&active, b"{}").unwrap();
1956 assert!(history_reason(home, &q).is_none());
1957 std::fs::remove_file(active).unwrap();
1958 std::fs::write(dir.join("broken.json"), "invalid").unwrap();
1959 assert!(history_reason(home, &q).is_none());
1960 std::fs::write(
1961 dir.join("broken.json"),
1962 serde_json::to_vec(&crate::release_watch::WatchState {
1963 question: Some(q.id.clone()),
1964 ..Default::default()
1965 })
1966 .unwrap(),
1967 )
1968 .unwrap();
1969 assert!(history_reason(home, &q).is_none());
1970 }
1971
1972 #[test]
1973 fn history_correction_preserves_accepted_and_completed_decisions() {
1974 let home = tempfile::tempdir().unwrap();
1975 let outbox = crate::task_inquiry::Outbox::at(home.path());
1976 for completed in [false, true] {
1977 let q = Question::new(
1978 String::new(),
1979 crate::bump::NOTICE_NODE.into(),
1980 "release-watch".into(),
1981 "Saved release".into(),
1982 String::new(),
1983 vec!["hold".into()],
1984 );
1985 let mut record = history_record(&q, None);
1986 record.archived = false;
1987 record.decision = Some(crate::task_decision::Decision::awaiting(q.summary.clone()));
1988 outbox.enqueue(record).unwrap();
1989 outbox
1990 .update_decision(&q.id, |d| {
1991 if completed {
1992 d.applied("explicit durable effect receipt")
1993 } else {
1994 d.accept("decision: hold")
1995 }
1996 })
1997 .unwrap();
1998 let before = outbox.get(&q.id).unwrap();
1999 outbox
2000 .reclassify_history(history_record(&q, None), HistoryResolution::Retired)
2001 .unwrap();
2002 assert_eq!(outbox.get(&q.id).unwrap(), before);
2003 }
2004 }
2005
2006 #[test]
2007 fn routed_merge_accepts_direct_answers_and_checks_optional_button_binding() {
2008 let mut q = Question::new(
2009 "run".into(),
2010 crate::land::APPROVAL_NODE.into(),
2011 "land".into(),
2012 "Merge?".into(),
2013 String::new(),
2014 vec!["merge".into(), "hold".into()],
2015 );
2016 q.routed_task = Some("task".into());
2017 q.routed_chat = Some("chat".into());
2018 q.merge_target = Some(crate::merge_decision::Target {
2019 pr: "https://example.test/pull/1".into(),
2020 head: "head-a".into(),
2021 language: "en".into(),
2022 });
2023 assert!(q.clone().answer(Answer::Choice("merge".into())).is_ok());
2024 assert!(
2025 q.settle_by_deputy("seat", "merge", None).is_err(),
2026 "a routed decision is the task chat's, never a deputy's"
2027 );
2028 assert!(
2029 q.answer_chat_button(Answer::Choice("merge".into()), "other-chat", "head-a")
2030 .is_err()
2031 );
2032 assert!(
2033 q.answer_chat_button(Answer::Choice("merge".into()), "chat", "old-head")
2034 .is_err()
2035 );
2036 assert!(
2037 q.answer_chat_button(Answer::Text("merge".into()), "chat", "head-a")
2038 .is_err()
2039 );
2040 assert_eq!(q.status, QuestionStatus::Open);
2041 q.answer_chat_button(Answer::Choice("merge".into()), "chat", "head-a")
2042 .unwrap();
2043 assert_eq!(q.resolution().as_deref(), Some("merge"));
2044 assert!(
2045 q.answer_chat_button(Answer::Choice("merge".into()), "chat", "head-a")
2046 .is_err()
2047 );
2048 }
2049
2050 #[test]
2051 fn gate_divergence_and_release_questions_route_and_await_a_decision() {
2052 let q = |node: &str, seat: &str, choices: Vec<String>| {
2053 Question::new(
2054 "run".into(),
2055 node.into(),
2056 seat.into(),
2057 "s".into(),
2058 String::new(),
2059 choices,
2060 )
2061 };
2062 let gate = q(
2063 crate::github_text::ASK_NODE,
2064 "posting-gate",
2065 vec!["use fallback".into()],
2066 );
2067 assert!(chat_routable(&gate) && awaits_decision(&gate));
2068 for node in [crate::triage::NODE, crate::triage::DEPS_NODE] {
2071 let triage = q(node, "triage", vec!["hold".into(), "discard".into()]);
2072 assert!(chat_routable(&triage) && awaits_decision(&triage));
2073 }
2074 let mut acted = q("conduct", "conductor", vec!["finish".into(), "hold".into()]);
2075 acted
2076 .actions
2077 .insert("finish".into(), crate::ask::ChoiceAction::Done);
2078 assert!(chat_routable(&acted) && awaits_decision(&acted));
2079 let diverged = q(
2080 crate::reconcile::NODE,
2081 crate::reconcile::SEAT,
2082 vec!["a".into()],
2083 );
2084 assert!(chat_routable(&diverged) && awaits_decision(&diverged));
2085 let release = q(
2086 crate::bump::NOTICE_NODE,
2087 "release-watch",
2088 vec!["hold".into()],
2089 );
2090 assert!(chat_routable(&release) && awaits_decision(&release));
2091 let legacy_release = q(
2092 crate::bump::NOTICE_NODE,
2093 "release-watch",
2094 vec![crate::land::APPROVE.into(), crate::land::HOLD.into()],
2095 );
2096 assert!(chat_routable(&legacy_release));
2097 assert!(awaits_decision(&legacy_release));
2098 assert!(!chat_routable(&q(crate::bump::NOTICE_NODE, "bump", vec![])));
2101 assert!(chat_routable(&q(
2102 crate::land::APPROVAL_NODE,
2103 "land",
2104 vec!["merge".into()]
2105 )));
2106 let q = |node: &str| q(node, "seat", vec![]);
2107 assert!(chat_routable(&q("conduct")) && !awaits_decision(&q("conduct")));
2108 let mut m = q(crate::bump::NOTICE_NODE);
2109 m.merge_target = Some(crate::merge_decision::Target {
2110 pr: "https://example.test/pull/1".into(),
2111 head: "h".into(),
2112 language: "en".into(),
2113 });
2114 assert!(chat_routable(&m));
2115 }
2116
2117 #[test]
2118 fn unreadable_repository_config_keeps_task_routing_and_pending_delivery() {
2119 let home = tempfile::tempdir().unwrap();
2120 let queue = Queue::at(home.path().join("queue"));
2121 let repo = home.path().join("repo");
2122 std::fs::create_dir(&repo).unwrap();
2123 std::fs::write(repo.join("magi.toml"), "this is = [not toml").unwrap();
2124 let mut task = Task::new("t".into(), "i".into(), repo, crate::queue::Source::Human);
2125 queue.put(&mut task).unwrap();
2126 let questions = Questions::at(home.path().join("questions"));
2127 let mut q = Question::new(
2128 task.id.clone(),
2129 "conduct".into(),
2130 "seat".into(),
2131 "s".into(),
2132 String::new(),
2133 vec![],
2134 );
2135 questions.put(&mut q).unwrap();
2136 assert_eq!(q.routed_task.as_deref(), Some(task.id.as_str()));
2137 assert_eq!(
2138 questions.get(&q.id).unwrap().routed_task.as_deref(),
2139 Some(task.id.as_str())
2140 );
2141 let talks = Talks::at(home.path().join("talks"));
2142 sweep(&queue, &talks, &questions, home.path());
2143 let outbox = crate::task_inquiry::Outbox::at(home.path());
2144 outbox.sweep(&queue, &talks).unwrap();
2145 assert!(
2146 migration_issues(home.path())
2147 .iter()
2148 .any(|issue| issue.id == q.id)
2149 );
2150 let pending = outbox.get(&q.id).unwrap();
2151 assert!(pending.delivered_to.is_none());
2152 assert!(talks.list().is_empty());
2153 assert_eq!(
2154 pending.decision.unwrap().status,
2155 crate::task_decision::Status::AwaitingOwner
2156 );
2157 }
2158
2159 #[test]
2160 fn a_delivered_decision_is_not_rewritten_on_every_sweep() {
2161 let home = tempfile::tempdir().unwrap();
2162 let queue = Queue::at(home.path().join("queue"));
2163 let talks = talk::Talks::at(home.path().join("talks"));
2164 let questions = Questions::at(home.path().join("questions"));
2165 let mut task = Task::new(
2166 "t".into(),
2167 "i".into(),
2168 home.path().to_path_buf(),
2169 crate::queue::Source::Human,
2170 );
2171 queue.put(&mut task).unwrap();
2172 let mut q = Question::new(
2173 task.id.clone(),
2174 "conduct".into(),
2175 "conductor".into(),
2176 "Finish?".into(),
2177 String::new(),
2178 vec!["finish".into(), "hold".into()],
2179 );
2180 q.actions
2181 .insert("finish".into(), crate::ask::ChoiceAction::Done);
2182 q.routed_task = Some(task.id.clone());
2183 q.routed_chat = Some("chat".into());
2184 questions.put(&mut q).unwrap();
2185 assert!(awaits_decision(&q));
2186 let path = questions.path_of(&q.id);
2187 let before = std::fs::read(&path).unwrap();
2188 let written = std::fs::metadata(&path).unwrap().modified().unwrap();
2189 std::thread::sleep(std::time::Duration::from_millis(50));
2192 sweep(&queue, &talks, &questions, home.path());
2193 sweep(&queue, &talks, &questions, home.path());
2194 assert_eq!(std::fs::read(&path).unwrap(), before);
2195 assert_eq!(
2196 std::fs::metadata(&path).unwrap().modified().unwrap(),
2197 written
2198 );
2199 }
2200 #[test]
2201 fn repair_receipts_keep_transport_and_failed_repairs_pending() {
2202 use crate::{
2203 ask::ChoiceAction,
2204 run::{MergeRepair, MergeRepairPhase as Phase, RunState},
2205 task_decision::{Decision, Status},
2206 task_inquiry::Outbox,
2207 };
2208 let temp = tempfile::tempdir().unwrap();
2209 let home = temp.path();
2210 let queue = Queue::at(home.join("queue"));
2211 let mut run = RunState::new(
2212 home.into(),
2213 "main".into(),
2214 "base".into(),
2215 "work".into(),
2216 Config::default(),
2217 );
2218 run.reserve_under(home).unwrap();
2219 let mut q = Question::new(
2220 run.id.clone(),
2221 crate::land::APPROVAL_NODE.into(),
2222 "land".into(),
2223 "Repair findings".into(),
2224 String::new(),
2225 vec![crate::land::REPAIR.into()],
2226 );
2227 q.merge_target = Some(crate::merge_decision::Target {
2228 pr: "https://example.test/pull/1".into(),
2229 head: "head".into(),
2230 language: "en".into(),
2231 });
2232 q.actions.insert(
2233 crate::land::REPAIR.into(),
2234 ChoiceAction::Resume {
2235 run: run.id.clone(),
2236 },
2237 );
2238 q.answer(Answer::Choice(crate::land::REPAIR.into()))
2239 .unwrap();
2240 run.next_pass_inquiries = vec![q.id.clone()];
2241 run.begin_pass();
2242 run.save_under(home).unwrap();
2243 let mut task = Task::new(
2244 "work".into(),
2245 "work".into(),
2246 home.into(),
2247 crate::queue::Source::Human,
2248 );
2249 task.runs.push(run.id.clone());
2250 task.mark_action_applied(&q.id);
2251 queue.put(&mut task).unwrap();
2252 let outbox = Outbox::at(home);
2253 let mut record = history_record(&q, Some(&task));
2254 let mut decision = Decision::awaiting(q.summary.clone());
2255 decision
2256 .accept(&format!("decision: {}", crate::land::REPAIR))
2257 .unwrap();
2258 record.decision = Some(decision);
2259 record.archived = false;
2260 outbox.enqueue(record).unwrap();
2261 let check = |expected| {
2262 sync_effect_receipt(home, &Queue::at(home.join("queue")), &q);
2263 let decision = Outbox::at(home).get(&q.id).unwrap().decision.unwrap();
2264 assert_eq!(decision.status, expected);
2265 decision
2266 };
2267 check(Status::Queued); run.merge_repairs.push(MergeRepair {
2269 question: "unrelated".into(),
2270 head: "head".into(),
2271 pr: q.merge_target.as_ref().unwrap().pr.clone(),
2272 reviews: vec![],
2273 gate: vec![],
2274 gate_head: None,
2275 gate_fixes: vec![],
2276 pre_gate: vec![],
2277 phase: Phase::Complete,
2278 failure: None,
2279 });
2280 run.save_under(home).unwrap();
2281 check(Status::Queued);
2282 run.merge_repairs[0].question = q.id.clone();
2283 for phase in [
2284 Phase::Requested,
2285 Phase::Fixing,
2286 Phase::Reviewing,
2287 Phase::Failed,
2288 ] {
2289 run.merge_repairs[0].phase = phase;
2290 run.merge_repairs[0].failure =
2291 (phase == Phase::Failed).then(|| "dirty worktree; inspect before retry".into());
2292 run.save_under(home).unwrap();
2293 let decision = check(if phase == Phase::Failed {
2294 Status::RetryNeeded
2295 } else {
2296 Status::Queued
2297 });
2298 if phase == Phase::Failed {
2299 assert!(decision.error.unwrap().contains("dirty worktree"));
2300 assert!(
2301 !decision.retry_safe,
2302 "a repair failure cannot authorize blind replay"
2303 );
2304 }
2305 }
2306 run.merge_repairs[0].phase = Phase::Complete;
2307 run.merge_repairs[0].head = "different-head".into();
2308 run.save_under(home).unwrap();
2309 check(Status::RetryNeeded);
2310 run.merge_repairs[0].head = "head".into();
2311 run.merge_repairs[0].failure = None;
2312 run.save_under(home).unwrap();
2313 check(Status::Resolved);
2314 check(Status::Resolved);
2315 }
2316
2317 #[test]
2318 fn landing_stop_receipts_require_the_intended_effect_after_restart() {
2319 use crate::{
2320 ask::ChoiceAction,
2321 merge_decision::{self as md, Replacement, Target},
2322 queue::{Source, TaskStatus},
2323 run::{PrRecord, RunState, RunStatus},
2324 task_decision::{Decision, Status},
2325 task_inquiry::Outbox,
2326 };
2327 for choice in [crate::land::HOLD, "reimplement:beta"] {
2328 let temp = tempfile::tempdir().unwrap();
2329 let home = temp.path();
2330 let queue = Queue::at(home.join("queue"));
2331 let mut run = RunState::new(
2332 home.into(),
2333 "main".into(),
2334 "base".into(),
2335 "work".into(),
2336 Config::default(),
2337 );
2338 run.reserve_under(home).unwrap();
2339 run.status = RunStatus::Blocked;
2340 run.driver_exited = true;
2341 run.pr = Some(PrRecord {
2342 url: "https://example.test/pull/1".into(),
2343 number: 1,
2344 state: "open".into(),
2345 checks: "green".into(),
2346 round: 1,
2347 rounds: 2,
2348 red_at_merge: vec![],
2349 });
2350 let mut q = Question::new(
2351 run.id.clone(),
2352 crate::land::APPROVAL_NODE.into(),
2353 "land".into(),
2354 "Stop landing".into(),
2355 String::new(),
2356 vec![choice.into()],
2357 );
2358 q.merge_target = Some(Target {
2359 pr: run.pr.as_ref().unwrap().url.clone(),
2360 head: "head".into(),
2361 language: "en".into(),
2362 });
2363 if choice != crate::land::HOLD {
2364 q.actions.insert(
2365 choice.into(),
2366 ChoiceAction::Resume {
2367 run: run.id.clone(),
2368 },
2369 );
2370 }
2371 q.answer(Answer::Choice(choice.into())).unwrap();
2372 run.next_pass_inquiries = vec![q.id.clone()];
2374 run.begin_pass();
2375 run.save_under(home).unwrap();
2376 let mut task = Task::new("work".into(), "work".into(), home.into(), Source::Human);
2377 task.runs.push(run.id.clone());
2378 if choice == crate::land::HOLD {
2379 task.status = TaskStatus::Running;
2380 } else {
2381 task.hold_manual(Some("landing stopped".into()));
2382 task.mark_action_applied(&q.id);
2383 }
2384 queue.put(&mut task).unwrap();
2385 let mut record = history_record(&q, Some(&task));
2386 let mut decision = Decision::awaiting(q.summary.clone());
2387 decision.accept(&format!("decision: {choice}")).unwrap();
2388 record.decision = Some(decision);
2389 record.archived = false;
2390 Outbox::at(home).enqueue(record).unwrap();
2391 let check = |expected| {
2392 sync_effect_receipt(home, &Queue::at(home.join("queue")), &q);
2393 assert_eq!(
2394 Outbox::at(home)
2395 .get(&q.id)
2396 .unwrap()
2397 .decision
2398 .unwrap()
2399 .status,
2400 expected
2401 );
2402 };
2403 check(Status::Queued);
2404 run.merge_decision = Some(md::Decision {
2405 question: q.id.clone(),
2406 target: q.merge_target.clone().unwrap(),
2407 choice: choice.into(),
2408 closed: false,
2409 replacement_run: None,
2410 replacement_pr: None,
2411 });
2412 run.save_under(home).unwrap();
2413 if choice == crate::land::HOLD {
2414 check(Status::Queued);
2416 task.hold_manual(Some("landing stopped".into()));
2417 task.mark_action_applied(&q.id);
2418 queue.put(&mut task).unwrap();
2419 task.release_operator("chat", None);
2421 queue.put(&mut task).unwrap();
2422 assert!(
2423 effect_receipt(home, &queue, &q, Some(&task.id))
2424 .unwrap()
2425 .is_some()
2426 );
2427 run.merge_decision = None;
2428 run.save_under(home).unwrap();
2429 check(Status::Queued); task.decision_effects
2432 .insert(q.id.clone(), format!("decision: {choice}"));
2433 queue.put(&mut task).unwrap();
2434 check(Status::Resolved);
2435 } else {
2436 check(Status::Queued); run.merge_decision.as_mut().unwrap().closed = true;
2438 run.status = RunStatus::Superseded;
2439 run.pr.as_mut().unwrap().state = "closed".into();
2440 run.save_under(home).unwrap();
2441 check(Status::Queued); let mut next = RunState::new(
2443 home.into(),
2444 "main".into(),
2445 "base".into(),
2446 "replacement".into(),
2447 Config::default(),
2448 );
2449 next.reserve_under(home).unwrap();
2450 next.replaces = Some(Replacement {
2451 question: q.id.clone(),
2452 run: run.id.clone(),
2453 pr: q.merge_target.as_ref().unwrap().pr.clone(),
2454 agent: "beta".into(),
2455 context: String::new(),
2456 });
2457 next.save_under(home).unwrap();
2458 run.merge_decision.as_mut().unwrap().replacement_run = Some(next.id.clone());
2459 run.save_under(home).unwrap();
2460 task.start(next.id.clone());
2461 queue.put(&mut task).unwrap();
2462 check(Status::Queued); next.next_pass_task_entry = true;
2464 next.begin_pass();
2465 next.save_under(home).unwrap();
2466 check(Status::Resolved);
2467 }
2468 check(Status::Resolved);
2469 }
2470 }
2471
2472 #[test]
2473 fn quiet_release_receipts_resolve_pending_decisions_after_restart() {
2474 use crate::{
2475 task_decision::{Decision, Status},
2476 task_inquiry::Outbox,
2477 };
2478 for choice in [crate::release_watch::HOLD, crate::release_watch::LEAVE_IT] {
2479 let dir = tempfile::tempdir().unwrap();
2480 let home = dir.path();
2481 let queue = Queue::at(home.join("queue"));
2482 let mut task = Task::new(
2483 "release".into(),
2484 "release".into(),
2485 home.into(),
2486 crate::queue::Source::Human,
2487 );
2488 queue.put(&mut task).unwrap();
2489 let mut q = Question::new(
2490 "run".into(),
2491 crate::bump::NOTICE_NODE.into(),
2492 "release-watch".into(),
2493 "release stalled".into(),
2494 String::new(),
2495 vec![choice.into()],
2496 );
2497 q.answer(Answer::Choice(choice.into())).unwrap();
2498 let mut record = history_record(&q, Some(&task));
2499 let mut decision = Decision::awaiting(q.summary.clone());
2500 decision.accept(&format!("decision: {choice}")).unwrap();
2501 record.decision = Some(decision);
2502 record.archived = false;
2503 Outbox::at(home).enqueue(record).unwrap();
2504 sync_effect_receipt(home, &queue, &q);
2505 assert_eq!(
2506 Outbox::at(home)
2507 .get(&q.id)
2508 .unwrap()
2509 .decision
2510 .unwrap()
2511 .status,
2512 Status::Queued
2513 );
2514 let receipts = home.join("release-watch-receipts");
2515 std::fs::create_dir_all(&receipts).unwrap();
2516 let st = crate::release_watch::WatchState {
2517 applied: vec![q.id.clone()],
2518 ..Default::default()
2519 };
2520 std::fs::write(
2521 receipts.join(format!("{}.json", q.id)),
2522 serde_json::to_vec(&st).unwrap(),
2523 )
2524 .unwrap();
2525 for _ in 0..2 {
2526 sync_effect_receipt(home, &Queue::at(home.join("queue")), &q);
2527 assert_eq!(
2528 Outbox::at(home)
2529 .get(&q.id)
2530 .unwrap()
2531 .decision
2532 .unwrap()
2533 .status,
2534 Status::Resolved
2535 );
2536 }
2537 }
2538 }
2539
2540 #[test]
2541 fn dismiss_receipt_resolves_done_tasks_and_later_attempts_without_task_markers() {
2542 use crate::{
2543 ask::Answer,
2544 queue::{Source, Task, TaskStatus},
2545 run::{LandApproval, PrRecord, RunState, RunStatus},
2546 task_decision::{Decision, Status},
2547 task_inquiry::Outbox,
2548 };
2549 for (later_attempt, incomplete) in [(false, false), (true, false), (false, true)] {
2550 let temp = tempfile::tempdir().unwrap();
2551 let home = temp.path();
2552 let queue = Queue::at(home.join("queue"));
2553 let mut state = RunState::new(
2554 home.into(),
2555 "main".into(),
2556 "base".into(),
2557 "work".into(),
2558 Config::default(),
2559 );
2560 state.reserve_under(home).unwrap();
2561 state.status = RunStatus::Blocked;
2562 state.driver_exited = true;
2563 let mut q = Question::new(
2564 state.id.clone(),
2565 crate::land::APPROVAL_NODE.into(),
2566 "land".into(),
2567 "Obsolete approval".into(),
2568 String::new(),
2569 vec![crate::merge_decision::DISMISS.into()],
2570 );
2571 state.land_approval = Some(LandApproval {
2572 question: q.id.clone(),
2573 head: "head".into(),
2574 });
2575 state.pr = Some(PrRecord {
2576 url: "https://example.test/pull/1".into(),
2577 number: 1,
2578 state: "open".into(),
2579 checks: "green".into(),
2580 round: 1,
2581 rounds: 2,
2582 red_at_merge: vec![],
2583 });
2584 state.save_under(home).unwrap();
2585 let mut task = Task::new("work".into(), "work".into(), home.into(), Source::Human);
2586 task.runs.push(state.id.clone());
2587 task.status = TaskStatus::Done;
2588 if later_attempt {
2589 task.runs.push("later-run".into());
2590 task.status = TaskStatus::Queued;
2591 }
2592 if incomplete {
2593 task.status = TaskStatus::Parked;
2594 }
2595 queue.put(&mut task).unwrap();
2596 q.answer(Answer::Choice(crate::merge_decision::DISMISS.into()))
2597 .unwrap();
2598 let outbox = Outbox::at(home);
2599 let mut record = history_record(&q, Some(&task));
2600 let mut decision = Decision::awaiting(q.summary.clone());
2601 decision
2602 .accept(&format!("decision: {}", crate::merge_decision::DISMISS))
2603 .unwrap();
2604 record.decision = Some(decision);
2605 record.archived = false;
2606 outbox.enqueue(record).unwrap();
2607 if incomplete {
2608 state.merge_decision = Some(crate::merge_decision::Decision {
2611 question: q.id.clone(),
2612 target: crate::merge_decision::Target {
2613 pr: state.pr.as_ref().unwrap().url.clone(),
2614 head: "head".into(),
2615 language: "en".into(),
2616 },
2617 choice: crate::merge_decision::DISMISS.into(),
2618 closed: false,
2619 replacement_run: None,
2620 replacement_pr: None,
2621 });
2622 state.save_under(home).unwrap();
2623 sync_effect_receipt(home, &queue, &q);
2624 assert_eq!(
2625 outbox.get(&q.id).unwrap().decision.unwrap().status,
2626 Status::Queued
2627 );
2628 }
2629 crate::merge_decision::dismiss(home, &q).unwrap();
2630 let after = std::fs::read(queue.path_of(&task.id)).unwrap();
2631 assert_eq!(
2632 queue.get(&task.id).unwrap().action_applied(&q.id),
2633 incomplete
2634 );
2635 for _ in 0..2 {
2636 sync_effect_receipt(home, &queue, &q);
2637 assert_eq!(
2638 Outbox::at(home)
2639 .get(&q.id)
2640 .unwrap()
2641 .decision
2642 .unwrap()
2643 .status,
2644 Status::Resolved
2645 );
2646 assert_eq!(std::fs::read(queue.path_of(&task.id)).unwrap(), after);
2647 }
2648 assert_eq!(
2649 RunState::load_under(&q.run, home)
2650 .unwrap()
2651 .pr
2652 .unwrap()
2653 .state,
2654 "open"
2655 );
2656 }
2657 }
2658}