1use std::path::Path;
38
39use anyhow::{Context, Result, bail, ensure};
40
41pub use crate::base_sync_recovery::Stop as BaseRecoveryStop;
43use crate::queue::{Queue, Task, TaskStatus};
44use crate::talk::{Talk, Talks};
45
46#[cfg(any(unix, windows))]
47pub(crate) mod bridge;
48
49pub(crate) mod standing;
50
51#[derive(Debug, serde::Serialize, serde::Deserialize)]
54#[serde(tag = "operation", deny_unknown_fields)]
55pub enum Operation {
56 Standing {
58 task: String,
60 evidence: String,
62 command: Box<Operation>,
64 },
65 Goal {
67 command: crate::chat_goal::Command,
69 },
70 Reassign {
72 task: String,
74 repo: std::path::PathBuf,
76 },
77 GrantRepair {
79 request: crate::repair_budget::Request,
81 },
82 ReconcileRepairGrant {
84 request: crate::repair_budget::reconcile::Request,
86 },
87 ReconcileDecision {
89 inquiry: String,
91 },
92 ForDecision {
94 inquiry: String,
96 command: Box<Operation>,
98 },
99 SettleDecision {
101 inquiry: String,
103 reason: String,
105 replacement: Option<String>,
107 },
108 Add {
110 filing: Box<Filing>,
112 },
113 AddImmediate {
116 request: String,
118 filing: Box<Filing>,
120 #[serde(default)]
122 force: bool,
123 },
124 SetImmediate {
127 request: String,
129 task: String,
131 #[serde(default)]
133 clear: bool,
134 },
135 Done {
137 task: String,
139 #[serde(default)]
141 reason: Option<String>,
142 #[serde(default, skip_serializing_if = "Option::is_none")]
144 result: Option<String>,
145 #[serde(default)]
147 discard: bool,
148 },
149 Reopen {
151 task: String,
153 reason: String,
155 },
156 Priority {
158 task: String,
160 priority: i32,
162 },
163 MergePr {
165 repo: String,
167 number: u64,
169 head: String,
171 request: String,
173 },
174 RecoverBase {
176 run: String,
178 head: String,
180 request: String,
182 #[serde(default, skip_serializing_if = "Option::is_none")]
184 evidence_digest: Option<String>,
185 },
186 RecoverLandSync {
188 run: String,
190 head: String,
192 request: String,
194 },
195 AdoptInstruction {
198 run: String,
200 head: String,
202 request: String,
204 },
205 Resume {
207 run: String,
209 },
210 SyncBaseOnly {
212 run: String,
214 },
215 Hold {
217 task: String,
219 reason: String,
221 },
222 Release {
224 task: String,
226 },
227 Retry {
229 task: String,
231 title: Option<String>,
233 instruction: String,
235 },
236 RerunChecks {
238 run: String,
240 request: String,
242 head: String,
244 workflows: Vec<String>,
246 },
247 Decide {
249 question: String,
251 choice: String,
253 #[serde(default)]
255 title: Option<String>,
256 },
257 Answer {
260 question: String,
262 reply: String,
264 #[serde(default)]
266 title: Option<String>,
267 },
268 ReplyOther {
272 question: String,
274 text: String,
276 },
277 ReconcileRetention {
279 task: String,
281 authority: String,
283 apply: Option<String>,
285 },
286 Abandon {
288 run: String,
290 },
291}
292
293#[derive(Debug, serde::Serialize, serde::Deserialize)]
295#[serde(deny_unknown_fields)]
296pub struct Filing {
297 pub title: String,
299 pub instruction: String,
301 pub repo: std::path::PathBuf,
303 #[serde(default)]
305 pub investigation: bool,
306 pub source: crate::queue::Source,
308 #[serde(default, skip_serializing_if = "Option::is_none")]
310 pub issue: Option<crate::queue::IssueRef>,
311 pub sources: crate::refs::Sources,
313 pub hold: Option<String>,
315 pub priority: i32,
317 pub solo: bool,
319 pub urgent: bool,
321 pub implementers: Option<usize>,
323 #[serde(default, skip_serializing_if = "Option::is_none")]
325 pub build_cache: Option<crate::config::BuildCache>,
326 pub attach: Vec<std::path::PathBuf>,
328}
329
330pub fn has_channel() -> bool {
333 #[cfg(any(unix, windows))]
334 {
335 #[cfg(unix)]
336 let socket = std::env::var_os("MAGI_CHAT_CONTROL_SOCKET").is_some();
337 #[cfg(windows)]
338 let socket = false;
339 std::env::var_os(bridge::CHANNEL_ENV).is_some() || socket
340 }
341 #[cfg(not(any(unix, windows)))]
342 {
343 false
344 }
345}
346
347pub async fn dispatch(
350 queue: &Queue,
351 home: &Path,
352 talks: &Talks,
353 talk: &str,
354 operation: Operation,
355) -> Result<String> {
356 if matches!(
357 &operation,
358 Operation::Reassign { .. }
359 | Operation::RecoverBase { .. }
360 | Operation::RecoverLandSync { .. }
361 | Operation::AdoptInstruction { .. }
362 | Operation::SyncBaseOnly { .. }
363 | Operation::Goal { .. }
364 | Operation::Standing { .. }
365 | Operation::AddImmediate { .. }
366 | Operation::SetImmediate { .. }
367 ) {
368 #[cfg(unix)]
369 {
370 return bridge::request(&operation).context("this operation requires the authenticated chat control channel; repair the launcher/backend transport; reopening the conversation does not repair descriptor propagation");
371 }
372 #[cfg(windows)]
373 {
374 return bridge::request(&operation).await.context("this operation requires the authenticated chat control channel; repair the launcher/backend transport; reopening the conversation does not repair descriptor propagation");
375 }
376 #[cfg(not(any(unix, windows)))]
377 {
378 bail!("authenticated chat control channel is unavailable on this platform");
379 }
380 }
381 if standing_turn() {
382 #[cfg(unix)]
383 return bridge::request(&operation)
384 .context("automatic recovery requires the authenticated chat control channel");
385 #[cfg(windows)]
386 return bridge::request(&operation)
387 .await
388 .context("automatic recovery requires the authenticated chat control channel");
389 #[cfg(not(any(unix, windows)))]
390 bail!("authenticated chat control channel is unavailable on this platform");
391 }
392 #[cfg(unix)]
393 if std::env::var_os(bridge::CHANNEL_ENV).is_some()
394 || std::env::var_os("MAGI_CHAT_CONTROL_SOCKET").is_some()
395 {
396 match bridge::request(&operation) {
399 Err(error)
400 if error.is::<bridge::Unavailable>()
401 && std::env::var("MAGI_ALLOW_WRITE").as_deref() == Ok("1") => {}
402 result => return result,
403 }
404 }
405 #[cfg(windows)]
406 if std::env::var_os(bridge::CHANNEL_ENV).is_some() {
407 return bridge::request(&operation).await;
408 }
409 Box::pin(execute(queue, home, talks, talk, operation)).await
410}
411
412pub(crate) async fn execute_authenticated(
414 queue: &Queue,
415 home: &Path,
416 talks: &Talks,
417 talk: &str,
418 source: crate::chat_goal::Source,
419 operation: Operation,
420) -> Result<String> {
421 if let crate::chat_goal::Source::Standing(scope) = source {
422 return Box::pin(standing::execute(
423 queue, home, talks, talk, &scope, operation,
424 ))
425 .await;
426 }
427 crate::chat_goal::with_source(
428 source,
429 Box::pin(execute(queue, home, talks, talk, operation)),
430 )
431 .await
432}
433
434pub fn standing_turn() -> bool {
437 std::env::var_os(standing::ENV).is_some()
438}
439
440async fn execute(
441 queue: &Queue,
442 home: &Path,
443 talks: &Talks,
444 talk: &str,
445 operation: Operation,
446) -> Result<String> {
447 authorize(talks, talk, crate::queue::CHAT_NODE)?;
448 crate::chat_goal::fence(talks, talk, &crate::chat_goal::current_source())?;
449 admit_goal_operation(queue, home, talks, talk, &operation)?;
450 Ok(match operation {
451 Operation::Standing { .. } => bail!(
452 "standing authorization is disabled or this turn is not an eligible automatic report"
453 ),
454 Operation::Goal { command } => {
455 crate::chat_goal::apply(
456 queue,
457 home,
458 talks,
459 talk,
460 &crate::chat_goal::current_source(),
461 command,
462 )
463 .await?
464 }
465 Operation::Reassign { task, repo } => {
466 let cwd = &talks.get(talk)?.repo;
467 let task = crate::task_reassign::reassign(
468 queue,
469 home,
470 cwd,
471 &task,
472 &repo,
473 &format!("chat:{talk}"),
474 )
475 .await?;
476 let mut message = describe(&task, "reassigned");
477 for note in crate::task_reassign::advisory_notes(&task, home) {
478 message.push_str(&format!("\n {note}"));
479 }
480 message
481 }
482 Operation::ReconcileDecision { inquiry } => {
483 reconcile_task_decision(queue, home, talk, &inquiry)?;
484 format!("decision {inquiry} reconciled from the task's durable state")
485 }
486 Operation::ForDecision { inquiry, command } => {
487 Box::pin(execute_decision(
488 queue, home, talks, talk, &inquiry, *command,
489 ))
490 .await?
491 }
492 Operation::SettleDecision {
493 inquiry,
494 reason,
495 replacement,
496 } => {
497 let outbox = crate::task_inquiry::Outbox::at(home);
498 let record = outbox.get(&inquiry)?;
499 let questions = crate::ask::Questions::at(home.join("questions"));
500 let source = questions.read_history(&inquiry).ok();
501 let unaccepted_history = record
505 .decision
506 .as_ref()
507 .is_some_and(|d| d.request.is_none())
508 && source.as_ref().is_some_and(|source| {
509 source.status == crate::ask::QuestionStatus::Answered
510 && crate::task_chat::saved_reply_requires_confirmation(home, source)
511 });
512 let _task_claim = if !record.task.is_empty()
516 && (unaccepted_history
517 || record
518 .decision
519 .as_ref()
520 .is_some_and(|d| d.request.is_some()))
521 {
522 Some(
523 queue
524 .claim(&record.task)
525 .context("decision task is executing")?,
526 )
527 } else {
528 None
529 };
530 if record
531 .decision
532 .as_ref()
533 .is_some_and(|d| d.request.is_none())
534 && let Some(source) = source
535 && !(record.task.is_empty() && record.delivered_to.is_none())
536 {
537 ensure!(
538 unaccepted_history || !crate::task_chat::awaits_decision(&source),
539 "a legacy effect still awaits consumer reconciliation; settlement executes no action"
540 );
541 }
542 outbox.settle(&inquiry, talk, &reason, replacement.as_deref())?;
543 format!("settled decision {inquiry}: {reason}")
544 }
545 Operation::Add { filing } => {
546 ensure!(
547 matches!(&filing.source, crate::queue::Source::Agent { run, node }
548 if run == talk && node == crate::queue::CHAT_NODE),
549 "filing must retain this conversation's provenance"
550 );
551 serde_json::to_string(&file_task(queue, *filing)?)?
552 }
553 Operation::AddImmediate {
554 request,
555 filing,
556 force,
557 } => serde_json::to_string(
558 &Box::pin(crate::immediate_filing_control::file(
559 queue, home, talks, talk, &request, *filing, force,
560 ))
561 .await?,
562 )?,
563 Operation::SetImmediate {
564 request,
565 task,
566 clear,
567 } => serde_json::to_string(&crate::immediate_filing_control::set(
568 queue, home, talks, talk, &request, &task, clear,
569 )?)?,
570 Operation::Done {
571 task,
572 reason,
573 result,
574 discard,
575 } => {
576 let claimed = claimed_for_chat(queue, &task, talks, talk)?;
577 let task = Box::pin(crate::task_completion::close_claimed(
578 queue,
579 home,
580 claimed,
581 crate::queue::CompletionActor::Chat(talk.to_owned()),
582 reason,
583 result,
584 discard,
585 ))
586 .await?;
587 crate::task_completion::describe(&task)
588 }
589 Operation::Reopen { task, reason } => {
590 let (_claim, mut t) = claimed_for_chat(queue, &task, talks, talk)?;
591 let expected = t.clone();
592 let (_guards, context) = Box::pin(crate::task_completion::admit_reopen(
593 &t,
594 home,
595 crate::queue::CompletionActor::Chat(talk.to_owned()),
596 &reason,
597 ))
598 .await?;
599 t.reopen(context)?;
600 queue.commit_completion(&mut t, &expected)?;
601 describe(&t, "reopened on hold")
602 }
603 Operation::Priority { task, priority } => {
604 let t = priority_claimed(
605 queue,
606 claimed_for_chat(queue, &task, talks, talk)?,
607 priority,
608 )?;
609 format!("{} priority now {} - {}", t.short(), t.priority, t.title)
610 }
611 Operation::MergePr {
612 repo,
613 number,
614 head,
615 request,
616 } => crate::chat_merge::merge(
617 home,
618 talks,
619 talk,
620 crate::chat_merge::Request {
621 repo,
622 number,
623 head,
624 request,
625 },
626 )
627 .await
628 .map_err(|error| {
629 if error.is::<crate::chat_merge::BeforeMergeWrite>() {
630 anyhow::Error::new(BeforeEffect(error))
631 } else {
632 error
633 }
634 })?,
635 Operation::ReconcileRepairGrant { request } => serde_json::to_string(
636 &Box::pin(crate::repair_budget::reconcile::apply(queue, home, request)).await?,
637 )?,
638 Operation::GrantRepair { request } => {
639 let owner_requested_at = match crate::chat_goal::current_source() {
642 crate::chat_goal::Source::Input { turn } => talks
643 .get(talk)?
644 .turns
645 .get(turn)
646 .and_then(|turn| crate::talk::owner_send_boundary(&turn.messages)),
647 _ => None,
648 };
649 let receipt = Box::pin(crate::repair_budget::grant_with_claim(
650 queue,
651 home,
652 request,
653 None,
654 owner_requested_at,
655 ))
656 .await
657 .map_err(|error| {
658 if error.is::<crate::repair_budget::PublicationUnknown>() {
659 error
660 } else {
661 BeforeEffect(error).into()
662 }
663 })?;
664 serde_json::to_string(&receipt)?
665 }
666 Operation::RecoverBase {
667 run,
668 head,
669 request,
670 evidence_digest,
671 } => {
672 if evidence_digest.is_some() {
673 ensure!(
674 matches!(
675 crate::chat_goal::current_source(),
676 crate::chat_goal::Source::Input { .. }
677 ),
678 "preparation recovery requires explicit owner input"
679 );
680 }
681 let result = Box::pin(crate::base_recovery_control::recover(
682 queue,
683 home,
684 crate::base_recovery_control::Request {
685 run,
686 head,
687 request,
688 actor: talk.to_owned(),
689 decision: None,
690 expected_stop: None,
691 evidence_digest,
692 },
693 ))
694 .await?;
695 if result.repeated {
696 format!(
697 "This base-recovery request was already applied to task {}; inspect its current status before continuing",
698 result.task.id
699 )
700 } else {
701 format!(
702 "{}; bounded base recovery authorized; the daemon resumes the exact run under its execution lease",
703 describe(&result.task, "recovery queued for")
704 )
705 }
706 }
707 Operation::RecoverLandSync { run, head, request } => {
708 ensure!(
709 matches!(
710 crate::chat_goal::current_source(),
711 crate::chat_goal::Source::Input { .. }
712 ),
713 "recover-land-sync requires explicit owner input"
714 );
715 let result = Box::pin(crate::land_sync_recovery_control::recover(
716 queue,
717 home,
718 crate::land_sync_recovery_control::Request {
719 run,
720 head,
721 request,
722 actor: talk.to_owned(),
723 },
724 ))
725 .await
726 .map_err(|error| {
727 if error.is::<crate::land_sync_recovery_control::BeforeWrite>() {
728 anyhow::Error::new(BeforeEffect(error))
729 } else {
730 error
731 }
732 })?;
733 if result.repeated {
734 format!(
735 "This landing base-sync recovery request was already applied to task {}; inspect its current status before continuing",
736 result.task.id
737 )
738 } else {
739 format!(
740 "{}; bounded landing base-sync recovery authorized (1 attempt); the daemon resumes the exact run under its execution lease",
741 describe(&result.task, "landing sync recovery queued for")
742 )
743 }
744 }
745 Operation::AdoptInstruction { run, head, request } => {
746 ensure!(
747 matches!(
748 crate::chat_goal::current_source(),
749 crate::chat_goal::Source::Input { .. }
750 ),
751 "adopt-instruction requires explicit owner input"
752 );
753 let result = Box::pin(crate::instruction_revision_control::adopt(
754 queue,
755 home,
756 crate::instruction_revision_control::Request {
757 run,
758 head,
759 request,
760 actor: talk.to_owned(),
761 },
762 ))
763 .await
764 .map_err(|error| {
765 if error.is::<crate::instruction_revision_control::BeforeWrite>() {
766 anyhow::Error::new(BeforeEffect(error))
767 } else {
768 error
769 }
770 })?;
771 if result.repeated {
772 format!(
773 "This instruction adoption request was already applied to task {}; inspect its current status before continuing",
774 result.task.id
775 )
776 } else {
777 format!(
778 "{}; revised instruction adopted into the existing run and PR; the daemon resumes it for one bounded repair and fresh review",
779 describe(&result.task, "instruction adoption queued for")
780 )
781 }
782 }
783 Operation::Resume { run } => {
784 let t = resume(queue, home, &run)?;
785 format!(
786 "{}; the loop (`magi serve`) resumes the run under its execution lease",
787 describe(&t, "resume queued for")
788 )
789 }
790 Operation::SyncBaseOnly { run } => {
791 ensure!(
792 matches!(
793 crate::chat_goal::current_source(),
794 crate::chat_goal::Source::Input { .. }
795 ),
796 "sync-base-only requires an explicit owner request in this chat turn"
797 );
798 let owner = run_task(queue, &run)?;
799 let _claim = queue.claim(&owner.id)?;
800 let mut task = queue.get(&owner.id)?;
801 crate::base_sync_only::queue(&mut task, home, &run)?;
802 queue.put(&mut task)?;
803 describe(&task, "base synchronization only queued for")
804 }
805 Operation::Hold { task, reason } => describe(
806 &hold_claimed(queue, claimed_for_chat(queue, &task, talks, talk)?, &reason)?,
807 "held",
808 ),
809 Operation::Release { task } => describe(
810 &release_claimed(queue, claimed_for_chat(queue, &task, talks, talk)?)?,
811 "released",
812 ),
813 Operation::Retry {
814 task,
815 title,
816 instruction,
817 } => describe(
818 &retry_claimed(
819 queue,
820 claimed_for_chat(queue, &task, talks, talk)?,
821 title,
822 &instruction,
823 )?,
824 "retry queued for",
825 ),
826 Operation::RerunChecks {
827 run,
828 request,
829 head,
830 workflows,
831 } => {
832 let ids = rerun_checks(queue, home, talk, &run, &request, &head, &workflows).await?;
833 format!("requested a rerun of workflow run(s) {}", ids.join(", "))
834 }
835 Operation::Decide {
836 question,
837 choice,
838 title,
839 } => {
840 let q = record_decision(home, &question, &choice, title.as_deref())?;
841 format!(
842 "recorded `{choice}` for decision {}; effect pending until its durable application receipt is confirmed",
843 q.short()
844 )
845 }
846 Operation::Answer {
847 question,
848 reply,
849 title,
850 } => crate::ask::record_answer(
851 &crate::ask::Questions::at(home.join("questions")),
852 &question,
853 &reply,
854 title.as_deref(),
855 )?,
856 Operation::ReplyOther { question, text } => crate::consult::reply_other(
857 &crate::ask::Questions::at(home.join("questions")),
858 &question,
859 &text,
860 )?,
861 Operation::ReconcileRetention {
862 task,
863 authority,
864 apply,
865 } => {
866 let path = Box::pin(crate::retention::reconcile::run_chat(
867 home,
868 &task,
869 &authority,
870 apply.as_deref(),
871 crate::retention::reconcile::ChatRequest {
872 talks,
873 conversation: talk,
874 },
875 ))
876 .await?;
877 if apply.is_none() {
878 crate::retention::reconcile::chat_summary(&path)?
880 } else {
881 format!(
882 "Applied saved plan {}",
883 apply.as_deref().unwrap_or_default()
884 )
885 }
886 }
887 Operation::Abandon { run } => {
888 abandon(queue, home, &run)?;
889 format!("abandoned run {run}")
890 }
891 })
892}
893
894pub(crate) fn build_task(filing: Filing, immediate: bool) -> Task {
895 let mut task = Task::new(filing.title, filing.instruction, filing.repo, filing.source);
896 task.issue = filing.issue;
897 task.investigation = filing.investigation;
898 task.sources = filing.sources;
899 if let Some(reason) = filing.hold {
900 task.hold_manual(Some(reason));
901 }
902 task.priority = filing.priority;
903 task.solo = filing.solo;
904 task.urgent = filing.urgent;
905 task.immediate = immediate;
906 if filing.implementers.is_some() || filing.build_cache.is_some() {
907 task.overrides = Some(crate::queue::RunOverrides {
908 inherit_daemon_options: filing.implementers.is_none(),
909 candidates: filing.implementers,
910 build_cache: filing.build_cache,
911 ..Default::default()
912 });
913 }
914 task
915}
916
917fn file_task(queue: &Queue, filing: Filing) -> Result<Task> {
918 let attach = filing.attach.clone();
919 let mut task = build_task(filing, false);
920 if attach.is_empty() {
921 queue.put(&mut task)?;
922 } else {
923 queue.attach_and_put(&mut task, &attach)?;
924 }
925 Ok(task)
926}
927
928fn admit_goal_operation(
930 queue: &Queue,
931 home: &Path,
932 talks: &Talks,
933 talk_id: &str,
934 operation: &Operation,
935) -> Result<()> {
936 let crate::chat_goal::Source::Goal { id, generation } = crate::chat_goal::current_source()
937 else {
938 return Ok(());
939 };
940 let talk = talks.get(talk_id)?;
941 let goal = talk
942 .goals
943 .iter()
944 .find(|goal| goal.id == id)
945 .context("unknown goal")?;
946 goal.admit(generation)?;
947 ensure!(
948 !goal.owner_input.is_empty(),
949 "this goal was registered under standing authorization; fresh owner input is required with the setting off"
950 );
951 let repo = goal.effective_repo(&talk.repo);
952 let task_allowed = |reference: &str| -> Result<()> {
953 let id = queue.resolve_id(reference)?;
954 ensure!(
955 goal.tasks.contains(&id),
956 "effect targets a task outside this goal"
957 );
958 crate::chat_goal::task_record(queue, &id, repo)?;
959 Ok(())
960 };
961 let run_allowed = |run: &str| -> Result<()> {
962 ensure!(
963 goal.runs.iter().any(|id| id == run)
964 || goal
965 .tasks
966 .iter()
967 .any(|id| crate::chat_goal::task_record(queue, id, repo)
968 .is_ok_and(|task| task.execution_runs().iter().any(|id| id == run))),
969 "effect targets an execution outside this goal"
970 );
971 crate::chat_goal::run_record(home, run, repo)?;
972 Ok(())
973 };
974 match operation {
975 Operation::Standing { .. } => bail!("standing authorization is disabled for this turn"),
976 Operation::Goal { .. } => {}
977 Operation::Add { filing } => {
978 crate::chat_goal::require_repo("filing", talk_id, &filing.repo, repo)?;
979 ensure!(
980 matches!(&filing.source, crate::queue::Source::Agent { run, node }
981 if run == talk_id && node == crate::queue::CHAT_NODE),
982 "goal filing must retain this conversation's provenance"
983 );
984 }
985 Operation::SetImmediate { .. } => {
986 bail!(
987 "automatic goal turns cannot change immediate settings; explicit owner input is required"
988 )
989 }
990 Operation::AddImmediate { .. } => {
991 bail!(
992 "automatic goal turns cannot file immediate tasks; explicit owner input is required"
993 )
994 }
995 Operation::Done { discard: true, .. } | Operation::Reopen { .. } => {
996 anyhow::bail!("task discard and reopen require an explicit owner turn");
997 }
998 Operation::Done {
999 task,
1000 discard: false,
1001 ..
1002 }
1003 | Operation::Priority { task, .. }
1004 | Operation::Hold { task, .. }
1005 | Operation::Release { task }
1006 | Operation::Retry { task, .. }
1007 | Operation::ReconcileRetention { task, .. } => task_allowed(task)?,
1008 Operation::GrantRepair { request } => {
1009 task_allowed(&request.task)?;
1010 run_allowed(&request.run)?;
1011 }
1012 Operation::ReconcileRepairGrant { request } => {
1013 task_allowed(&request.task)?;
1014 run_allowed(&request.run)?;
1015 }
1016 Operation::AdoptInstruction { .. } => {
1017 bail!(
1018 "automatic goal turns cannot adopt a revised instruction; explicit owner input is required"
1019 )
1020 }
1021 Operation::RecoverLandSync { .. } => {
1022 bail!(
1023 "automatic goal turns cannot authorize landing base-sync recovery; explicit owner input is required"
1024 )
1025 }
1026 Operation::Resume { run }
1027 | Operation::SyncBaseOnly { run }
1028 | Operation::RecoverBase { run, .. }
1029 | Operation::Abandon { run }
1030 | Operation::RerunChecks { run, .. } => run_allowed(run)?,
1031 Operation::ForDecision { inquiry, .. }
1032 | Operation::ReconcileDecision { inquiry }
1033 | Operation::SettleDecision { inquiry, .. } => {
1034 let record = crate::task_inquiry::Outbox::at(home).get(inquiry)?;
1035 crate::chat_goal::require_repo("inquiry", inquiry, &record.repo, repo)?;
1036 task_allowed(&record.task)?;
1037 if let Some(run) = record.run {
1038 run_allowed(&run)?;
1039 }
1040 }
1041 Operation::Decide { question, .. }
1042 | Operation::Answer { question, .. }
1043 | Operation::ReplyOther { question, .. } => {
1044 let questions = crate::ask::Questions::at(home.join("questions"));
1045 let question = questions.get_for_effects(&questions.resolve_id(question)?)?;
1046 if question.run_names_task() {
1047 task_allowed(&question.run)?;
1048 } else {
1049 run_allowed(&question.run)?;
1050 }
1051 }
1052 Operation::MergePr {
1053 repo: slug, number, ..
1054 } => {
1055 let expected = format!("https://github.com/{slug}/pull/{number}");
1056 let mut found = false;
1057 let mut inspect = |run: &str| -> Result<()> {
1058 let state = crate::chat_goal::run_record(home, run, repo)?;
1059 found |= state
1060 .pr
1061 .as_ref()
1062 .is_some_and(|pr| pr.url.eq_ignore_ascii_case(&expected));
1063 Ok(())
1064 };
1065 for run in &goal.runs {
1066 inspect(run)?;
1067 }
1068 for task in &goal.tasks {
1069 for run in crate::chat_goal::task_record(queue, task, repo)?.execution_runs() {
1070 inspect(run)?;
1071 }
1072 }
1073 ensure!(found, "merge targets a pull request outside this goal");
1074 }
1075 Operation::Reassign { .. } => bail!("automatic goal turns cannot change repository scope"),
1076 }
1077 Ok(())
1078}
1079
1080async fn execute_decision(
1085 queue: &Queue,
1086 home: &Path,
1087 talks: &Talks,
1088 chat: &str,
1089 id: &str,
1090 command: Operation,
1091) -> Result<String> {
1092 use crate::task_decision::Status;
1093 admit_goal_operation(queue, home, talks, chat, &command)?;
1094 let outbox = crate::task_inquiry::Outbox::at(home);
1095 let _execution = outbox.execution_claim(id)?;
1096 let inquiry = outbox.get(id)?;
1097 ensure!(
1098 inquiry.delivered_to.as_deref() == Some(chat),
1099 "decision belongs to another chat"
1100 );
1101 let task = queue.get(&inquiry.task)?;
1102 ensure!(task.repo == inquiry.repo, "decision repository changed");
1103 let deferred = matches!(
1104 command,
1105 Operation::Resume { .. } | Operation::MergePr { .. }
1106 );
1107 let merge = match &command {
1108 Operation::MergePr {
1109 repo,
1110 number,
1111 head,
1112 request,
1113 } => Some(crate::chat_merge::Request {
1114 repo: repo.clone(),
1115 number: *number,
1116 head: head.clone(),
1117 request: request.clone(),
1118 }),
1119 _ => None,
1120 };
1121 match &command {
1122 Operation::Done { task: target, .. }
1123 | Operation::Reopen { task: target, .. }
1124 | Operation::Hold { task: target, .. }
1125 | Operation::Release { task: target }
1126 | Operation::Retry { task: target, .. } => {
1127 ensure!(
1128 queue.resolve_id(target)? == task.id,
1129 "command targets another task"
1130 );
1131 }
1132 Operation::Resume { run }
1133 | Operation::Abandon { run }
1134 | Operation::RerunChecks { run, .. } => {
1135 ensure!(
1136 task.runs.contains(run) && inquiry.run.as_ref().is_none_or(|own| own == run),
1137 "command targets another execution"
1138 );
1139 ensure!(
1140 queue
1141 .list()
1142 .iter()
1143 .filter(|owner| owner.runs.contains(run))
1144 .count()
1145 == 1,
1146 "execution ownership is ambiguous"
1147 );
1148 }
1149 Operation::MergePr { repo, number, .. } => {
1150 let run = inquiry
1151 .run
1152 .as_ref()
1153 .or_else(|| task.runs.last())
1154 .context("task has no execution for this merge")?;
1155 let state = crate::run::RunState::load_under(run, home)?;
1156 ensure!(state.id == *run, "merge run identity changed");
1157 ensure!(
1158 crate::git::same_checkout(&state.repo, &task.repo)?,
1159 "merge targets another repository"
1160 );
1161 let expected = format!("https://github.com/{repo}/pull/{number}");
1162 ensure!(
1163 state
1164 .pr
1165 .as_ref()
1166 .is_some_and(|pr| pr.url.eq_ignore_ascii_case(&expected)),
1167 "merge targets another task or repository"
1168 );
1169 }
1170 _ => bail!("use a task/run effect command with --decision; routed approvals use decide"),
1171 }
1172 let request = serde_json::to_string(&command)?;
1173 let mut decision = inquiry.decision.context("inquiry is informational")?;
1174 if decision.request.is_some()
1175 && decision.status != Status::Resolved
1176 && let Operation::Resume { run } = &command
1177 {
1178 ensure!(
1179 decision.request.as_deref() == Some(&request),
1180 "decision already binds a different request"
1181 );
1182 reconcile_resume_claimed(queue, home, &outbox, id, run)?;
1187 decision = outbox
1188 .get(id)?
1189 .decision
1190 .context("inquiry is informational")?;
1191 ensure!(
1192 decision.status == Status::Resolved || decision.retry_safe,
1193 "previous resume remains queued or executing; it will not be replayed"
1194 );
1195 }
1196 if decision.status == Status::Resolved {
1197 ensure!(
1198 decision.request.as_deref() == Some(&request),
1199 "decision resolved for a different request"
1200 );
1201 return Ok(format!(
1202 "decision {id} is already resolved; inspect its outcome history"
1203 ));
1204 }
1205 if let Operation::RerunChecks { run, request, .. } = &command {
1206 rerun_preflight(queue, home, run, request)?;
1209 }
1210 if let Some(action) = &merge {
1211 action.validate()?;
1214 }
1215 let merge_admission = merge
1218 .as_ref()
1219 .map(|action| crate::chat_merge::admit(home, talks, chat, action))
1220 .transpose()?;
1221 if decision.request.is_none() && decision.status == Status::RetryNeeded {
1222 if let Ok(source) = crate::ask::Questions::at(home.join("questions")).get(id) {
1223 ensure!(
1224 !crate::task_chat::awaits_decision(&source),
1225 "a legacy effect still needs its receipt reconciled before another effect is accepted"
1226 );
1227 }
1228 }
1229 {
1230 let claim = (queue.get(&task.id)?.status != TaskStatus::Running)
1233 .then(|| queue.claim(&task.id))
1234 .transpose();
1235 let _claim = match claim {
1236 Ok(claim) => claim,
1237 Err(error) => {
1238 let message = format!(
1242 "{error:#}. No effect began; retry this same request after resolving the cause, or explicitly settle it."
1243 );
1244 outbox.update_decision(id, |d| {
1245 let safe = d.request.is_none() || d.retry_safe;
1246 d.accept(&request)?;
1247 if safe {
1248 d.fail_before_effect(&message)
1249 } else {
1250 Ok(false)
1253 }
1254 })?;
1255 return Err(anyhow::Error::new(BeforeEffect(error)));
1256 }
1257 };
1258 outbox.update_decision(id, |d| d.accept(&request))?;
1259 }
1260 let late_admission = crate::chat_goal::fence(talks, chat, &crate::chat_goal::current_source())
1261 .and_then(|()| admit_goal_operation(queue, home, talks, chat, &command));
1262 if late_admission.is_ok()
1263 && decision.request.is_some()
1264 && matches!(decision.status, Status::InProgress | Status::RetryNeeded)
1265 {
1266 if decision.retry_safe {
1267 outbox.update_decision(id, |d| {
1268 d.retry_unapplied()?;
1269 d.start()
1270 })?;
1271 } else {
1272 let action = merge
1273 .as_ref()
1274 .context("previous effect needs receipt reconciliation; it will not be replayed")?;
1275 ensure!(
1276 merge_receipt(home, chat, action)?.is_some(),
1277 "previous merge has no receipt; inspect the operation before retrying"
1278 );
1279 }
1280 } else if late_admission.is_ok() {
1283 outbox.update_decision(id, |d| d.start())?;
1284 }
1285 let local = match late_admission {
1286 Err(error)
1288 if decision.request.is_some()
1289 && !decision.retry_safe
1290 && (matches!(decision.status, Status::InProgress | Status::RetryNeeded)
1291 || decision
1292 .history
1293 .iter()
1294 .any(|event| event.status == Status::InProgress)) =>
1295 {
1296 return Err(error);
1297 }
1298 Err(error) => Err(anyhow::Error::new(BeforeEffect(error))),
1299 Ok(()) => {
1300 Box::pin(apply_local_decision(
1301 queue,
1302 home,
1303 id,
1304 &request,
1305 &inquiry.task,
1306 &inquiry.repo,
1307 &command,
1308 ))
1309 .await
1310 }
1311 };
1312 let result = if let Err(error) = local {
1313 Err(error)
1314 } else if let Some(message) = local? {
1315 Ok(message)
1316 } else if let Operation::Resume { run } = &command {
1317 crate::resume::validate(home, run)
1319 .map(|_| ())
1320 .map_err(|e| anyhow::Error::new(BeforeEffect(e)))
1321 .and_then(|()| -> Result<String> {
1322 let pinned =
1323 crate::resume::pin_queued(queue, run, None, Some(id)).map_err(|error| {
1324 if error.is::<crate::resume::BeforeQueueWrite>() {
1325 anyhow::Error::new(BeforeEffect(error))
1326 } else {
1327 error
1328 }
1329 })?;
1330 if !pinned {
1331 return Err(anyhow::Error::new(BeforeEffect(anyhow::anyhow!(
1332 "no queued task owns this run"
1333 ))));
1334 }
1335 Ok(format!(
1336 "resume queued for {run}; execution start remains unconfirmed"
1337 ))
1338 })
1339 } else if let Operation::Abandon { run } = &command {
1340 crate::driver::abandon_decision(home, run, id, &request)
1341 .map_err(|error| {
1342 if error.is::<crate::driver::BeforeAbandonWrite>() {
1343 anyhow::Error::new(BeforeEffect(error))
1344 } else {
1345 error
1346 }
1347 })
1348 .map(|()| format!("abandoned run {run}"))
1349 } else if let Some(admission) = merge_admission {
1350 crate::chat_merge::merge_admitted(home, merge.as_ref().unwrap().clone(), admission)
1351 .await
1352 .map_err(|error| {
1353 if error.is::<crate::chat_merge::BeforeMergeWrite>() {
1354 anyhow::Error::new(BeforeEffect(error))
1355 } else {
1356 error
1357 }
1358 })
1359 } else {
1360 Box::pin(execute(queue, home, talks, chat, command)).await
1361 };
1362 match result {
1363 Ok(message) => {
1364 if let Some(action) = &merge {
1365 if let Some(receipt) = merge_receipt(home, chat, action)? {
1366 if receipt["status"] == "merged" {
1367 outbox.update_decision(id, |d| d.applied(&message))?;
1368 } else if receipt["status"] != "pending" {
1369 outbox.update_decision(id, |d| {
1370 d.fail(&format!(
1371 "{message}; reuse this same request ID to reconcile only"
1372 ))
1373 })?;
1374 }
1375 }
1376 } else if !deferred {
1377 outbox.update_decision(id, |d| {
1378 d.applied(&format!("typed command completed: {message}"))
1379 })?;
1380 }
1381 if deferred
1382 && outbox
1383 .get(id)?
1384 .decision
1385 .as_ref()
1386 .is_some_and(|d| d.status == Status::InProgress)
1387 {
1388 outbox.update_decision(id, |d| d.queued())?;
1389 }
1390 Ok(message)
1393 }
1394 Err(error) => {
1395 let message = if error.is::<BeforeEffect>() {
1396 format!(
1397 "{error:#}. No effect began; retry this same request after resolving the cause, or explicitly settle it."
1398 )
1399 } else {
1400 format!(
1401 "Operation failed or has an uncertain result: {error:#}. Inspect its receipt before retrying."
1402 )
1403 };
1404 outbox.update_decision(id, |d| {
1405 if error.is::<BeforeEffect>() {
1406 d.fail_before_effect(&message)
1407 } else {
1408 d.fail(&message)
1409 }
1410 })?;
1411 Err(error)
1412 }
1413 }
1414}
1415
1416#[derive(Debug, thiserror::Error)]
1417#[error("effect did not start: {0:#}")]
1418struct BeforeEffect(anyhow::Error);
1419
1420async fn apply_local_decision(
1424 queue: &Queue,
1425 home: &Path,
1426 id: &str,
1427 request: &str,
1428 owner: &str,
1429 repo: &Path,
1430 command: &Operation,
1431) -> Result<Option<String>> {
1432 let target = match command {
1433 Operation::Done { task, .. }
1434 | Operation::Reopen { task, .. }
1435 | Operation::Hold { task, .. }
1436 | Operation::Release { task }
1437 | Operation::Retry { task, .. } => task,
1438 _ => return Ok(None),
1439 };
1440 let prepare = async {
1441 let (_claim, mut task) = claimed(queue, target)?;
1442 let expected = task.clone();
1443 ensure!(
1444 task.id == owner && task.repo == repo,
1445 "decision ownership changed"
1446 );
1447 if let Some(prior) = task.decision_effects.get(id) {
1448 ensure!(prior == request, "decision receipt binds another command");
1449 let message = format!("task {}: decision {id} already applied", task.id);
1450 return Ok((_claim, task, message, true, None, expected));
1451 }
1452 let mut close_guard = None;
1453 let message = match command {
1454 Operation::Done {
1455 reason,
1456 result,
1457 discard,
1458 ..
1459 } => {
1460 let (guards, context) = crate::task_completion::admit_close(
1461 &task,
1462 home,
1463 crate::queue::CompletionActor::Chat(
1464 crate::task_inquiry::Outbox::at(home)
1465 .get(id)?
1466 .delivered_to
1467 .context("decision has no chat")?,
1468 ),
1469 reason.clone(),
1470 result.clone(),
1471 *discard,
1472 )
1473 .await?;
1474 if !*discard && task.investigation {
1475 task.record_investigation_result(result.as_deref())?;
1476 }
1477 close_guard = Some(guards);
1478 task.succeed(context);
1479 crate::task_completion::describe(&task)
1480 }
1481 Operation::Reopen { reason, .. } => {
1482 let (guards, context) = crate::task_completion::admit_reopen(
1483 &task,
1484 home,
1485 crate::queue::CompletionActor::Chat(
1486 crate::task_inquiry::Outbox::at(home)
1487 .get(id)?
1488 .delivered_to
1489 .context("decision has no chat")?,
1490 ),
1491 reason,
1492 )
1493 .await?;
1494 close_guard = Some(guards);
1495 task.reopen(context)?;
1496 describe(&task, "reopened on hold")
1497 }
1498 Operation::Hold { reason, .. } => {
1499 check_hold_release(&task, "hold")?;
1500 let reason = reason.trim();
1501 task.hold_manual((!reason.is_empty()).then(|| reason.to_owned()));
1502 describe(&task, "held")
1503 }
1504 Operation::Release { .. } => {
1505 check_hold_release(&task, "release")?;
1506 task.release_operator("chat", Some(id));
1507 describe(&task, "released")
1508 }
1509 Operation::Retry {
1510 title, instruction, ..
1511 } => {
1512 ensure!(
1513 !instruction.trim().is_empty(),
1514 "the new instruction is empty"
1515 );
1516 let title = title
1517 .clone()
1518 .unwrap_or_else(|| crate::queue::title_from(instruction, 72));
1519 task.edit(title, instruction.clone())?;
1520 task.release_operator("chat", Some(id));
1521 describe(&task, "retry queued for")
1522 }
1523 _ => unreachable!("task-local operation checked above"),
1524 };
1525 task.decision_effects
1526 .insert(id.to_owned(), request.to_owned());
1527 Ok::<_, anyhow::Error>((_claim, task, message, false, close_guard, expected))
1528 };
1529 let (_claim, mut task, message, already_applied, close_guard, expected) =
1530 prepare.await.map_err(BeforeEffect)?;
1531 if !already_applied {
1532 if close_guard.is_some() {
1533 queue.commit_completion(&mut task, &expected)?;
1534 } else {
1535 queue.put(&mut task)?;
1536 }
1537 }
1538 if matches!(command, Operation::Done { .. }) {
1539 crate::daemon::supersede_prior_runs(&task, home);
1540 }
1541 Ok(Some(message))
1542}
1543
1544fn reconcile_task_decision(queue: &Queue, home: &Path, chat: &str, id: &str) -> Result<()> {
1548 let outbox = crate::task_inquiry::Outbox::at(home);
1549 let inquiry = outbox.get(id)?;
1550 ensure!(
1551 inquiry.delivered_to.as_deref() == Some(chat)
1552 || (inquiry.task.is_empty() && inquiry.delivered_to.is_none()),
1553 "decision belongs to another chat"
1554 );
1555 let decision = inquiry.decision.context("inquiry is informational")?;
1556 if decision.status == crate::task_decision::Status::Resolved {
1557 return Ok(());
1558 }
1559 if decision
1560 .request
1561 .as_ref()
1562 .is_none_or(|request| request.starts_with("decision: "))
1563 {
1564 let source = crate::ask::Questions::at(home.join("questions")).read_history(id)?;
1565 crate::task_chat::sync_effect_receipt(home, queue, &source);
1566 ensure!(
1567 outbox
1568 .get(id)?
1569 .decision
1570 .is_some_and(|d| d.status == crate::task_decision::Status::Resolved),
1571 "source effect remains unconfirmed; no operation was replayed"
1572 );
1573 return Ok(());
1574 }
1575 let request = decision
1576 .request
1577 .context("decision has no accepted operation to reconcile")?;
1578 let command: Operation = serde_json::from_str(&request)?;
1579 if let Operation::Resume { run } = &command {
1580 reconcile_resume_decision(queue, home, &outbox, id, run)?;
1581 ensure!(
1582 outbox.get(id)?.decision.is_some_and(|d| {
1583 d.status == crate::task_decision::Status::Resolved || d.retry_safe
1584 }),
1585 "resume remains queued or executing; no operation was replayed"
1586 );
1587 return Ok(());
1588 }
1589 let (_claim, task) = claimed(queue, &inquiry.task)?;
1590 ensure!(task.repo == inquiry.repo, "decision repository changed");
1591 if let Some(receipt) = task.decision_effects.get(id) {
1592 ensure!(
1593 receipt == &request,
1594 "decision receipt binds another command"
1595 );
1596 return outbox.update_decision(id, |d| {
1597 d.applied("exact task command receipt confirmed; no operation replayed")
1598 });
1599 }
1600 let matches = match command {
1601 Operation::Hold {
1602 task: target,
1603 reason,
1604 } => {
1605 queue.resolve_id(&target)? == task.id
1606 && task.status == TaskStatus::Held
1607 && task.hold_reason.as_deref() == Some(reason.trim())
1608 }
1609 Operation::Release { task: target } => {
1610 queue.resolve_id(&target)? == task.id
1611 && task.status == TaskStatus::Queued
1612 && !task.operator_held()
1613 }
1614 Operation::Done { task: target, .. } => {
1615 queue.resolve_id(&target)? == task.id && task.status == TaskStatus::Done
1616 }
1617 Operation::Retry {
1618 task: target,
1619 title,
1620 instruction,
1621 } => {
1622 queue.resolve_id(&target)? == task.id
1623 && task.instruction == instruction
1624 && title.as_ref().is_none_or(|title| *title == task.title)
1625 && task.status == TaskStatus::Queued
1626 }
1627 Operation::Abandon { run } => abandonment_receipt(home, &task, id, &run, &request)?,
1628 _ => anyhow::bail!(
1629 "external effects require their authoritative receipt; no operation was replayed"
1630 ),
1631 };
1632 ensure!(
1633 matches,
1634 "intended task condition is not confirmed; no operation was replayed"
1635 );
1636 outbox.update_decision(id, |d| d.applied("owner-requested reconciliation: exact intended task condition confirmed under its claim; no effect remains necessary"))
1637}
1638
1639pub(crate) fn resume_started(home: &Path, task: &Task, inquiry: &str, run: &str) -> Result<bool> {
1642 ensure!(
1643 crate::run::is_run_id(run) && task.runs.iter().any(|id| id == run),
1644 "resume run ownership changed"
1645 );
1646 let state = crate::run::RunState::load_under(run, home)?;
1647 ensure!(state.id == run, "resume run identity changed");
1648 ensure!(
1649 crate::git::same_checkout(&state.repo, &task.repo)?,
1650 "resume run repository changed"
1651 );
1652 if task
1653 .superseded_resumes
1654 .get(inquiry)
1655 .is_some_and(|target| target == run)
1656 {
1657 return Ok(true);
1658 }
1659 Ok(state.decision_starts.get(inquiry).is_some_and(|index| {
1660 state
1661 .passes
1662 .get(*index)
1663 .is_some_and(|pass| pass.index == *index)
1664 }))
1665}
1666
1667fn reconcile_resume_decision(
1671 queue: &Queue,
1672 home: &Path,
1673 outbox: &crate::task_inquiry::Outbox,
1674 id: &str,
1675 run: &str,
1676) -> Result<()> {
1677 let Ok(_execution) = outbox.execution_claim(id) else {
1678 return Ok(());
1679 };
1680 reconcile_resume_claimed(queue, home, outbox, id, run)
1681}
1682
1683fn reconcile_resume_claimed(
1685 queue: &Queue,
1686 home: &Path,
1687 outbox: &crate::task_inquiry::Outbox,
1688 id: &str,
1689 run: &str,
1690) -> Result<()> {
1691 let inquiry = outbox.get(id)?;
1692 let Ok(_claim) = queue.claim(&inquiry.task) else {
1693 return Ok(());
1694 };
1695 let task = queue.get(&inquiry.task)?;
1696 ensure!(task.repo == inquiry.repo, "resume task repository changed");
1697 let decision = inquiry.decision.context("inquiry is informational")?;
1698 if decision.status == crate::task_decision::Status::Resolved {
1699 return Ok(());
1700 }
1701 if resume_started(home, &task, id, run)? {
1702 outbox.update_decision(id, |d| {
1703 d.applied("exact resume execution-start or supersession receipt confirmed")
1704 })?;
1705 } else if !task.action_applied(id)
1706 && !task.dispatched_resumes.contains_key(id)
1707 && !task.superseded_resumes.contains_key(id)
1708 && !task
1709 .resume_override
1710 .as_ref()
1711 .is_some_and(|pin| pin.question_id == id)
1712 {
1713 outbox.update_decision(id, |d| {
1714 d.fail_before_effect("Resume was not published to the queue; the owner may retry the same request or cancel it. No operation was replayed.")
1715 })?;
1716 }
1717 Ok(())
1718}
1719
1720fn abandonment_receipt(
1721 home: &Path,
1722 task: &Task,
1723 id: &str,
1724 run: &str,
1725 request: &str,
1726) -> Result<bool> {
1727 ensure!(
1728 task.runs.iter().any(|own| own == run),
1729 "abandon run ownership changed"
1730 );
1731 let state = crate::run::RunState::load_under(run, home)?;
1732 ensure!(state.id == run, "abandon run identity changed");
1733 ensure!(
1734 crate::git::same_checkout(&state.repo, &task.repo)?,
1735 "abandon run repository changed"
1736 );
1737 Ok(state
1738 .abandonment_receipts
1739 .get(id)
1740 .is_some_and(|receipt| receipt == request))
1741}
1742
1743fn merge_receipt(
1744 home: &Path,
1745 chat: &str,
1746 action: &crate::chat_merge::Request,
1747) -> Result<Option<serde_json::Value>> {
1748 ensure!(
1749 crate::ask::valid_asset_name(chat) && crate::ask::valid_asset_name(&action.request),
1750 "invalid merge receipt identity"
1751 );
1752 let path = home
1753 .join("chat-controls")
1754 .join(chat)
1755 .join(format!("{}.json", action.request));
1756 let bytes = match std::fs::read(path) {
1757 Ok(bytes) => bytes,
1758 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
1759 Err(error) => return Err(error.into()),
1760 };
1761 let receipt: serde_json::Value = serde_json::from_slice(&bytes)?;
1762 ensure!(
1763 receipt["action"] == serde_json::to_value(action)?,
1764 "merge receipt names another operation"
1765 );
1766 Ok(Some(receipt))
1767}
1768
1769#[derive(Debug, PartialEq, Eq)]
1770struct ApprovalEvidence {
1771 target: crate::merge_decision::Target,
1772 terminal: bool,
1773 successor: Option<(String, String)>,
1774}
1775
1776impl ApprovalEvidence {
1777 fn obsolete_reason(&self, state: &str, head: &str) -> Option<String> {
1778 if self.terminal
1779 && let Some(reason) = obsolete_pr_reason(state, head, &self.target)
1780 {
1781 return Some(reason);
1782 }
1783 let (question, successor_head) = self.successor.as_ref()?;
1784 if state == "OPEN" && head == successor_head && head != self.target.head {
1785 return Some(format!(
1786 "Obsolete: approval for {} at {} was retired in favor of inquiry {question} at {head}",
1787 self.target.pr, self.target.head
1788 ));
1789 }
1790 None
1791 }
1792}
1793
1794fn approval_target(
1796 home: &Path,
1797 queue: &Queue,
1798 inquiry: &crate::task_inquiry::Inquiry,
1799) -> Option<ApprovalEvidence> {
1800 use crate::task_decision::Status;
1801 let decision = inquiry.decision.as_ref()?;
1802 if decision.status == Status::Resolved || inquiry.task.is_empty() {
1803 return None;
1804 }
1805 let task = queue.get(&inquiry.task).ok()?;
1806 if task.id != inquiry.task || task.repo != inquiry.repo {
1807 return None;
1808 }
1809 let run_id = inquiry.run.as_ref()?;
1810 if !task.execution_runs().contains(run_id) {
1811 return None;
1812 }
1813 let q = crate::ask::Questions::at(home.join("questions"))
1814 .read_history(&inquiry.id)
1815 .ok()?;
1816 if inquiry.key != format!("question:{}", q.id)
1817 || q.node != crate::land::APPROVAL_NODE
1818 || q.run != *run_id
1819 || q.legacy_foreground
1820 || q.routed_task.as_ref().is_some_and(|id| id != &task.id)
1821 || crate::task_chat::task_of(&q, &queue.list()).as_ref() != Some(&task.id)
1822 {
1823 return None;
1824 }
1825 let no_reply = q.answer.is_none()
1826 || (q.resolution().as_deref() == Some(crate::land::APPROVE)
1827 && crate::task_chat::migration_sources(home)
1828 .is_ok_and(|ids| ids.is_some_and(|ids| ids.contains(&q.id)))
1829 && crate::task_chat::source_reply_needs_confirmation(home, &q));
1830 let target = q.merge_target.clone()?;
1831 let run = crate::run::RunState::load_under(run_id, home).ok()?;
1832 if run.id != *run_id
1833 || run.repo != task.repo
1834 || !task.assignment_accepts(&run)
1835 || run
1836 .origin
1837 .as_ref()
1838 .and_then(|o| o.task.as_ref())
1839 .is_some_and(|id| id != &task.id)
1840 || target.head.is_empty()
1841 || !run.pr.as_ref().is_some_and(|pr| pr.url == target.pr)
1842 || run.pr_publication_pending
1843 {
1844 return None;
1845 }
1846 let safe_retry = decision.retry_safe
1847 && decision.request.as_deref() == Some("decision: merge")
1848 && q.resolution().as_deref() == Some(crate::land::APPROVE)
1849 && decision.source_answer_at.is_some()
1850 && decision.source_answer_at == q.answered_at;
1851 let unstarted = ((decision.request.is_none() && no_reply) || safe_retry)
1852 && !task.blocked_by.contains(&q.id)
1853 && task.status != TaskStatus::Held;
1854 let terminal = unstarted
1855 && task.status == TaskStatus::Done
1856 && matches!(
1857 run.status,
1858 crate::run::RunStatus::Merged | crate::run::RunStatus::Ready
1859 );
1860 let successor = if unstarted && q.status == crate::ask::QuestionStatus::Abandoned {
1861 superseding_approval(home, inquiry, &run, &target)
1862 } else {
1863 None
1864 };
1865 Some(ApprovalEvidence {
1866 target,
1867 terminal,
1868 successor,
1869 })
1870}
1871
1872fn superseding_approval(
1873 home: &Path,
1874 old: &crate::task_inquiry::Inquiry,
1875 run: &crate::run::RunState,
1876 target: &crate::merge_decision::Target,
1877) -> Option<(String, String)> {
1878 let binding = run.land_approval.as_ref()?;
1879 if binding.question == old.id || binding.head == target.head {
1880 return None;
1881 }
1882 let q = crate::ask::Questions::at(home.join("questions"))
1883 .read_history(&binding.question)
1884 .ok()?;
1885 if q.run != run.id
1886 || q.node != crate::land::APPROVAL_NODE
1887 || !q.status.open()
1888 || q.routed_task.as_ref().is_some_and(|task| task != &old.task)
1889 || !q
1890 .merge_target
1891 .as_ref()
1892 .is_some_and(|next| next.pr == target.pr && next.head == binding.head)
1893 {
1894 return None;
1895 }
1896 let next = crate::task_inquiry::Outbox::at(home).get(&q.id).ok()?;
1897 if next.task != old.task
1898 || next.repo != old.repo
1899 || next.run != old.run
1900 || next.key != format!("question:{}", q.id)
1901 || next
1902 .decision
1903 .as_ref()
1904 .is_none_or(|d| d.status == crate::task_decision::Status::Resolved)
1905 {
1906 return None;
1907 }
1908 Some((binding.question.clone(), binding.head.clone()))
1909}
1910
1911pub(crate) async fn retire_obsolete_decisions(queue: &Queue, home: &Path) -> Result<()> {
1914 retire_obsolete_with(queue, home, |repo, pr| async move {
1915 observe_decision_pr(&repo, &pr).await
1916 })
1917 .await
1918}
1919
1920#[derive(serde::Serialize, serde::Deserialize)]
1921struct DecisionCursor {
1922 cursor: String,
1923 high_water: String,
1924}
1925
1926async fn retire_obsolete_with<F, Fut>(queue: &Queue, home: &Path, mut observe: F) -> Result<()>
1927where
1928 F: FnMut(std::path::PathBuf, String) -> Fut,
1929 Fut: Future<Output = Option<(String, String)>>,
1930{
1931 let outbox = crate::task_inquiry::Outbox::at(home);
1932 let (mut items, _) = outbox.list_readable()?;
1933 items.retain(|i| {
1934 i.decision
1935 .as_ref()
1936 .is_some_and(|d| d.status != crate::task_decision::Status::Resolved)
1937 });
1938 items.sort_by(|a, b| a.id.cmp(&b.id));
1939 let cursor_path = home.join("decision-reconcile-cursor");
1940 let Some(last) = items.last() else {
1941 return Ok(());
1942 };
1943 let fresh = || DecisionCursor {
1944 cursor: String::new(),
1945 high_water: last.id.clone(),
1946 };
1947 let mut cycle = std::fs::read(&cursor_path)
1948 .ok()
1949 .and_then(|body| serde_json::from_slice::<DecisionCursor>(&body).ok())
1950 .filter(|c| c.cursor <= c.high_water)
1951 .unwrap_or_else(fresh);
1952 let range = |cycle: &DecisionCursor| {
1953 items.partition_point(|i| i.id <= cycle.cursor)
1954 ..items.partition_point(|i| i.id <= cycle.high_water)
1955 };
1956 if range(&cycle).is_empty() {
1957 cycle = fresh();
1958 }
1959 let range = range(&cycle);
1960 let mut observations = std::collections::BTreeMap::new();
1961 for inquiry in items[range].iter().take(32) {
1962 if let Some(evidence) = approval_target(home, queue, inquiry) {
1963 let target = evidence.target;
1964 let key = (inquiry.repo.clone(), target.pr.clone());
1965 if !observations.contains_key(&key) {
1966 if observations.len() == 5 {
1967 break;
1968 }
1969 let result = observe(key.0.clone(), key.1.clone()).await;
1970 observations.insert(key.clone(), result);
1971 }
1972 if let Ok(_execution) = outbox.execution_claim(&inquiry.id)
1973 && let Ok(_claim) = queue.claim(&inquiry.task)
1974 && let Ok(_task_write) = queue.lock_task(&inquiry.task)
1975 && let Some(run) = &inquiry.run
1976 && let Ok(_owner) = crate::pr_head::owner_lock(home, run)
1977 {
1978 let questions = crate::ask::Questions::at(home.join("questions"));
1979 if let Err(error) = questions.try_inspect_history(&inquiry.id, || {
1980 let current = outbox.get(&inquiry.id)?;
1981 if current != *inquiry {
1982 return Ok(());
1983 }
1984 let Some(current_evidence) = approval_target(home, queue, ¤t) else {
1985 return Ok(());
1986 };
1987 if current_evidence.target != target {
1988 return Ok(());
1989 }
1990 let observed = observations.get(&key).and_then(Option::as_ref);
1991 let observation = target_observation(&target, observed);
1992 let reason = observed
1993 .and_then(|(state, head)| current_evidence.obsolete_reason(state, head));
1994 outbox.try_update_decision(&inquiry.id, |d| {
1995 if current.decision.as_ref() != Some(d) {
1996 return Ok(false);
1997 }
1998 let changed = d.observe(observation);
1999 if let Some(reason) = reason {
2000 return Ok(d.retire_target(&reason)? || changed);
2001 }
2002 Ok(changed)
2003 })
2004 }) {
2005 tracing::debug!("decision {} reconciliation deferred: {error:#}", inquiry.id);
2006 }
2007 }
2008 }
2009 let temporary = cursor_path.with_extension("tmp");
2010 cycle.cursor.clone_from(&inquiry.id);
2011 std::fs::write(&temporary, serde_json::to_vec(&cycle)?)?;
2012 std::fs::rename(temporary, &cursor_path)?;
2013 }
2014 Ok(())
2015}
2016
2017async fn observe_decision_pr(repo: &Path, pr: &str) -> Option<(String, String)> {
2018 let mut command = tokio::process::Command::new("gh");
2019 command
2020 .args(["pr", "view", pr, "--json", "url,state,headRefOid"])
2021 .current_dir(repo)
2022 .env_remove("GH_REPO")
2023 .stdin(std::process::Stdio::null())
2024 .kill_on_drop(true);
2025 let output = tokio::time::timeout(std::time::Duration::from_secs(5), command.output())
2026 .await
2027 .ok()?
2028 .ok()?;
2029 if !output.status.success() {
2030 return None;
2031 }
2032 let snapshot: serde_json::Value = serde_json::from_slice(&output.stdout).ok()?;
2033 let head = snapshot["headRefOid"].as_str()?;
2034 if snapshot["url"].as_str()? != pr || head.is_empty() {
2035 return None;
2036 }
2037 Some((snapshot["state"].as_str()?.to_owned(), head.to_owned()))
2038}
2039
2040fn target_observation(
2041 target: &crate::merge_decision::Target,
2042 observed: Option<&(String, String)>,
2043) -> crate::task_decision::TargetObservation {
2044 use crate::task_decision::{TargetObservation, TargetState};
2045 let state = match observed.map(|(state, _)| state.as_str()) {
2046 Some("OPEN") => TargetState::Open,
2047 Some("MERGED") => TargetState::Merged,
2048 Some("CLOSED") => TargetState::Closed,
2049 _ => TargetState::Unknown,
2050 };
2051 TargetObservation {
2052 pr: target.pr.clone(),
2053 target_head: target.head.clone(),
2054 head: observed.map(|(_, head)| head.clone()),
2055 state,
2056 }
2057}
2058
2059fn obsolete_pr_reason(
2060 state: &str,
2061 head: &str,
2062 target: &crate::merge_decision::Target,
2063) -> Option<String> {
2064 let outcome = match state {
2065 "MERGED" if head == target.head => "merged at the requested head",
2066 "MERGED" => "merged at a different head",
2067 _ => return None,
2068 };
2069 Some(format!(
2070 "Obsolete: {} is {outcome} (observed head {head}); no approval effect remains. This does not confirm application of a request.",
2071 target.pr
2072 ))
2073}
2074
2075#[cfg(test)]
2076#[test]
2077fn obsolete_pr_requires_terminal_forge_state() {
2078 let target = crate::merge_decision::Target {
2079 pr: "https://github.com/example/project/pull/42".into(),
2080 head: "old-head".into(),
2081 language: "en".into(),
2082 };
2083 assert!(obsolete_pr_reason("OPEN", "new-head", &target).is_none());
2084 assert!(obsolete_pr_reason("UNKNOWN", "old-head", &target).is_none());
2085 assert!(
2086 obsolete_pr_reason("MERGED", "old-head", &target)
2087 .unwrap()
2088 .contains("requested head")
2089 );
2090 assert!(
2091 obsolete_pr_reason("MERGED", "new-head", &target)
2092 .unwrap()
2093 .contains("different head")
2094 );
2095 assert!(obsolete_pr_reason("CLOSED", "old-head", &target).is_none());
2096}
2097
2098#[cfg(test)]
2099#[tokio::test]
2100async fn obsolete_approval_needs_original_run_and_unaccepted_source() {
2101 use crate::{
2102 ask::{Question, Questions},
2103 queue::Source,
2104 run::{RunState, RunStatus},
2105 };
2106 let tmp = tempfile::tempdir().unwrap();
2107 let home = tmp.path();
2108 let queue = Queue::at(home.join("queue"));
2109 let mut task = Task::new("work".into(), "work".into(), home.into(), Source::Human);
2110 task.status = TaskStatus::Done;
2111 queue.put(&mut task).unwrap();
2112 let mut run = RunState::new(
2113 home.into(),
2114 "main".into(),
2115 "base".into(),
2116 "work".into(),
2117 crate::config::Config::default(),
2118 );
2119 run.reserve_under(home).unwrap();
2120 let mut q = Question::new(
2121 run.id.clone(),
2122 crate::land::APPROVAL_NODE.into(),
2123 "land".into(),
2124 "Merge?".into(),
2125 String::new(),
2126 vec!["merge".into()],
2127 );
2128 let target = crate::merge_decision::Target {
2129 pr: "https://github.com/example/project/pull/42".into(),
2130 head: "old-head".into(),
2131 language: "en".into(),
2132 };
2133 q.merge_target = Some(target.clone());
2134 Questions::at(home.join("questions")).put(&mut q).unwrap();
2135 task.runs.push(run.id.clone());
2136 queue.put(&mut task).unwrap();
2137 let mut inquiry = crate::task_chat::live_record(home, &task, &q);
2138 assert!(approval_target(home, &queue, &inquiry).is_none());
2139 run.status = RunStatus::Merged;
2140 run.pr = Some(crate::run::PrRecord {
2141 url: target.pr.clone(),
2142 number: 42,
2143 state: "merged".into(),
2144 checks: "green".into(),
2145 round: 1,
2146 rounds: 1,
2147 red_at_merge: vec![],
2148 });
2149 run.save_under(home).unwrap();
2150 assert_eq!(
2151 approval_target(home, &queue, &inquiry),
2152 Some(ApprovalEvidence {
2153 target: target.clone(),
2154 terminal: true,
2155 successor: None
2156 })
2157 );
2158 let outbox = crate::task_inquiry::Outbox::at(home);
2159 let id = inquiry.id.clone();
2160 outbox.enqueue(inquiry.clone()).unwrap();
2161 retire_obsolete_with(&queue, home, |_, _| async { None })
2162 .await
2163 .unwrap();
2164 let observed = outbox.get(&id).unwrap().decision.unwrap();
2165 assert_eq!(
2166 observed.attention(false),
2167 crate::task_decision::Attention::ReceiptCheck
2168 );
2169 assert_ne!(observed.status, crate::task_decision::Status::Resolved);
2170 retire_obsolete_with(&queue, home, |_, _| async {
2171 Some(("CLOSED".into(), "old-head".into()))
2172 })
2173 .await
2174 .unwrap();
2175 let closed = outbox.get(&id).unwrap().decision.unwrap();
2176 assert_eq!(
2177 closed.attention(false),
2178 crate::task_decision::Attention::StaleTarget
2179 );
2180 assert!(!closed.source_retired);
2181 retire_obsolete_with(&queue, home, |_, _| async {
2182 Some(("OPEN".into(), "old-head".into()))
2183 })
2184 .await
2185 .unwrap();
2186 let reopened = outbox.get(&id).unwrap().decision.unwrap();
2187 assert_eq!(
2188 reopened.attention(false),
2189 crate::task_decision::Attention::OwnerChoice
2190 );
2191 assert!(!reopened.source_retired);
2192 retire_obsolete_with(&queue, home, |_, _| async {
2193 Some(("OPEN".into(), "new-head".into()))
2194 })
2195 .await
2196 .unwrap();
2197 let observed = outbox.get(&id).unwrap().decision.unwrap();
2198 assert_eq!(
2199 observed.attention(false),
2200 crate::task_decision::Attention::StaleTarget
2201 );
2202 assert_ne!(observed.status, crate::task_decision::Status::Resolved);
2203 let claim = outbox.execution_claim(&id).unwrap();
2204 retire_obsolete_with(&queue, home, |_, _| async {
2205 Some(("MERGED".into(), "new-head".into()))
2206 })
2207 .await
2208 .unwrap();
2209 assert_eq!(outbox.get(&id).unwrap().decision.unwrap(), observed);
2210 drop(claim);
2211 let question_lock = home.join("questions").join(format!("{id}.lock"));
2212 let leftover = std::fs::File::create(&question_lock).unwrap();
2213 retire_obsolete_with(&queue, home, |_, _| async {
2214 Some(("MERGED".into(), "new-head".into()))
2215 })
2216 .await
2217 .unwrap();
2218 assert_eq!(outbox.get(&id).unwrap().decision.unwrap(), observed);
2219 leftover
2220 .set_modified(std::time::SystemTime::now() - std::time::Duration::from_secs(60))
2221 .unwrap();
2222 drop(leftover);
2223 retire_obsolete_with(&Queue::at(home.join("queue")), home, |_, _| async {
2224 Some(("MERGED".into(), "new-head".into()))
2225 })
2226 .await
2227 .unwrap();
2228 let retired = outbox.get(&id).unwrap().decision.unwrap();
2229 assert_eq!(
2230 retired.closure,
2231 Some(crate::task_decision::Closure::Obsolete)
2232 );
2233 assert!(retired.source_retired);
2234 assert!(!question_lock.exists());
2235 assert!(
2236 Questions::at(home.join("questions"))
2237 .read_history(&q.id)
2238 .unwrap()
2239 .answer
2240 .is_none()
2241 );
2242 let questions = crate::ask::Questions::at(home.join("questions"));
2243 assert!(
2244 questions
2245 .update(&q.id, |q| q
2246 .answer(crate::ask::Answer::Choice("merge".into())))
2247 .is_err()
2248 );
2249 retire_obsolete_with(&queue, home, |_, _| async {
2250 panic!("resolved inquiry was queried again")
2251 })
2252 .await
2253 .unwrap();
2254 assert_eq!(outbox.get(&id).unwrap().decision.unwrap(), retired);
2255 inquiry
2256 .decision
2257 .as_mut()
2258 .unwrap()
2259 .accept("decision: merge")
2260 .unwrap();
2261 assert_eq!(
2262 approval_target(home, &queue, &inquiry),
2263 Some(ApprovalEvidence {
2264 target: target.clone(),
2265 terminal: false,
2266 successor: None
2267 })
2268 );
2269 let replacement = ApprovalEvidence {
2270 target: target.clone(),
2271 terminal: false,
2272 successor: Some(("successor".into(), "new-head".into())),
2273 };
2274 assert!(replacement.obsolete_reason("OPEN", "other-head").is_none());
2275 assert!(replacement.obsolete_reason("UNKNOWN", "new-head").is_none());
2276 assert!(
2277 replacement
2278 .obsolete_reason("OPEN", "new-head")
2279 .unwrap()
2280 .contains("successor")
2281 );
2282 let mut legacy = None;
2285 for index in 0..34 {
2286 let mut source = q.clone();
2287 source.id = format!("approval-{index:02}");
2288 if index == 1 {
2289 source
2290 .answer(crate::ask::Answer::Choice("merge".into()))
2291 .unwrap();
2292 legacy = Some(source.id.clone());
2293 }
2294 if index == 33 {
2295 source.merge_target = None;
2296 }
2297 questions.put(&mut source).unwrap();
2298 let mut record = crate::task_chat::live_record(home, &task, &source);
2299 if index == 0 {
2300 record
2301 .decision
2302 .as_mut()
2303 .unwrap()
2304 .accept("decision: merge")
2305 .unwrap();
2306 }
2307 if index == 1 {
2308 record
2309 .decision
2310 .as_mut()
2311 .unwrap()
2312 .fail("historical response has no receipt")
2313 .unwrap();
2314 }
2315 outbox.enqueue(record).unwrap();
2316 }
2317 let journal = home.join("notifications/task-chat-migration-v1");
2318 std::fs::create_dir_all(&journal).unwrap();
2319 std::fs::write(
2320 journal.join("state.json"),
2321 serde_json::to_vec(&serde_json::json!({
2322 "schema": 1, "pending": [], "sources": [legacy.unwrap()]
2323 }))
2324 .unwrap(),
2325 )
2326 .unwrap();
2327 let calls = std::cell::Cell::new(0);
2328 let observe = |_, _| {
2329 calls.set(calls.get() + 1);
2330 async { Some(("MERGED".into(), "old-head".into())) }
2331 };
2332 retire_obsolete_with(&queue, home, observe).await.unwrap();
2333 assert_eq!(calls.get(), 1);
2334 assert_eq!(
2335 outbox
2336 .list_readable()
2337 .unwrap()
2338 .0
2339 .iter()
2340 .filter(|i| i
2341 .decision
2342 .as_ref()
2343 .is_some_and(|d| d.status != crate::task_decision::Status::Resolved))
2344 .count(),
2345 3
2346 );
2347 retire_obsolete_with(&Queue::at(home.join("queue")), home, observe)
2348 .await
2349 .unwrap();
2350 assert_eq!(calls.get(), 2);
2351 let pending = outbox
2352 .list_readable()
2353 .unwrap()
2354 .0
2355 .into_iter()
2356 .filter(|i| {
2357 i.decision
2358 .as_ref()
2359 .is_some_and(|d| d.status != crate::task_decision::Status::Resolved)
2360 })
2361 .map(|i| i.id)
2362 .collect::<std::collections::BTreeSet<_>>();
2363 assert_eq!(
2364 pending,
2365 ["approval-00".into(), "approval-33".into()]
2366 .into_iter()
2367 .collect()
2368 );
2369 let legacy = questions.read_history("approval-01").unwrap();
2370 assert_eq!(legacy.resolution().as_deref(), Some("merge"));
2371 assert!(questions.held_reply("approval-01"));
2372 assert_eq!(
2373 outbox.get("approval-01").unwrap().decision.unwrap().closure,
2374 Some(crate::task_decision::Closure::Obsolete)
2375 );
2376}
2377
2378pub fn reconcile_decisions(queue: &Queue, home: &Path) -> Result<()> {
2381 let outbox = crate::task_inquiry::Outbox::at(home);
2382 let (inquiries, unreadable) = outbox.list_readable()?;
2383 let mut errors = Vec::new();
2384 if unreadable != 0 {
2385 errors.push(format!("{unreadable} unreadable inquiry record(s)"));
2386 }
2387 for inquiry in inquiries {
2388 let id = inquiry.id.clone();
2389 let task_id = inquiry.task.clone();
2390 let before = inquiry.decision.clone();
2391 if let Err(error) = reconcile_inquiry(queue, home, &outbox, inquiry) {
2392 let message = format!(
2393 "Decision receipt reconciliation failed: {error:#}. Inspect this inquiry's receipt before retrying."
2394 );
2395 tracing::warn!("decision {id}: {message}");
2396 if let Ok(_execution) = outbox.execution_claim(&id)
2399 && let Ok(_claim) = queue.claim(&task_id)
2400 && let Err(error) = outbox.try_update_decision(&id, |d| {
2401 if before.as_ref() != Some(d)
2402 || d.status == crate::task_decision::Status::Resolved
2403 {
2404 return Ok(false);
2405 }
2406 if d.retry_safe {
2407 return d.fail_before_effect(&message);
2408 }
2409 d.fail(&message)
2410 })
2411 {
2412 tracing::warn!(
2413 "decision {id} reconciliation error persistence deferred: {error:#}"
2414 );
2415 }
2416 errors.push(format!("{id}: {message}"));
2417 }
2418 }
2419 ensure!(
2420 errors.is_empty(),
2421 "{} decision reconciliation problem(s): {}",
2422 errors.len(),
2423 errors.join("; ")
2424 );
2425 Ok(())
2426}
2427
2428fn reconcile_inquiry(
2429 queue: &Queue,
2430 home: &Path,
2431 outbox: &crate::task_inquiry::Outbox,
2432 inquiry: crate::task_inquiry::Inquiry,
2433) -> Result<()> {
2434 use crate::task_decision::Status;
2435 let Some(decision) = inquiry.decision else {
2436 return Ok(());
2437 };
2438 if decision.status == Status::Resolved {
2439 return Ok(());
2440 }
2441 let Some(request) = decision.request else {
2442 return Ok(());
2443 };
2444 let Ok(command) = serde_json::from_str::<Operation>(&request) else {
2445 return Ok(());
2446 };
2447 if let Operation::Resume { run } = &command {
2448 return reconcile_resume_decision(queue, home, outbox, &inquiry.id, run);
2449 }
2450 let Ok(_execution) = outbox.execution_claim(&inquiry.id) else {
2451 return Ok(());
2452 };
2453 let Ok(_claim) = queue.claim(&inquiry.task) else {
2454 return Ok(());
2455 };
2456 let current = outbox.get(&inquiry.id)?;
2457 let Some(decision) = current.decision else {
2458 return Ok(());
2459 };
2460 if decision.status == Status::Resolved || decision.request.as_ref() != Some(&request) {
2461 return Ok(());
2462 }
2463 let task = queue.get(&inquiry.task)?;
2464 ensure!(task.repo == inquiry.repo, "decision repository changed");
2465 if let Some(receipt) = task.decision_effects.get(&inquiry.id) {
2466 ensure!(
2467 receipt == &request,
2468 "decision receipt binds another command"
2469 );
2470 outbox.update_decision(&inquiry.id, |d| {
2471 d.applied("exact task command receipt confirmed after restart")
2472 })?;
2473 return Ok(());
2474 }
2475 let mut pending_external = false;
2476 let receipt = match command {
2477 Operation::Abandon { run } => {
2478 abandonment_receipt(home, &task, &inquiry.id, &run, &request)?
2479 .then(|| format!("run {run}: exact abandonment receipt committed"))
2480 }
2481 Operation::RerunChecks {
2482 request,
2483 run,
2484 head,
2485 workflows,
2486 } => {
2487 let chat = inquiry.delivered_to.as_deref().unwrap_or_default();
2488 let path = home
2489 .join("chat-controls")
2490 .join(chat)
2491 .join(format!("{request}.json"));
2492 let state = crate::run::RunState::load_under(&run, home)?;
2493 let action = serde_json::json!({
2494 "run": run, "repo": state.repo,
2495 "pr": state.pr.as_ref().map(|pr| pr.url.as_str()),
2496 "head": head, "runs": workflows,
2497 });
2498 std::fs::read(path)
2499 .ok()
2500 .and_then(|bytes| serde_json::from_slice::<serde_json::Value>(&bytes).ok())
2501 .filter(|receipt| receipt["status"] == "applied" && receipt["action"] == action)
2502 .map(|_| format!("chat-controls/{chat}/{request}.json: applied"))
2503 }
2504 Operation::MergePr {
2505 repo,
2506 number,
2507 head,
2508 request,
2509 } => {
2510 let action = crate::chat_merge::Request {
2511 repo,
2512 number,
2513 head,
2514 request,
2515 };
2516 let chat = inquiry
2517 .delivered_to
2518 .as_deref()
2519 .context("merge decision has no chat")?;
2520 let receipt = merge_receipt(home, chat, &action)?;
2521 pending_external = receipt
2522 .as_ref()
2523 .is_some_and(|receipt| receipt["status"] == "pending");
2524 if let Some(receipt) = &receipt
2525 && receipt["status"] != "merged"
2526 && receipt["status"] != "pending"
2527 {
2528 outbox.update_decision(&inquiry.id, |d| d.fail(&format!("Merge outcome requires reconciliation: {}. Reuse the same request ID to check only.", receipt["detail"])))?;
2529 }
2530 receipt
2531 .filter(|receipt| receipt["status"] == "merged")
2532 .map(|receipt| format!("confirmed merge receipt: {}", receipt["detail"]))
2533 }
2534 _ => None,
2535 };
2536 if let Some(receipt) = receipt {
2537 outbox.update_decision(&inquiry.id, |d| d.applied(&receipt))?;
2538 } else if decision.status == Status::InProgress
2539 && !pending_external
2540 && outbox
2541 .get(&inquiry.id)?
2542 .decision
2543 .as_ref()
2544 .is_some_and(|d| d.status == Status::InProgress)
2545 {
2546 let talks = Talks::at(home.join("talks"));
2547 let chat = inquiry
2548 .delivered_to
2549 .as_deref()
2550 .context("executing decision has no chat")?;
2551 if !talks.turn_held(chat) && !crate::chat_worker::turn_worker_active(&talks, chat) {
2552 outbox.update_decision(&inquiry.id, |d| d.fail("Execution ended without a confirmed effect receipt. Inspect the operation before retrying; restart did not replay it."))?;
2553 }
2554 }
2555 Ok(())
2556}
2557
2558pub fn decide(
2562 talks: &Talks,
2563 home: &Path,
2564 talk: &str,
2565 question: &str,
2566 choice: &str,
2567) -> Result<crate::ask::Question> {
2568 authorize(talks, talk, crate::queue::CHAT_NODE)?;
2569 record_decision(home, question, choice, None)
2570}
2571
2572fn record_decision(
2578 home: &Path,
2579 question: &str,
2580 choice: &str,
2581 title: Option<&str>,
2582) -> Result<crate::ask::Question> {
2583 use crate::ask::{Answer, Questions};
2584 let questions = Questions::at(home.join("questions"));
2585 let id = questions.resolve_id(question)?;
2586 let q = questions.get(&id)?;
2587 let queue = Queue::at(home.join("queue"));
2588 let _claims = decision_claims(&queue, &q)?;
2589 for task in queue.list() {
2590 if q.run == task.id
2591 || task.runs.contains(&q.run)
2592 || q.routed_task.as_deref() == Some(&task.id)
2593 {
2594 ensure!(
2595 !task.stale_question(&q),
2596 "question predates task repository reassignment; inspect the current task and release it for fresh execution"
2597 );
2598 }
2599 }
2600 ensure!(
2601 crate::task_chat::awaits_decision(&q),
2602 "question {} is not a decision the machinery waits on; answer it with `magi answer`",
2603 q.short()
2604 );
2605 let (q, ()) = questions.update(&q.id, |r| {
2606 if crate::task_chat::saved_reply_requires_confirmation(home, r) {
2607 ensure!(
2608 crate::task_inquiry::Outbox::at(home)
2609 .get(&r.id)?
2610 .decision
2611 .is_some_and(
2612 |decision| decision.status != crate::task_decision::Status::Resolved
2613 ),
2614 "saved decision is settled; no effect remains necessary"
2615 );
2616 r.status = crate::ask::QuestionStatus::Open;
2617 r.answer = None;
2618 r.answered_at = None;
2619 r.answer_authority = None;
2620 }
2621 ensure!(
2622 r.status.open(),
2623 "question {} is already {}",
2624 r.short(),
2625 r.status.as_str()
2626 );
2627 let reply = r.resolve_reply(choice)?.to_owned();
2628 ensure!(
2629 crate::land::approval(Some(&reply)) != crate::land::Approval::Merge || r.merge_target.is_some()
2630 || !(r.node == crate::land::APPROVAL_NODE || (r.node == crate::bump::NOTICE_NODE && r.seat == "release-watch")),
2631 "approval has no recorded PR/head; recover its target or discuss a non-merge operation in chat"
2632 );
2633 let replacement =
2634 r.node == crate::github_text::ASK_NODE && reply == crate::github_text::USE_MY_TEXT;
2635 ensure!(
2636 replacement || title.is_none(),
2637 "--title is only valid for a publication decision's `use my text` choice"
2638 );
2639 let title = if replacement {
2640 let title =
2641 title.context("use my text needs --title with the literal replacement title")?;
2642 ensure!(
2643 !title.trim().is_empty(),
2644 "replacement title must not be empty"
2645 );
2646 Some(title.to_owned())
2647 } else {
2648 None
2649 };
2650 let answer = if r.free_text() {
2651 Answer::Text(reply)
2652 } else {
2653 Answer::Choice(reply)
2654 };
2655 r.publication_title = title;
2656 r.answer(answer)?;
2657 Ok(())
2658 })?;
2659 Ok(q)
2660}
2661
2662pub(crate) fn decision_claims(
2667 queue: &Queue,
2668 q: &crate::ask::Question,
2669) -> Result<Vec<crate::queue::Claim>> {
2670 let mut owners: Vec<_> = queue
2671 .list()
2672 .into_iter()
2673 .filter(|task| {
2674 q.run == task.id
2675 || task.runs.contains(&q.run)
2676 || q.routed_task.as_deref() == Some(&task.id)
2677 })
2678 .map(|task| task.id)
2679 .collect();
2680 owners.sort();
2681 let mut claims = Vec::new();
2682 if matches!(
2683 q.node.as_str(),
2684 crate::triage::NODE | crate::triage::DEPS_NODE
2685 ) {
2686 for id in &owners {
2687 if queue.get(id)?.status != TaskStatus::Running {
2688 claims.push(queue.claim(id)?);
2689 }
2690 }
2691 }
2692 for id in owners {
2693 ensure!(
2694 !crate::repair_budget::reconcile::superseded_question(&queue.get(&id)?, q),
2695 "question was superseded by explicit repair receipt recovery; inspect the reconciliation receipt"
2696 );
2697 }
2698 Ok(claims)
2699}
2700
2701pub fn authorize(talks: &Talks, run: &str, node: &str) -> Result<Talk> {
2703 if node != crate::queue::CHAT_NODE || run.trim().is_empty() {
2704 bail!("task control requires MAGI_NODE=chat and MAGI_RUN from a standing chat");
2705 }
2706 let id = crate::chat_watch::authorize(talks, run, node)?;
2707 talks.get(&id)
2708}
2709
2710fn run_task(queue: &Queue, run: &str) -> Result<Task> {
2712 ensure!(
2713 crate::run::is_run_id(run),
2714 "an execution command needs the full run id"
2715 );
2716 queue
2717 .list()
2718 .into_iter()
2719 .find(|t| t.runs.iter().any(|r| r == run))
2720 .with_context(|| format!("run {run} belongs to no task"))
2721}
2722
2723fn claimed(queue: &Queue, reference: &str) -> Result<(crate::queue::Claim, Task)> {
2726 let id = queue.resolve_id(reference)?;
2727 let claim = queue
2728 .claim(&id)
2729 .with_context(|| format!("task {id} is claimed by a running daemon"))?;
2730 let task = queue.get(&id)?;
2731 Ok((claim, task))
2732}
2733
2734fn claimed_for_chat(
2735 queue: &Queue,
2736 reference: &str,
2737 talks: &Talks,
2738 chat: &str,
2739) -> Result<(crate::queue::Claim, Task)> {
2740 let claimed = claimed(queue, reference)?;
2741 if let crate::chat_goal::Source::Goal { id, generation } = crate::chat_goal::current_source() {
2742 let talk = talks.get(chat)?;
2743 let goal = talk
2744 .goals
2745 .iter()
2746 .find(|goal| goal.id == id)
2747 .context("unknown goal")?;
2748 goal.admit(generation)?;
2749 let task = &claimed.1;
2750 ensure!(
2751 goal.tasks.contains(&task.id),
2752 "effect targets a task outside this goal"
2753 );
2754 crate::chat_goal::require_repo(
2755 "task",
2756 &task.id,
2757 &task.repo,
2758 goal.effective_repo(&talk.repo),
2759 )?;
2760 }
2761 Ok(claimed)
2762}
2763
2764fn check_hold_release(task: &Task, operation: &str) -> Result<()> {
2765 match task.status {
2766 TaskStatus::Queued
2767 | TaskStatus::Held
2768 | TaskStatus::Failed
2769 | TaskStatus::Blocked
2770 | TaskStatus::Parked => Ok(()),
2771 TaskStatus::Done => bail!(
2772 "cannot {operation} task {} (done): completed work must not be restarted; create a new task instead",
2773 task.id
2774 ),
2775 TaskStatus::Running => bail!(
2776 "cannot {operation} task {} (running): its run may still be active; use resume or abandon for the existing run instead",
2777 task.id
2778 ),
2779 }
2780}
2781
2782pub async fn done(
2784 queue: &Queue,
2785 home: &Path,
2786 reference: &str,
2787 reason: Option<String>,
2788 discard: bool,
2789) -> Result<Task> {
2790 crate::task_completion::close(
2791 queue,
2792 home,
2793 reference,
2794 crate::queue::CompletionActor::Cli,
2795 reason,
2796 discard,
2797 )
2798 .await
2799}
2800
2801pub fn set_priority(queue: &Queue, reference: &str, priority: i32) -> Result<Task> {
2803 priority_claimed(queue, claimed(queue, reference)?, priority)
2804}
2805
2806fn priority_claimed(
2807 queue: &Queue,
2808 (_claim, mut task): (crate::queue::Claim, Task),
2809 priority: i32,
2810) -> Result<Task> {
2811 task.set_priority(priority)?;
2812 queue.put(&mut task)?;
2813 Ok(task)
2814}
2815
2816pub fn hold(queue: &Queue, reference: &str, reason: &str) -> Result<Task> {
2818 hold_claimed(queue, claimed(queue, reference)?, reason)
2819}
2820
2821fn hold_claimed(
2822 queue: &Queue,
2823 (_claim, mut task): (crate::queue::Claim, Task),
2824 reason: &str,
2825) -> Result<Task> {
2826 check_hold_release(&task, "hold")?;
2827 let reason = reason.trim();
2828 task.hold_manual((!reason.is_empty()).then(|| reason.to_owned()));
2829 queue.put(&mut task)?;
2830 Ok(task)
2831}
2832
2833pub fn release(queue: &Queue, reference: &str) -> Result<Task> {
2837 release_claimed(queue, claimed(queue, reference)?)
2838}
2839
2840fn release_claimed(queue: &Queue, (_claim, mut task): (crate::queue::Claim, Task)) -> Result<Task> {
2841 check_hold_release(&task, "release")?;
2842 crate::base_sync_recovery::ensure_generic_release(queue, &task)?;
2843 let run = task.execution_runs().last().cloned();
2844 let preserved = match run {
2845 Some(run) => crate::repair_budget::queue_resumption(queue, &mut task, &run)?,
2846 None => false,
2847 };
2848 if !preserved {
2849 task.release_operator("chat", None);
2850 }
2851 queue.put(&mut task)?;
2852 Ok(task)
2853}
2854
2855pub fn retry(
2860 queue: &Queue,
2861 reference: &str,
2862 title: Option<String>,
2863 instruction: &str,
2864) -> Result<Task> {
2865 retry_claimed(queue, claimed(queue, reference)?, title, instruction)
2866}
2867
2868fn retry_claimed(
2869 queue: &Queue,
2870 (_claim, mut task): (crate::queue::Claim, Task),
2871 title: Option<String>,
2872 instruction: &str,
2873) -> Result<Task> {
2874 ensure!(
2875 !instruction.trim().is_empty(),
2876 "the new instruction is empty"
2877 );
2878 if let Some(state) = crate::base_sync_recovery::held_run(queue, &task)
2879 && state
2880 .base_sync_recovery
2881 .stop
2882 .as_ref()
2883 .is_some_and(|stop| stop.kind == crate::base_sync_recovery::StopKind::Conflict)
2884 {
2885 anyhow::bail!(
2886 "retry cannot authorize editing a retained base-sync stop. {}",
2887 state.base_sync_next_action()
2888 );
2889 }
2890 crate::base_sync_recovery::ensure_generic_release(queue, &task)?;
2891 let title = title.unwrap_or_else(|| crate::queue::title_from(instruction, 72));
2892 task.edit(title, instruction.to_owned())?;
2893 task.release_operator("chat", None);
2894 queue.put(&mut task)?;
2895 Ok(task)
2896}
2897
2898pub fn resume(queue: &Queue, home: &Path, run: &str) -> Result<Task> {
2901 let task = run_task(queue, run)?;
2902 ensure!(
2903 task.execution_runs().last().map(String::as_str) == Some(run),
2904 "only the task's latest run can be resumed"
2905 );
2906 crate::resume::validate(home, run)?;
2907 ensure!(
2908 crate::resume::pin_queued(queue, run, None, None)?,
2909 "no queued task owns run {run}"
2910 );
2911 queue.get(&task.id)
2912}
2913
2914fn rerun_preflight(
2917 queue: &Queue,
2918 home: &Path,
2919 run: &str,
2920 request: &str,
2921) -> Result<crate::run::RunState> {
2922 run_task(queue, run)?;
2923 let state = crate::run::RunState::load_under(run, home)?;
2924 ensure!(state.pr.is_some(), "the run recorded no pull request");
2925 ensure!(
2926 crate::ask::valid_asset_name(request),
2927 "request must be a safe filename of at most 64 bytes"
2928 );
2929 Ok(state)
2930}
2931
2932pub async fn rerun_checks(
2934 queue: &Queue,
2935 home: &Path,
2936 talk: &str,
2937 run: &str,
2938 request: &str,
2939 head: &str,
2940 workflows: &[String],
2941) -> Result<Vec<String>> {
2942 let state = rerun_preflight(queue, home, run, request).map_err(BeforeEffect)?;
2943 let dir = home.join("chat-controls").join(talk);
2944 std::fs::create_dir_all(&dir)?;
2945 let lock = std::fs::OpenOptions::new()
2946 .create(true)
2947 .truncate(false)
2948 .write(true)
2949 .open(dir.join(format!("{request}.lock")))?;
2950 crate::pr_head::try_lock_file(&lock).map_err(|error| BeforeEffect(error.into()))?;
2951 let path = dir.join(format!("{request}.json"));
2952 let pr = &state
2953 .pr
2954 .as_ref()
2955 .context("the run recorded no pull request")?
2956 .url;
2957 let action = serde_json::json!({
2958 "run": run, "repo": state.repo, "pr": pr, "head": head, "runs": workflows
2959 });
2960 if path.exists() {
2961 let prior: serde_json::Value = serde_json::from_slice(&std::fs::read(&path)?)?;
2962 if prior["action"] != action {
2963 return Err(BeforeEffect(anyhow::anyhow!(
2964 "request ID already binds a different operation"
2965 ))
2966 .into());
2967 }
2968 ensure!(
2969 prior["status"] == "applied",
2970 "previous request has an uncertain result; inspect its receipt before a new request"
2971 );
2972 return Ok(workflows.to_vec());
2973 }
2974 let record = |status: &str| -> Result<()> {
2975 let tmp = path.with_extension("tmp");
2976 std::fs::write(
2977 &tmp,
2978 serde_json::to_vec(&serde_json::json!({
2979 "action": action, "status": status
2980 }))?,
2981 )?;
2982 std::fs::rename(tmp, &path)?;
2983 Ok(())
2984 };
2985 let operation = format!("chat:{talk}:{request}");
2986 let started = std::sync::atomic::AtomicBool::new(false);
2987 crate::daemon::rerun_checks_once(home, &operation, &state.repo, pr, head, workflows, || {
2988 started.store(true, std::sync::atomic::Ordering::SeqCst);
2991 record("started")
2992 })
2993 .await
2994 .map_err(|error| {
2995 if started.load(std::sync::atomic::Ordering::SeqCst) {
2996 error
2997 } else {
2998 anyhow::Error::new(BeforeEffect(error))
2999 }
3000 })?;
3001 record("applied")?;
3002 Ok(workflows.to_vec())
3003}
3004
3005pub fn abandon(queue: &Queue, home: &Path, run: &str) -> Result<()> {
3009 run_task(queue, run)?;
3010 crate::driver::abandon_proven_dead(home, run)
3011}
3012
3013pub fn describe(task: &Task, what: &str) -> String {
3015 let status = match task.status {
3016 TaskStatus::Queued => "queued",
3017 _ => task.status.as_str(),
3018 };
3019 format!("{what} {} {} ({status})", task.short(), task.title)
3020}
3021
3022#[cfg(test)]
3023mod tests {
3024 use super::*;
3025 use crate::queue::Source;
3026 use jiff::Timestamp;
3027
3028 fn talk(talks: &Talks, id: &str) -> Talk {
3029 let mut t: Talk = serde_json::from_value(serde_json::json!({
3030 "schema":1,"id":id,"repo":".","agent":"worker","status":"open","turns":[],
3031 "created_at":Timestamp::now(),"updated_at":Timestamp::now(),
3032 "seat":crate::agent::SeatState::new("talk","worker",1)
3033 }))
3034 .unwrap();
3035 talks.put(&mut t).unwrap();
3036 t
3037 }
3038
3039 fn filed(queue: &Queue, talk: &str, text: &str) -> Task {
3040 let mut t = Task::new(
3041 text.into(),
3042 text.into(),
3043 ".".into(),
3044 Source::Agent {
3045 run: talk.into(),
3046 node: crate::queue::CHAT_NODE.into(),
3047 },
3048 );
3049 queue.put(&mut t).unwrap();
3050 t
3051 }
3052
3053 #[tokio::test]
3054 async fn direct_chat_completion_supersedes_the_earlier_blocked_run() {
3055 use crate::run::{RunState, RunStatus};
3056
3057 let dir = tempfile::tempdir().unwrap();
3058 let home = dir.path();
3059 let talks = Talks::at(home.join("talks"));
3060 let queue = Queue::at(home.join("queue"));
3061 let talk = talk(&talks, "talk-a");
3062 let mut task = filed(&queue, &talk.id, "deliver");
3063 for status in [RunStatus::Blocked, RunStatus::Merged] {
3064 let mut run = RunState::new(
3065 task.repo.clone(),
3066 "main".into(),
3067 "base".into(),
3068 task.instruction.clone(),
3069 crate::config::Config::default(),
3070 );
3071 run.status = status;
3072 if status == RunStatus::Merged {
3073 run.merge = Some(crate::run::MergeOutcome {
3074 mode: crate::config::MergeMode::Pr,
3075 ok: true,
3076 detail: "merged".into(),
3077 empty: false,
3078 });
3079 }
3080 run.driver_exited = true;
3081 run.reserve_under(home).unwrap();
3082 task.link_run(&run.id);
3083 }
3084 queue.put(&mut task).unwrap();
3085 execute(
3086 &queue,
3087 home,
3088 &talks,
3089 &talk.id,
3090 Operation::Done {
3091 task: task.id.clone(),
3092 reason: None,
3093 result: None,
3094 discard: false,
3095 },
3096 )
3097 .await
3098 .unwrap();
3099 assert_eq!(
3100 RunState::load_under(&task.runs[0], home).unwrap().status,
3101 RunStatus::Superseded
3102 );
3103 }
3104
3105 #[test]
3106 fn ownerless_import_reconciliation_requires_effect_evidence_not_saved_consent() {
3107 use crate::ask::{Answer, Question, Questions};
3108 let home = tempfile::tempdir().unwrap();
3109 let home = home.path();
3110 let queue = Queue::at(home.join("queue"));
3111 let talks = Talks::at(home.join("talks"));
3112 let questions = Questions::at(home.join("questions"));
3113 let mut q = Question::new(
3114 String::new(),
3115 crate::bump::NOTICE_NODE.into(),
3116 "release-watch".into(),
3117 "Historical release hold".into(),
3118 String::new(),
3119 vec!["hold".into()],
3120 );
3121 q.answer(Answer::Choice("hold".into())).unwrap();
3122 q.answer_delivered = true;
3123 questions.put(&mut q).unwrap();
3124 let source = std::fs::read(questions.path_of(&q.id)).unwrap();
3125 crate::task_chat::sweep(&queue, &talks, &questions, home);
3126 assert!(reconcile_task_decision(&queue, home, "authorized-chat", &q.id).is_err());
3127 let outbox = crate::task_inquiry::Outbox::at(home);
3128 assert_eq!(
3129 outbox.get(&q.id).unwrap().decision.unwrap().status,
3130 crate::task_decision::Status::RetryNeeded
3131 );
3132 let dir = home.join("release-watch-receipts");
3133 std::fs::create_dir_all(&dir).unwrap();
3134 std::fs::write(
3135 dir.join(format!("{}.json", q.id)),
3136 serde_json::to_vec(&crate::release_watch::WatchState {
3137 applied: vec![q.id.clone()],
3138 ..Default::default()
3139 })
3140 .unwrap(),
3141 )
3142 .unwrap();
3143 for _ in 0..2 {
3144 reconcile_task_decision(&queue, home, "authorized-chat", &q.id).unwrap();
3145 }
3146 let decision = outbox.get(&q.id).unwrap().decision.unwrap();
3147 assert_eq!(decision.status, crate::task_decision::Status::Resolved);
3148 assert!(decision.request.is_none());
3149 assert!(decision.source_answer_at.is_none());
3150 assert_eq!(std::fs::read(questions.path_of(&q.id)).unwrap(), source);
3151 assert!(queue.list().is_empty());
3152 assert!(talks.list().is_empty());
3153 }
3154
3155 #[test]
3156 fn receipt_reconciliation_error_is_visible_after_restart() {
3157 use crate::task_decision::{Attention, Status};
3158 let tmp = tempfile::tempdir().unwrap();
3159 let home = tmp.path();
3160 let queue = Queue::at(home.join("queue"));
3161 let task = filed(&queue, "talk-a", "work");
3162 let outbox = crate::task_inquiry::Outbox::at(home);
3163 let inquiry = outbox
3164 .file(&task, None, "merge".into(), "Merge?", "")
3165 .unwrap();
3166 let request = serde_json::to_string(&Operation::MergePr {
3167 repo: "example/project".into(),
3168 number: 42,
3169 head: "head".into(),
3170 request: "request-a".into(),
3171 })
3172 .unwrap();
3173 outbox
3174 .update_decision(&inquiry.id, |d| {
3175 d.accept(&request)?;
3176 d.start()
3177 })
3178 .unwrap();
3179 assert!(reconcile_decisions(&queue, home).is_err());
3181 let failed = outbox.get(&inquiry.id).unwrap().decision.unwrap();
3182 assert_eq!(failed.status, Status::RetryNeeded);
3183 assert_eq!(failed.attention(false), Attention::ReceiptCheck);
3184 assert!(
3185 failed
3186 .error
3187 .as_deref()
3188 .unwrap()
3189 .contains("merge decision has no chat")
3190 );
3191 assert_eq!(failed.request.as_deref(), Some(request.as_str()));
3192 assert!(!failed.retry_safe);
3193 assert!(reconcile_decisions(&queue, home).is_err());
3194 assert_eq!(outbox.get(&inquiry.id).unwrap().decision.unwrap(), failed);
3195 }
3196
3197 #[test]
3198 fn resume_recovery_waits_for_the_inquiry_publisher() {
3199 let tmp = tempfile::tempdir().unwrap();
3200 let queue = Queue::at(tmp.path().join("queue"));
3201 let mut task = filed(&queue, "talk-a", "work");
3202 let mut state = crate::run::RunState::new(
3203 task.repo.clone(),
3204 "main".into(),
3205 "base".into(),
3206 "work".into(),
3207 crate::config::Config::default(),
3208 );
3209 state.status = crate::run::RunStatus::Blocked;
3210 state.driver_exited = true;
3211 state.save_under(tmp.path()).unwrap();
3212 task.runs.push(state.id.clone());
3213 queue.put(&mut task).unwrap();
3214 let outbox = crate::task_inquiry::Outbox::at(tmp.path());
3215 let inquiry = outbox
3216 .file(
3217 &task,
3218 Some(state.id.clone()),
3219 "resume".into(),
3220 "Resume?",
3221 "",
3222 )
3223 .unwrap();
3224 let request = serde_json::to_string(&Operation::Resume {
3225 run: state.id.clone(),
3226 })
3227 .unwrap();
3228 outbox
3229 .update_decision(&inquiry.id, |d| {
3230 d.accept(&request)?;
3231 d.start()
3232 })
3233 .unwrap();
3234 let before = outbox.get(&inquiry.id).unwrap().decision.unwrap();
3235 let publisher = outbox.execution_claim(&inquiry.id).unwrap();
3236 reconcile_decisions(&queue, tmp.path()).unwrap();
3237 assert_eq!(outbox.get(&inquiry.id).unwrap().decision.unwrap(), before);
3238 drop(publisher);
3239 reconcile_decisions(&queue, tmp.path()).unwrap();
3240 let recovered = outbox.get(&inquiry.id).unwrap().decision.unwrap();
3241 assert_eq!(recovered.status, crate::task_decision::Status::RetryNeeded);
3242 assert!(recovered.retry_safe);
3243 }
3244
3245 #[tokio::test]
3246 async fn resume_receipt_matches_checkout_root_not_filing_directory() {
3247 use crate::task_decision::Status;
3248 let tmp = tempfile::tempdir().unwrap();
3249 let home = tmp.path();
3250 let repo = home.join("checkout");
3251 let subdir = repo.join("src");
3252 let foreign = home.join("foreign");
3253 std::fs::create_dir_all(&subdir).unwrap();
3254 std::fs::create_dir(&foreign).unwrap();
3255 for checkout in [&repo, &foreign] {
3256 crate::git::git(checkout, &["init", "-q"]).await.unwrap();
3257 }
3258 let queue = Queue::at(home.join("queue"));
3259 let mut task = Task::new("work".into(), "work".into(), subdir, Source::Human);
3260 let mut state = crate::run::RunState::new(
3261 repo,
3262 "main".into(),
3263 "base".into(),
3264 "work".into(),
3265 crate::config::Config::default(),
3266 );
3267 state.reserve_under(home).unwrap();
3268 task.runs.push(state.id.clone());
3269 queue.put(&mut task).unwrap();
3270 let outbox = crate::task_inquiry::Outbox::at(home);
3271 let inquiry = outbox
3272 .file(
3273 &task,
3274 Some(state.id.clone()),
3275 "resume".into(),
3276 "Resume?",
3277 "",
3278 )
3279 .unwrap();
3280 let request = serde_json::to_string(&Operation::Resume {
3281 run: state.id.clone(),
3282 })
3283 .unwrap();
3284 outbox
3285 .update_decision(&inquiry.id, |d| {
3286 d.accept(&request)?;
3287 d.start()
3288 })
3289 .unwrap();
3290 task.dispatched_resumes
3291 .insert(inquiry.id.clone(), state.id.clone());
3292 queue.put(&mut task).unwrap();
3293 reconcile_decisions(&queue, home).unwrap();
3294 assert_eq!(
3295 outbox.get(&inquiry.id).unwrap().decision.unwrap().status,
3296 Status::InProgress
3297 );
3298
3299 state.carry_dispatched_resumes(&task);
3300 state.begin_pass();
3301 state.save_under(home).unwrap();
3302 let mut reassigned = task.clone();
3303 reassigned.repo = foreign;
3304 assert!(resume_started(home, &reassigned, &inquiry.id, &state.id).is_err());
3305 reconcile_decisions(&queue, home).unwrap();
3306 assert_eq!(
3307 outbox.get(&inquiry.id).unwrap().decision.unwrap().status,
3308 Status::Resolved
3309 );
3310 }
3311
3312 #[test]
3313 fn only_the_chat_seat_of_an_open_talk_is_authorized() {
3314 let tmp = tempfile::tempdir().unwrap();
3315 let talks = Talks::at(tmp.path().join("talks"));
3316 let t = talk(&talks, "talk-a");
3317 assert!(authorize(&talks, &t.id, "chat").is_ok());
3318 assert!(authorize(&talks, &t.id, "deputy").is_err());
3319 assert!(authorize(&talks, &t.id, "").is_err());
3320 assert!(authorize(&talks, "", "chat").is_err());
3321 assert!(
3322 authorize(&talks, "talk-", "chat").is_err(),
3323 "prefix is not an id"
3324 );
3325 }
3326
3327 #[test]
3328 fn tasks_of_any_origin_are_controlled_on_request() {
3329 let tmp = tempfile::tempdir().unwrap();
3330 let queue = Queue::at(tmp.path().join("queue"));
3331 let theirs = filed(&queue, "talk-b", "theirs");
3332 let mut hand = Task::new("h".into(), "h".into(), ".".into(), Source::Human);
3333 hand.hold_manual(Some("operator".into()));
3334 queue.put(&mut hand).unwrap();
3335 assert_eq!(
3338 hold(&queue, &theirs.id, "wait").unwrap().status,
3339 TaskStatus::Held
3340 );
3341 assert_eq!(
3342 release(&queue, &hand.id).unwrap().status,
3343 TaskStatus::Queued
3344 );
3345 let again = retry(&queue, &theirs.id, None, "new").unwrap();
3346 assert_eq!(again.instruction, "new");
3347 assert_eq!(again.status, TaskStatus::Queued);
3348 }
3349
3350 #[test]
3351 fn hold_then_release_keeps_history_and_restarts_attempts() {
3352 let tmp = tempfile::tempdir().unwrap();
3353 let queue = Queue::at(tmp.path().join("queue"));
3354 let mut t = filed(&queue, "talk-a", "work");
3355 t.attempts = 3;
3356 t.runs.push("20260101-000000-aaaa".into());
3357 queue.put(&mut t).unwrap();
3358 let held = hold(&queue, &t.id, "owner asked").unwrap();
3359 assert_eq!(held.status, TaskStatus::Held);
3360 assert_eq!(held.hold_reason.as_deref(), Some("owner asked"));
3361 let back = release(&queue, &t.id).unwrap();
3362 assert_eq!(back.status, TaskStatus::Queued);
3363 assert_eq!(back.attempts, 0);
3364 assert_eq!(back.runs, t.runs);
3365 assert!(back.resumption.is_some());
3366 }
3367
3368 #[test]
3369 fn hold_and_release_refuse_done_and_running_without_saving() {
3370 let tmp = tempfile::tempdir().unwrap();
3371 let queue = Queue::at(tmp.path().join("queue"));
3372 for status in [TaskStatus::Done, TaskStatus::Running] {
3373 let mut t = filed(&queue, "talk-a", "work");
3374 t.start("20260101-000000-aaaa".into());
3375 if status == TaskStatus::Done {
3376 t.succeed(crate::queue::CompletionContext::new(
3377 crate::queue::CompletionActor::Cli,
3378 None,
3379 tmp.path(),
3380 &t,
3381 ));
3382 }
3383 queue.put(&mut t).unwrap();
3384 let before = std::fs::read(queue.path_of(&t.id)).unwrap();
3385 for operation in ["hold", "release"] {
3386 let error = if operation == "hold" {
3387 hold(&queue, &t.id, "owner asked")
3388 } else {
3389 release(&queue, &t.id)
3390 }
3391 .unwrap_err()
3392 .to_string();
3393 assert!(error.contains(operation), "{error}");
3394 assert!(error.contains(&t.id), "{error}");
3395 assert!(error.contains(status.as_str()), "{error}");
3396 let guidance = if status == TaskStatus::Done {
3397 "create a new task"
3398 } else {
3399 "use resume or abandon"
3400 };
3401 assert!(error.contains(guidance), "{error}");
3402 assert_eq!(std::fs::read(queue.path_of(&t.id)).unwrap(), before);
3403 }
3404 }
3405 }
3406
3407 #[test]
3408 fn hold_and_release_allow_unfinished_inactive_tasks() {
3409 let tmp = tempfile::tempdir().unwrap();
3410 let queue = Queue::at(tmp.path().join("queue"));
3411 for status in [
3412 TaskStatus::Queued,
3413 TaskStatus::Held,
3414 TaskStatus::Failed,
3415 TaskStatus::Blocked,
3416 TaskStatus::Parked,
3417 ] {
3418 for operation in ["hold", "release"] {
3419 let mut t = filed(&queue, "talk-a", "work");
3420 t.status = status;
3421 t.hold_reason = Some("old reason".into());
3422 t.attempts = 3;
3423 t.runs.push("20260101-000000-aaaa".into());
3424 queue.put(&mut t).unwrap();
3425 let changed = if operation == "hold" {
3426 let held = hold(&queue, &t.id, " new reason ").unwrap();
3427 assert_eq!(held.status, TaskStatus::Held);
3428 assert_eq!(held.hold_reason.as_deref(), Some("new reason"));
3429 assert_eq!(held.attempts, t.attempts);
3430 held
3431 } else {
3432 let released = release(&queue, &t.id).unwrap();
3433 assert_eq!(released.status, TaskStatus::Queued);
3434 assert_eq!(released.attempts, 0);
3435 assert_eq!(released.resumption.as_ref().unwrap().source, "chat");
3436 released
3437 };
3438 assert_eq!(changed.runs, t.runs);
3439 assert_eq!(queue.get(&t.id).unwrap().status, changed.status);
3440 }
3441 }
3442 }
3443
3444 #[test]
3445 fn retry_edits_and_requeues_in_one_save() {
3446 let tmp = tempfile::tempdir().unwrap();
3447 let queue = Queue::at(tmp.path().join("queue"));
3448 let mut t = filed(&queue, "talk-a", "old text");
3449 t.runs.push("20260101-000000-aaaa".into());
3450 t.attempts = 2;
3451 t.hold_manual(Some("stopped".into()));
3452 queue.put(&mut t).unwrap();
3453 let again = retry(&queue, &t.id, None, "new text").unwrap();
3454 assert_eq!(again.instruction, "new text");
3455 assert_eq!(again.status, TaskStatus::Queued);
3456 assert_eq!(again.attempts, 0);
3457 assert_eq!(again.runs, t.runs, "run history is kept");
3458 assert_eq!(again.resumption.as_ref().unwrap().source, "chat");
3459 assert_eq!(again.resumption.as_ref().unwrap().instruction, "new text");
3460 let mut running = filed(&queue, "talk-a", "busy");
3462 running.start("20260101-000000-bbbb".into());
3463 queue.put(&mut running).unwrap();
3464 assert!(retry(&queue, &running.id, None, "x").is_err());
3465 assert_eq!(queue.get(&running.id).unwrap().instruction, "busy");
3466 assert!(retry(&queue, &t.id, None, " ").is_err());
3467 }
3468
3469 #[test]
3470 fn execution_commands_need_the_full_id_of_a_recorded_run() {
3471 let tmp = tempfile::tempdir().unwrap();
3472 let queue = Queue::at(tmp.path().join("queue"));
3473 let mut t = filed(&queue, "talk-b", "work");
3474 t.runs.push("20260101-000000-aaaa".into());
3475 queue.put(&mut t).unwrap();
3476 assert_eq!(
3477 run_task(&queue, "20260101-000000-aaaa").unwrap().id,
3478 t.id,
3479 "any chat may address another chat's run"
3480 );
3481 assert!(run_task(&queue, "aaaa").is_err());
3482 assert!(run_task(&queue, "20260101-000000-bbbb").is_err());
3483 assert!(resume(&queue, tmp.path(), "aaaa").is_err());
3484 }
3485
3486 #[test]
3487 fn abandon_needs_no_phrase_but_refuses_unrecorded_and_unknown_runs() {
3488 let tmp = tempfile::tempdir().unwrap();
3489 let queue = Queue::at(tmp.path().join("queue"));
3490 let mut t = filed(&queue, "talk-b", "work");
3491 t.runs.push("20260101-000000-aaaa".into());
3492 queue.put(&mut t).unwrap();
3493 assert!(abandon(&queue, tmp.path(), "20260101-000000-bbbb").is_err());
3495 assert!(abandon(&queue, tmp.path(), "20260101-000000-aaaa").is_err());
3498 }
3499}
3500
3501#[cfg(test)]
3502mod goal_admission_tests {
3503 use super::*;
3504
3505 #[tokio::test]
3506 async fn goal_effects_require_current_generation_scope_and_no_new_owner_input() {
3507 let tmp = tempfile::tempdir().unwrap();
3508 let talks = Talks::at(tmp.path().join("talks"));
3509 let queue = Queue::at(tmp.path().join("queue"));
3510 let target = tmp.path().join("target");
3511 std::fs::create_dir(&target).unwrap();
3512 crate::git::git(&target, &["init", "-q"]).await.unwrap();
3513 let mut talk = crate::talk::seeded_for_test("goal-effect", tmp.path().into());
3514 talk.turns.push(
3515 serde_json::from_value(serde_json::json!({
3516 "sender": "operator", "who": "operator", "body": "Follow this task through",
3517 "at": jiff::Timestamp::now()
3518 }))
3519 .unwrap(),
3520 );
3521 talks.put(&mut talk).unwrap();
3522 let mut task = Task::new(
3523 "work".into(),
3524 "work".into(),
3525 target.clone(),
3526 crate::queue::Source::Agent {
3527 run: talk.id.clone(),
3528 node: crate::queue::CHAT_NODE.into(),
3529 },
3530 );
3531 queue.put(&mut task).unwrap();
3532 let mut unrelated = Task::new(
3533 "other".into(),
3534 "other".into(),
3535 target.clone(),
3536 crate::queue::Source::Agent {
3537 run: talk.id.clone(),
3538 node: crate::queue::CHAT_NODE.into(),
3539 },
3540 );
3541 queue.put(&mut unrelated).unwrap();
3542 crate::chat_goal::apply(
3543 &queue,
3544 tmp.path(),
3545 &talks,
3546 &talk.id,
3547 &crate::chat_goal::Source::Input { turn: 0 },
3548 crate::chat_goal::Command::Establish {
3549 id: "g".into(),
3550 purpose: "Deliver this task".into(),
3551 scope: "This task only".into(),
3552 condition: "Verified delivery".into(),
3553 completion: crate::chat_goal::Completion::TasksDone,
3554 repo: Some(target),
3555 tasks: vec![task.id.clone()],
3556 runs: vec![],
3557 watches: vec![],
3558 },
3559 )
3560 .await
3561 .unwrap();
3562 talks
3563 .mutate(&talk.id, |talk| {
3564 let boundary = talk.turns.len();
3565 let goal = &mut talk.goals[0];
3566 goal.wake = 1;
3567 goal.started = Some(1);
3568 goal.launch_turns = Some(boundary);
3569 Ok(())
3570 })
3571 .unwrap();
3572 let source = crate::chat_goal::Source::Goal {
3573 id: "g".into(),
3574 generation: 1,
3575 };
3576 assert!(
3577 execute_authenticated(
3578 &queue,
3579 tmp.path(),
3580 &talks,
3581 &talk.id,
3582 source.clone(),
3583 Operation::Priority {
3584 task: unrelated.id.clone(),
3585 priority: 8
3586 }
3587 )
3588 .await
3589 .is_err()
3590 );
3591 execute_authenticated(
3592 &queue,
3593 tmp.path(),
3594 &talks,
3595 &talk.id,
3596 source.clone(),
3597 Operation::Priority {
3598 task: task.id.clone(),
3599 priority: 3,
3600 },
3601 )
3602 .await
3603 .unwrap();
3604 let hold = Operation::Hold {
3605 task: task.id.clone(),
3606 reason: "pause".into(),
3607 };
3608 crate::chat_goal::with_source(source.clone(), async {
3609 admit_goal_operation(&queue, tmp.path(), &talks, &talk.id, &hold).unwrap();
3612 let original = task.repo.clone();
3613 {
3614 let claim = queue.claim(&task.id).unwrap();
3615 task = queue.get(&task.id).unwrap();
3616 task.repo = talk.repo.clone();
3617 queue.put(&mut task).unwrap();
3618 drop(claim);
3619 }
3620 let result = claimed_for_chat(&queue, &task.id, &talks, &talk.id)
3621 .and_then(|claimed| hold_claimed(&queue, claimed, "pause"));
3622 assert!(result.unwrap_err().to_string().contains(&task.id));
3623 assert_eq!(queue.get(&task.id).unwrap().status, TaskStatus::Queued);
3624 task.repo = original;
3625 queue.put(&mut task).unwrap();
3626 })
3627 .await;
3628 let error = execute_authenticated(
3629 &queue,
3630 tmp.path(),
3631 &talks,
3632 &talk.id,
3633 source.clone(),
3634 Operation::Done {
3635 task: task.id.clone(),
3636 reason: Some("discard unfinished work".into()),
3637 result: None,
3638 discard: true,
3639 },
3640 )
3641 .await
3642 .unwrap_err();
3643 assert!(
3644 error.to_string().contains("explicit owner turn"),
3645 "{error:#}"
3646 );
3647 assert_eq!(queue.get(&task.id).unwrap().status, TaskStatus::Queued);
3648 assert!(queue.get(&task.id).unwrap().completion_history.is_empty());
3649 assert!(
3650 execute_authenticated(
3651 &queue,
3652 tmp.path(),
3653 &talks,
3654 &talk.id,
3655 source.clone(),
3656 Operation::Done {
3657 task: unrelated.id.clone(),
3658 reason: None,
3659 result: None,
3660 discard: false,
3661 },
3662 )
3663 .await
3664 .is_err()
3665 );
3666 queue
3670 .modify(&task.id, |t| {
3671 t.investigation = true;
3672 true
3673 })
3674 .unwrap();
3675 execute_authenticated(
3676 &queue,
3677 tmp.path(),
3678 &talks,
3679 &talk.id,
3680 source.clone(),
3681 Operation::Done {
3682 task: task.id.clone(),
3683 reason: Some("goal work finished".into()),
3684 result: Some("goal findings recorded".into()),
3685 discard: false,
3686 },
3687 )
3688 .await
3689 .unwrap();
3690 let error = execute_authenticated(
3691 &queue,
3692 tmp.path(),
3693 &talks,
3694 &talk.id,
3695 source.clone(),
3696 Operation::Reopen {
3697 task: task.id.clone(),
3698 reason: "recover unfinished work".into(),
3699 },
3700 )
3701 .await
3702 .unwrap_err();
3703 assert!(
3704 error.to_string().contains("explicit owner turn"),
3705 "{error:#}"
3706 );
3707 assert_eq!(queue.get(&task.id).unwrap().status, TaskStatus::Done);
3708 execute_authenticated(
3709 &queue,
3710 tmp.path(),
3711 &talks,
3712 &talk.id,
3713 crate::chat_goal::Source::Input { turn: 0 },
3714 Operation::Reopen {
3715 task: task.id.clone(),
3716 reason: "recover unfinished work".into(),
3717 },
3718 )
3719 .await
3720 .unwrap();
3721 assert_eq!(queue.get(&task.id).unwrap().status, TaskStatus::Held);
3722 talks
3723 .mutate(&talk.id, |talk| {
3724 talk.turns.push(serde_json::from_value(serde_json::json!({
3725 "sender": "operator", "who": "operator", "body": "Stop",
3726 "at": jiff::Timestamp::now()
3727 }))?);
3728 Ok(())
3729 })
3730 .unwrap();
3731 assert!(
3732 execute_authenticated(
3733 &queue,
3734 tmp.path(),
3735 &talks,
3736 &talk.id,
3737 source.clone(),
3738 Operation::Priority {
3739 task: task.id.clone(),
3740 priority: 9
3741 }
3742 )
3743 .await
3744 .is_err()
3745 );
3746 talks
3747 .mutate(&talk.id, |talk| {
3748 talk.turns.pop();
3749 talk.goals[0].state = crate::chat_goal::State::Stopped;
3750 talk.goals[0].wake = 2;
3751 talk.goals[0].started = None;
3752 Ok(())
3753 })
3754 .unwrap();
3755 assert!(
3756 execute_authenticated(
3757 &queue,
3758 tmp.path(),
3759 &talks,
3760 &talk.id,
3761 source,
3762 Operation::Priority {
3763 task: task.id.clone(),
3764 priority: 9
3765 }
3766 )
3767 .await
3768 .is_err()
3769 );
3770 assert_eq!(queue.get(&task.id).unwrap().priority, 3);
3771 }
3772
3773 #[tokio::test]
3774 async fn land_sync_recovery_chat_control_requires_explicit_owner_input() {
3775 let tmp = tempfile::tempdir().unwrap();
3776 let home = tmp.path();
3777 let queue = Queue::at(home.join("queue"));
3778 let talks = Talks::at(home.join("talks"));
3779 let repo = home.join("repo");
3780 std::fs::create_dir(&repo).unwrap();
3781 let mut config = crate::config::Config::default();
3782 config.agents.push(crate::config::AgentSpec {
3783 id: "fixture".into(),
3784 kind: crate::config::AgentKind::Command,
3785 model: None,
3786 command: vec!["true".into()],
3787 extra_args: vec![],
3788 env: Default::default(),
3789 prompt_delivery: None,
3790 max_turn_secs: None,
3791 });
3792 let talk = crate::talk::begin(&talks, &config, repo, Some("fixture")).unwrap();
3793
3794 let make_op = || Operation::RecoverLandSync {
3795 run: "20261127-125940-3ce0".into(),
3796 head: "a".repeat(40),
3797 request: "req-chat-guard".into(),
3798 };
3799
3800 let err = execute_authenticated(
3802 &queue,
3803 home,
3804 &talks,
3805 &talk.id,
3806 crate::chat_goal::Source::Automatic,
3807 make_op(),
3808 )
3809 .await
3810 .unwrap_err();
3811 assert!(
3812 err.to_string()
3813 .contains("recover-land-sync requires explicit owner input"),
3814 "{err:#}"
3815 );
3816
3817 let mut task = crate::queue::Task::new(
3820 "held".into(),
3821 "held work".into(),
3822 home.join("repo"),
3823 crate::queue::Source::Agent {
3824 run: talk.id.clone(),
3825 node: crate::queue::CHAT_NODE.into(),
3826 },
3827 );
3828 task.hold_machine(Some("landing base synchronization budget exhausted".into()));
3829 queue.put(&mut task).unwrap();
3830 let input: crate::talk::Turn = serde_json::from_value(serde_json::json!({
3831 "sender": "magi",
3832 "who": "operator",
3833 "body": "report",
3834 "at": jiff::Timestamp::now(),
3835 "messages": [{
3836 "sender": "magi",
3837 "body": "report",
3838 "at": jiff::Timestamp::now(),
3839 "attachments": [],
3840 "recovery_event": standing::Event::task(&task)
3841 }]
3842 }))
3843 .unwrap();
3844 let standing_source = standing::capture(
3845 true,
3846 home,
3847 &talk,
3848 Some(&input),
3849 crate::chat_goal::Source::Automatic,
3850 );
3851 let err = execute_authenticated(
3852 &queue,
3853 home,
3854 &talks,
3855 &talk.id,
3856 standing_source,
3857 Operation::Standing {
3858 task: task.id.clone(),
3859 evidence: "auto".into(),
3860 command: Box::new(make_op()),
3861 },
3862 )
3863 .await
3864 .unwrap_err();
3865 assert!(
3866 err.to_string()
3867 .contains("outside the standing recovery allowlist"),
3868 "{err:#}"
3869 );
3870 }
3871}