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 Done {
115 task: String,
117 #[serde(default)]
119 reason: Option<String>,
120 #[serde(default)]
122 discard: bool,
123 },
124 Reopen {
126 task: String,
128 reason: String,
130 },
131 Priority {
133 task: String,
135 priority: i32,
137 },
138 MergePr {
140 repo: String,
142 number: u64,
144 head: String,
146 request: String,
148 },
149 RecoverBase {
151 run: String,
153 head: String,
155 request: String,
157 #[serde(default, skip_serializing_if = "Option::is_none")]
159 evidence_digest: Option<String>,
160 },
161 Resume {
163 run: String,
165 },
166 SyncBaseOnly {
168 run: String,
170 },
171 Hold {
173 task: String,
175 reason: String,
177 },
178 Release {
180 task: String,
182 },
183 Retry {
185 task: String,
187 title: Option<String>,
189 instruction: String,
191 },
192 RerunChecks {
194 run: String,
196 request: String,
198 head: String,
200 workflows: Vec<String>,
202 },
203 Decide {
205 question: String,
207 choice: String,
209 #[serde(default)]
211 title: Option<String>,
212 },
213 Answer {
216 question: String,
218 reply: String,
220 #[serde(default)]
222 title: Option<String>,
223 },
224 ReplyOther {
228 question: String,
230 text: String,
232 },
233 ReconcileRetention {
235 task: String,
237 authority: String,
239 apply: Option<String>,
241 },
242 Abandon {
244 run: String,
246 },
247}
248
249#[derive(Debug, serde::Serialize, serde::Deserialize)]
251#[serde(deny_unknown_fields)]
252pub struct Filing {
253 pub title: String,
255 pub instruction: String,
257 pub repo: std::path::PathBuf,
259 pub source: crate::queue::Source,
261 pub sources: crate::refs::Sources,
263 pub hold: Option<String>,
265 pub priority: i32,
267 pub solo: bool,
269 pub urgent: bool,
271 pub implementers: Option<usize>,
273 #[serde(default, skip_serializing_if = "Option::is_none")]
275 pub build_cache: Option<crate::config::BuildCache>,
276 pub attach: Vec<std::path::PathBuf>,
278}
279
280pub fn has_channel() -> bool {
283 #[cfg(any(unix, windows))]
284 {
285 #[cfg(unix)]
286 let socket = std::env::var_os("MAGI_CHAT_CONTROL_SOCKET").is_some();
287 #[cfg(windows)]
288 let socket = false;
289 std::env::var_os(bridge::CHANNEL_ENV).is_some() || socket
290 }
291 #[cfg(not(any(unix, windows)))]
292 {
293 false
294 }
295}
296
297pub async fn dispatch(
300 queue: &Queue,
301 home: &Path,
302 talks: &Talks,
303 talk: &str,
304 operation: Operation,
305) -> Result<String> {
306 if matches!(
307 &operation,
308 Operation::Reassign { .. }
309 | Operation::RecoverBase { .. }
310 | Operation::SyncBaseOnly { .. }
311 | Operation::Goal { .. }
312 | Operation::Standing { .. }
313 ) {
314 #[cfg(unix)]
315 {
316 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");
317 }
318 #[cfg(windows)]
319 {
320 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");
321 }
322 #[cfg(not(any(unix, windows)))]
323 {
324 bail!("authenticated chat control channel is unavailable on this platform");
325 }
326 }
327 if standing_turn() {
328 #[cfg(unix)]
329 return bridge::request(&operation)
330 .context("automatic recovery requires the authenticated chat control channel");
331 #[cfg(windows)]
332 return bridge::request(&operation)
333 .await
334 .context("automatic recovery requires the authenticated chat control channel");
335 #[cfg(not(any(unix, windows)))]
336 bail!("authenticated chat control channel is unavailable on this platform");
337 }
338 #[cfg(unix)]
339 if std::env::var_os(bridge::CHANNEL_ENV).is_some()
340 || std::env::var_os("MAGI_CHAT_CONTROL_SOCKET").is_some()
341 {
342 match bridge::request(&operation) {
345 Err(error)
346 if error.is::<bridge::Unavailable>()
347 && std::env::var("MAGI_ALLOW_WRITE").as_deref() == Ok("1") => {}
348 result => return result,
349 }
350 }
351 #[cfg(windows)]
352 if std::env::var_os(bridge::CHANNEL_ENV).is_some() {
353 return bridge::request(&operation).await;
354 }
355 Box::pin(execute(queue, home, talks, talk, operation)).await
356}
357
358async fn execute_authenticated(
360 queue: &Queue,
361 home: &Path,
362 talks: &Talks,
363 talk: &str,
364 source: crate::chat_goal::Source,
365 operation: Operation,
366) -> Result<String> {
367 if let crate::chat_goal::Source::Standing(scope) = source {
368 return Box::pin(standing::execute(
369 queue, home, talks, talk, &scope, operation,
370 ))
371 .await;
372 }
373 crate::chat_goal::with_source(
374 source,
375 Box::pin(execute(queue, home, talks, talk, operation)),
376 )
377 .await
378}
379
380pub fn standing_turn() -> bool {
383 std::env::var_os(standing::ENV).is_some()
384}
385
386async fn execute(
387 queue: &Queue,
388 home: &Path,
389 talks: &Talks,
390 talk: &str,
391 operation: Operation,
392) -> Result<String> {
393 authorize(talks, talk, crate::queue::CHAT_NODE)?;
394 crate::chat_goal::fence(talks, talk, &crate::chat_goal::current_source())?;
395 admit_goal_operation(queue, home, talks, talk, &operation)?;
396 Ok(match operation {
397 Operation::Standing { .. } => bail!(
398 "standing authorization is disabled or this turn is not an eligible automatic report"
399 ),
400 Operation::Goal { command } => {
401 crate::chat_goal::apply(
402 queue,
403 home,
404 talks,
405 talk,
406 &crate::chat_goal::current_source(),
407 command,
408 )
409 .await?
410 }
411 Operation::Reassign { task, repo } => {
412 let cwd = &talks.get(talk)?.repo;
413 let task = crate::task_reassign::reassign(
414 queue,
415 home,
416 cwd,
417 &task,
418 &repo,
419 &format!("chat:{talk}"),
420 )
421 .await?;
422 let mut message = describe(&task, "reassigned");
423 for note in crate::task_reassign::advisory_notes(&task, home) {
424 message.push_str(&format!("\n {note}"));
425 }
426 message
427 }
428 Operation::ReconcileDecision { inquiry } => {
429 reconcile_task_decision(queue, home, talk, &inquiry)?;
430 format!("decision {inquiry} reconciled from the task's durable state")
431 }
432 Operation::ForDecision { inquiry, command } => {
433 Box::pin(execute_decision(
434 queue, home, talks, talk, &inquiry, *command,
435 ))
436 .await?
437 }
438 Operation::SettleDecision {
439 inquiry,
440 reason,
441 replacement,
442 } => {
443 let outbox = crate::task_inquiry::Outbox::at(home);
444 let record = outbox.get(&inquiry)?;
445 let questions = crate::ask::Questions::at(home.join("questions"));
446 let source = questions.read_history(&inquiry).ok();
447 let unaccepted_history = record
451 .decision
452 .as_ref()
453 .is_some_and(|d| d.request.is_none())
454 && source.as_ref().is_some_and(|source| {
455 source.status == crate::ask::QuestionStatus::Answered
456 && crate::task_chat::saved_reply_requires_confirmation(home, source)
457 });
458 let _task_claim = if !record.task.is_empty()
462 && (unaccepted_history
463 || record
464 .decision
465 .as_ref()
466 .is_some_and(|d| d.request.is_some()))
467 {
468 Some(
469 queue
470 .claim(&record.task)
471 .context("decision task is executing")?,
472 )
473 } else {
474 None
475 };
476 if record
477 .decision
478 .as_ref()
479 .is_some_and(|d| d.request.is_none())
480 && let Some(source) = source
481 && !(record.task.is_empty() && record.delivered_to.is_none())
482 {
483 ensure!(
484 unaccepted_history || !crate::task_chat::awaits_decision(&source),
485 "a legacy effect still awaits consumer reconciliation; settlement executes no action"
486 );
487 }
488 outbox.settle(&inquiry, talk, &reason, replacement.as_deref())?;
489 format!("settled decision {inquiry}: {reason}")
490 }
491 Operation::Add { filing } => serde_json::to_string(&file_task(queue, *filing)?)?,
492 Operation::Done {
493 task,
494 reason,
495 discard,
496 } => {
497 let claimed = claimed_for_chat(queue, &task, talks, talk)?;
498 let task = Box::pin(crate::task_completion::close_claimed(
499 queue,
500 home,
501 claimed,
502 crate::queue::CompletionActor::Chat(talk.to_owned()),
503 reason,
504 discard,
505 ))
506 .await?;
507 crate::task_completion::describe(&task)
508 }
509 Operation::Reopen { task, reason } => {
510 let (_claim, mut t) = claimed_for_chat(queue, &task, talks, talk)?;
511 let expected = t.clone();
512 let (_guards, context) = Box::pin(crate::task_completion::admit_reopen(
513 &t,
514 home,
515 crate::queue::CompletionActor::Chat(talk.to_owned()),
516 &reason,
517 ))
518 .await?;
519 t.reopen(context)?;
520 queue.commit_completion(&mut t, &expected)?;
521 describe(&t, "reopened on hold")
522 }
523 Operation::Priority { task, priority } => {
524 let t = priority_claimed(
525 queue,
526 claimed_for_chat(queue, &task, talks, talk)?,
527 priority,
528 )?;
529 format!("{} priority now {} - {}", t.short(), t.priority, t.title)
530 }
531 Operation::MergePr {
532 repo,
533 number,
534 head,
535 request,
536 } => crate::chat_merge::merge(
537 home,
538 talks,
539 talk,
540 crate::chat_merge::Request {
541 repo,
542 number,
543 head,
544 request,
545 },
546 )
547 .await
548 .map_err(|error| {
549 if error.is::<crate::chat_merge::BeforeMergeWrite>() {
550 anyhow::Error::new(BeforeEffect(error))
551 } else {
552 error
553 }
554 })?,
555 Operation::ReconcileRepairGrant { request } => serde_json::to_string(
556 &Box::pin(crate::repair_budget::reconcile::apply(queue, home, request)).await?,
557 )?,
558 Operation::GrantRepair { request } => {
559 let owner_requested_at = match crate::chat_goal::current_source() {
562 crate::chat_goal::Source::Input { turn } => talks
563 .get(talk)?
564 .turns
565 .get(turn)
566 .and_then(|turn| crate::talk::owner_send_boundary(&turn.messages)),
567 _ => None,
568 };
569 let receipt = Box::pin(crate::repair_budget::grant_with_claim(
570 queue,
571 home,
572 request,
573 None,
574 owner_requested_at,
575 ))
576 .await
577 .map_err(|error| {
578 if error.is::<crate::repair_budget::PublicationUnknown>() {
579 error
580 } else {
581 BeforeEffect(error).into()
582 }
583 })?;
584 serde_json::to_string(&receipt)?
585 }
586 Operation::RecoverBase {
587 run,
588 head,
589 request,
590 evidence_digest,
591 } => {
592 if evidence_digest.is_some() {
593 ensure!(
594 matches!(
595 crate::chat_goal::current_source(),
596 crate::chat_goal::Source::Input { .. }
597 ),
598 "preparation recovery requires explicit owner input"
599 );
600 }
601 let result = Box::pin(crate::base_recovery_control::recover(
602 queue,
603 home,
604 crate::base_recovery_control::Request {
605 run,
606 head,
607 request,
608 actor: talk.to_owned(),
609 decision: None,
610 expected_stop: None,
611 evidence_digest,
612 },
613 ))
614 .await?;
615 if result.repeated {
616 format!(
617 "This base-recovery request was already applied to task {}; inspect its current status before continuing",
618 result.task.id
619 )
620 } else {
621 format!(
622 "{}; bounded base recovery authorized; the daemon resumes the exact run under its execution lease",
623 describe(&result.task, "recovery queued for")
624 )
625 }
626 }
627 Operation::Resume { run } => {
628 let t = resume(queue, home, &run)?;
629 format!(
630 "{}; the loop (`magi serve`) resumes the run under its execution lease",
631 describe(&t, "resume queued for")
632 )
633 }
634 Operation::SyncBaseOnly { run } => {
635 ensure!(
636 matches!(
637 crate::chat_goal::current_source(),
638 crate::chat_goal::Source::Input { .. }
639 ),
640 "sync-base-only requires an explicit owner request in this chat turn"
641 );
642 let owner = run_task(queue, &run)?;
643 let _claim = queue.claim(&owner.id)?;
644 let mut task = queue.get(&owner.id)?;
645 crate::base_sync_only::queue(&mut task, home, &run)?;
646 queue.put(&mut task)?;
647 describe(&task, "base synchronization only queued for")
648 }
649 Operation::Hold { task, reason } => describe(
650 &hold_claimed(queue, claimed_for_chat(queue, &task, talks, talk)?, &reason)?,
651 "held",
652 ),
653 Operation::Release { task } => describe(
654 &release_claimed(queue, claimed_for_chat(queue, &task, talks, talk)?)?,
655 "released",
656 ),
657 Operation::Retry {
658 task,
659 title,
660 instruction,
661 } => describe(
662 &retry_claimed(
663 queue,
664 claimed_for_chat(queue, &task, talks, talk)?,
665 title,
666 &instruction,
667 )?,
668 "retry queued for",
669 ),
670 Operation::RerunChecks {
671 run,
672 request,
673 head,
674 workflows,
675 } => {
676 let ids = rerun_checks(queue, home, talk, &run, &request, &head, &workflows).await?;
677 format!("requested a rerun of workflow run(s) {}", ids.join(", "))
678 }
679 Operation::Decide {
680 question,
681 choice,
682 title,
683 } => {
684 let q = record_decision(home, &question, &choice, title.as_deref())?;
685 format!(
686 "recorded `{choice}` for decision {}; effect pending until its durable application receipt is confirmed",
687 q.short()
688 )
689 }
690 Operation::Answer {
691 question,
692 reply,
693 title,
694 } => crate::ask::record_answer(
695 &crate::ask::Questions::at(home.join("questions")),
696 &question,
697 &reply,
698 title.as_deref(),
699 )?,
700 Operation::ReplyOther { question, text } => crate::consult::reply_other(
701 &crate::ask::Questions::at(home.join("questions")),
702 &question,
703 &text,
704 )?,
705 Operation::ReconcileRetention {
706 task,
707 authority,
708 apply,
709 } => {
710 let path = Box::pin(crate::retention::reconcile::run_chat(
711 home,
712 &task,
713 &authority,
714 apply.as_deref(),
715 crate::retention::reconcile::ChatRequest {
716 talks,
717 conversation: talk,
718 },
719 ))
720 .await?;
721 if apply.is_none() {
722 crate::retention::reconcile::chat_summary(&path)?
724 } else {
725 format!(
726 "Applied saved plan {}",
727 apply.as_deref().unwrap_or_default()
728 )
729 }
730 }
731 Operation::Abandon { run } => {
732 abandon(queue, home, &run)?;
733 format!("abandoned run {run}")
734 }
735 })
736}
737
738fn file_task(queue: &Queue, filing: Filing) -> Result<Task> {
739 let mut task = Task::new(filing.title, filing.instruction, filing.repo, filing.source);
740 task.sources = filing.sources;
741 if let Some(reason) = filing.hold {
742 task.hold_manual(Some(reason));
743 }
744 task.priority = filing.priority;
745 task.solo = filing.solo;
746 task.urgent = filing.urgent;
747 if filing.implementers.is_some() || filing.build_cache.is_some() {
748 task.overrides = Some(crate::queue::RunOverrides {
749 inherit_daemon_options: filing.implementers.is_none(),
750 candidates: filing.implementers,
751 build_cache: filing.build_cache,
752 ..Default::default()
753 });
754 }
755 if filing.attach.is_empty() {
756 queue.put(&mut task)?;
757 } else {
758 queue.attach_and_put(&mut task, &filing.attach)?;
759 }
760 Ok(task)
761}
762
763fn admit_goal_operation(
765 queue: &Queue,
766 home: &Path,
767 talks: &Talks,
768 talk_id: &str,
769 operation: &Operation,
770) -> Result<()> {
771 let crate::chat_goal::Source::Goal { id, generation } = crate::chat_goal::current_source()
772 else {
773 return Ok(());
774 };
775 let talk = talks.get(talk_id)?;
776 let goal = talk
777 .goals
778 .iter()
779 .find(|goal| goal.id == id)
780 .context("unknown goal")?;
781 goal.admit(generation)?;
782 ensure!(
783 !goal.owner_input.is_empty(),
784 "this goal was registered under standing authorization; fresh owner input is required with the setting off"
785 );
786 let repo = goal.effective_repo(&talk.repo);
787 let task_allowed = |reference: &str| -> Result<()> {
788 let id = queue.resolve_id(reference)?;
789 ensure!(
790 goal.tasks.contains(&id),
791 "effect targets a task outside this goal"
792 );
793 crate::chat_goal::task_record(queue, &id, repo)?;
794 Ok(())
795 };
796 let run_allowed = |run: &str| -> Result<()> {
797 ensure!(
798 goal.runs.iter().any(|id| id == run)
799 || goal
800 .tasks
801 .iter()
802 .any(|id| crate::chat_goal::task_record(queue, id, repo)
803 .is_ok_and(|task| task.execution_runs().iter().any(|id| id == run))),
804 "effect targets an execution outside this goal"
805 );
806 crate::chat_goal::run_record(home, run, repo)?;
807 Ok(())
808 };
809 match operation {
810 Operation::Standing { .. } => bail!("standing authorization is disabled for this turn"),
811 Operation::Goal { .. } => {}
812 Operation::Add { filing } => {
813 crate::chat_goal::require_repo("filing", talk_id, &filing.repo, repo)?;
814 ensure!(
815 matches!(&filing.source, crate::queue::Source::Agent { run, node }
816 if run == talk_id && node == crate::queue::CHAT_NODE),
817 "goal filing must retain this conversation's provenance"
818 );
819 }
820 Operation::Done { discard: true, .. } | Operation::Reopen { .. } => {
821 anyhow::bail!("task discard and reopen require an explicit owner turn");
822 }
823 Operation::Done {
824 task,
825 discard: false,
826 ..
827 }
828 | Operation::Priority { task, .. }
829 | Operation::Hold { task, .. }
830 | Operation::Release { task }
831 | Operation::Retry { task, .. }
832 | Operation::ReconcileRetention { task, .. } => task_allowed(task)?,
833 Operation::GrantRepair { request } => {
834 task_allowed(&request.task)?;
835 run_allowed(&request.run)?;
836 }
837 Operation::ReconcileRepairGrant { request } => {
838 task_allowed(&request.task)?;
839 run_allowed(&request.run)?;
840 }
841 Operation::Resume { run }
842 | Operation::SyncBaseOnly { run }
843 | Operation::RecoverBase { run, .. }
844 | Operation::Abandon { run }
845 | Operation::RerunChecks { run, .. } => run_allowed(run)?,
846 Operation::ForDecision { inquiry, .. }
847 | Operation::ReconcileDecision { inquiry }
848 | Operation::SettleDecision { inquiry, .. } => {
849 let record = crate::task_inquiry::Outbox::at(home).get(inquiry)?;
850 crate::chat_goal::require_repo("inquiry", inquiry, &record.repo, repo)?;
851 task_allowed(&record.task)?;
852 if let Some(run) = record.run {
853 run_allowed(&run)?;
854 }
855 }
856 Operation::Decide { question, .. }
857 | Operation::Answer { question, .. }
858 | Operation::ReplyOther { question, .. } => {
859 let questions = crate::ask::Questions::at(home.join("questions"));
860 let question = questions.get_for_effects(&questions.resolve_id(question)?)?;
861 if question.run_names_task() {
862 task_allowed(&question.run)?;
863 } else {
864 run_allowed(&question.run)?;
865 }
866 }
867 Operation::MergePr {
868 repo: slug, number, ..
869 } => {
870 let expected = format!("https://github.com/{slug}/pull/{number}");
871 let mut found = false;
872 let mut inspect = |run: &str| -> Result<()> {
873 let state = crate::chat_goal::run_record(home, run, repo)?;
874 found |= state
875 .pr
876 .as_ref()
877 .is_some_and(|pr| pr.url.eq_ignore_ascii_case(&expected));
878 Ok(())
879 };
880 for run in &goal.runs {
881 inspect(run)?;
882 }
883 for task in &goal.tasks {
884 for run in crate::chat_goal::task_record(queue, task, repo)?.execution_runs() {
885 inspect(run)?;
886 }
887 }
888 ensure!(found, "merge targets a pull request outside this goal");
889 }
890 Operation::Reassign { .. } => bail!("automatic goal turns cannot change repository scope"),
891 }
892 Ok(())
893}
894
895async fn execute_decision(
900 queue: &Queue,
901 home: &Path,
902 talks: &Talks,
903 chat: &str,
904 id: &str,
905 command: Operation,
906) -> Result<String> {
907 use crate::task_decision::Status;
908 admit_goal_operation(queue, home, talks, chat, &command)?;
909 let outbox = crate::task_inquiry::Outbox::at(home);
910 let _execution = outbox.execution_claim(id)?;
911 let inquiry = outbox.get(id)?;
912 ensure!(
913 inquiry.delivered_to.as_deref() == Some(chat),
914 "decision belongs to another chat"
915 );
916 let task = queue.get(&inquiry.task)?;
917 ensure!(task.repo == inquiry.repo, "decision repository changed");
918 let deferred = matches!(
919 command,
920 Operation::Resume { .. } | Operation::MergePr { .. }
921 );
922 let merge = match &command {
923 Operation::MergePr {
924 repo,
925 number,
926 head,
927 request,
928 } => Some(crate::chat_merge::Request {
929 repo: repo.clone(),
930 number: *number,
931 head: head.clone(),
932 request: request.clone(),
933 }),
934 _ => None,
935 };
936 match &command {
937 Operation::Done { task: target, .. }
938 | Operation::Reopen { task: target, .. }
939 | Operation::Hold { task: target, .. }
940 | Operation::Release { task: target }
941 | Operation::Retry { task: target, .. } => {
942 ensure!(
943 queue.resolve_id(target)? == task.id,
944 "command targets another task"
945 );
946 }
947 Operation::Resume { run }
948 | Operation::Abandon { run }
949 | Operation::RerunChecks { run, .. } => {
950 ensure!(
951 task.runs.contains(run) && inquiry.run.as_ref().is_none_or(|own| own == run),
952 "command targets another execution"
953 );
954 ensure!(
955 queue
956 .list()
957 .iter()
958 .filter(|owner| owner.runs.contains(run))
959 .count()
960 == 1,
961 "execution ownership is ambiguous"
962 );
963 }
964 Operation::MergePr { repo, number, .. } => {
965 let run = inquiry
966 .run
967 .as_ref()
968 .or_else(|| task.runs.last())
969 .context("task has no execution for this merge")?;
970 let state = crate::run::RunState::load_under(run, home)?;
971 ensure!(state.id == *run, "merge run identity changed");
972 ensure!(
973 crate::git::same_checkout(&state.repo, &task.repo)?,
974 "merge targets another repository"
975 );
976 let expected = format!("https://github.com/{repo}/pull/{number}");
977 ensure!(
978 state
979 .pr
980 .as_ref()
981 .is_some_and(|pr| pr.url.eq_ignore_ascii_case(&expected)),
982 "merge targets another task or repository"
983 );
984 }
985 _ => bail!("use a task/run effect command with --decision; routed approvals use decide"),
986 }
987 let request = serde_json::to_string(&command)?;
988 let mut decision = inquiry.decision.context("inquiry is informational")?;
989 if decision.request.is_some()
990 && decision.status != Status::Resolved
991 && let Operation::Resume { run } = &command
992 {
993 ensure!(
994 decision.request.as_deref() == Some(&request),
995 "decision already binds a different request"
996 );
997 reconcile_resume_claimed(queue, home, &outbox, id, run)?;
1002 decision = outbox
1003 .get(id)?
1004 .decision
1005 .context("inquiry is informational")?;
1006 ensure!(
1007 decision.status == Status::Resolved || decision.retry_safe,
1008 "previous resume remains queued or executing; it will not be replayed"
1009 );
1010 }
1011 if decision.status == Status::Resolved {
1012 ensure!(
1013 decision.request.as_deref() == Some(&request),
1014 "decision resolved for a different request"
1015 );
1016 return Ok(format!(
1017 "decision {id} is already resolved; inspect its outcome history"
1018 ));
1019 }
1020 if let Operation::RerunChecks { run, request, .. } = &command {
1021 rerun_preflight(queue, home, run, request)?;
1024 }
1025 if let Some(action) = &merge {
1026 action.validate()?;
1029 }
1030 let merge_admission = merge
1033 .as_ref()
1034 .map(|action| crate::chat_merge::admit(home, talks, chat, action))
1035 .transpose()?;
1036 if decision.request.is_none() && decision.status == Status::RetryNeeded {
1037 if let Ok(source) = crate::ask::Questions::at(home.join("questions")).get(id) {
1038 ensure!(
1039 !crate::task_chat::awaits_decision(&source),
1040 "a legacy effect still needs its receipt reconciled before another effect is accepted"
1041 );
1042 }
1043 }
1044 {
1045 let claim = (queue.get(&task.id)?.status != TaskStatus::Running)
1048 .then(|| queue.claim(&task.id))
1049 .transpose();
1050 let _claim = match claim {
1051 Ok(claim) => claim,
1052 Err(error) => {
1053 let message = format!(
1057 "{error:#}. No effect began; retry this same request after resolving the cause, or explicitly settle it."
1058 );
1059 outbox.update_decision(id, |d| {
1060 let safe = d.request.is_none() || d.retry_safe;
1061 d.accept(&request)?;
1062 if safe {
1063 d.fail_before_effect(&message)
1064 } else {
1065 Ok(false)
1068 }
1069 })?;
1070 return Err(anyhow::Error::new(BeforeEffect(error)));
1071 }
1072 };
1073 outbox.update_decision(id, |d| d.accept(&request))?;
1074 }
1075 let late_admission = crate::chat_goal::fence(talks, chat, &crate::chat_goal::current_source())
1076 .and_then(|()| admit_goal_operation(queue, home, talks, chat, &command));
1077 if late_admission.is_ok()
1078 && decision.request.is_some()
1079 && matches!(decision.status, Status::InProgress | Status::RetryNeeded)
1080 {
1081 if decision.retry_safe {
1082 outbox.update_decision(id, |d| {
1083 d.retry_unapplied()?;
1084 d.start()
1085 })?;
1086 } else {
1087 let action = merge
1088 .as_ref()
1089 .context("previous effect needs receipt reconciliation; it will not be replayed")?;
1090 ensure!(
1091 merge_receipt(home, chat, action)?.is_some(),
1092 "previous merge has no receipt; inspect the operation before retrying"
1093 );
1094 }
1095 } else if late_admission.is_ok() {
1098 outbox.update_decision(id, |d| d.start())?;
1099 }
1100 let local = match late_admission {
1101 Err(error)
1103 if decision.request.is_some()
1104 && !decision.retry_safe
1105 && (matches!(decision.status, Status::InProgress | Status::RetryNeeded)
1106 || decision
1107 .history
1108 .iter()
1109 .any(|event| event.status == Status::InProgress)) =>
1110 {
1111 return Err(error);
1112 }
1113 Err(error) => Err(anyhow::Error::new(BeforeEffect(error))),
1114 Ok(()) => {
1115 Box::pin(apply_local_decision(
1116 queue,
1117 home,
1118 id,
1119 &request,
1120 &inquiry.task,
1121 &inquiry.repo,
1122 &command,
1123 ))
1124 .await
1125 }
1126 };
1127 let result = if let Err(error) = local {
1128 Err(error)
1129 } else if let Some(message) = local? {
1130 Ok(message)
1131 } else if let Operation::Resume { run } = &command {
1132 crate::resume::validate(home, run)
1134 .map(|_| ())
1135 .map_err(|e| anyhow::Error::new(BeforeEffect(e)))
1136 .and_then(|()| -> Result<String> {
1137 let pinned =
1138 crate::resume::pin_queued(queue, run, None, Some(id)).map_err(|error| {
1139 if error.is::<crate::resume::BeforeQueueWrite>() {
1140 anyhow::Error::new(BeforeEffect(error))
1141 } else {
1142 error
1143 }
1144 })?;
1145 if !pinned {
1146 return Err(anyhow::Error::new(BeforeEffect(anyhow::anyhow!(
1147 "no queued task owns this run"
1148 ))));
1149 }
1150 Ok(format!(
1151 "resume queued for {run}; execution start remains unconfirmed"
1152 ))
1153 })
1154 } else if let Operation::Abandon { run } = &command {
1155 crate::driver::abandon_decision(home, run, id, &request)
1156 .map_err(|error| {
1157 if error.is::<crate::driver::BeforeAbandonWrite>() {
1158 anyhow::Error::new(BeforeEffect(error))
1159 } else {
1160 error
1161 }
1162 })
1163 .map(|()| format!("abandoned run {run}"))
1164 } else if let Some(admission) = merge_admission {
1165 crate::chat_merge::merge_admitted(home, merge.as_ref().unwrap().clone(), admission)
1166 .await
1167 .map_err(|error| {
1168 if error.is::<crate::chat_merge::BeforeMergeWrite>() {
1169 anyhow::Error::new(BeforeEffect(error))
1170 } else {
1171 error
1172 }
1173 })
1174 } else {
1175 Box::pin(execute(queue, home, talks, chat, command)).await
1176 };
1177 match result {
1178 Ok(message) => {
1179 if let Some(action) = &merge {
1180 if let Some(receipt) = merge_receipt(home, chat, action)? {
1181 if receipt["status"] == "merged" {
1182 outbox.update_decision(id, |d| d.applied(&message))?;
1183 } else if receipt["status"] != "pending" {
1184 outbox.update_decision(id, |d| {
1185 d.fail(&format!(
1186 "{message}; reuse this same request ID to reconcile only"
1187 ))
1188 })?;
1189 }
1190 }
1191 } else if !deferred {
1192 outbox.update_decision(id, |d| {
1193 d.applied(&format!("typed command completed: {message}"))
1194 })?;
1195 }
1196 if deferred
1197 && outbox
1198 .get(id)?
1199 .decision
1200 .as_ref()
1201 .is_some_and(|d| d.status == Status::InProgress)
1202 {
1203 outbox.update_decision(id, |d| d.queued())?;
1204 }
1205 Ok(message)
1208 }
1209 Err(error) => {
1210 let message = if error.is::<BeforeEffect>() {
1211 format!(
1212 "{error:#}. No effect began; retry this same request after resolving the cause, or explicitly settle it."
1213 )
1214 } else {
1215 format!(
1216 "Operation failed or has an uncertain result: {error:#}. Inspect its receipt before retrying."
1217 )
1218 };
1219 outbox.update_decision(id, |d| {
1220 if error.is::<BeforeEffect>() {
1221 d.fail_before_effect(&message)
1222 } else {
1223 d.fail(&message)
1224 }
1225 })?;
1226 Err(error)
1227 }
1228 }
1229}
1230
1231#[derive(Debug, thiserror::Error)]
1232#[error("effect did not start: {0:#}")]
1233struct BeforeEffect(anyhow::Error);
1234
1235async fn apply_local_decision(
1239 queue: &Queue,
1240 home: &Path,
1241 id: &str,
1242 request: &str,
1243 owner: &str,
1244 repo: &Path,
1245 command: &Operation,
1246) -> Result<Option<String>> {
1247 let target = match command {
1248 Operation::Done { task, .. }
1249 | Operation::Reopen { task, .. }
1250 | Operation::Hold { task, .. }
1251 | Operation::Release { task }
1252 | Operation::Retry { task, .. } => task,
1253 _ => return Ok(None),
1254 };
1255 let prepare = async {
1256 let (_claim, mut task) = claimed(queue, target)?;
1257 let expected = task.clone();
1258 ensure!(
1259 task.id == owner && task.repo == repo,
1260 "decision ownership changed"
1261 );
1262 if let Some(prior) = task.decision_effects.get(id) {
1263 ensure!(prior == request, "decision receipt binds another command");
1264 let message = format!("task {}: decision {id} already applied", task.id);
1265 return Ok((_claim, task, message, true, None, expected));
1266 }
1267 let mut close_guard = None;
1268 let message = match command {
1269 Operation::Done {
1270 reason, discard, ..
1271 } => {
1272 let (guards, context) = crate::task_completion::admit_close(
1273 &task,
1274 home,
1275 crate::queue::CompletionActor::Chat(
1276 crate::task_inquiry::Outbox::at(home)
1277 .get(id)?
1278 .delivered_to
1279 .context("decision has no chat")?,
1280 ),
1281 reason.clone(),
1282 *discard,
1283 )
1284 .await?;
1285 close_guard = Some(guards);
1286 task.succeed(context);
1287 crate::task_completion::describe(&task)
1288 }
1289 Operation::Reopen { reason, .. } => {
1290 let (guards, context) = crate::task_completion::admit_reopen(
1291 &task,
1292 home,
1293 crate::queue::CompletionActor::Chat(
1294 crate::task_inquiry::Outbox::at(home)
1295 .get(id)?
1296 .delivered_to
1297 .context("decision has no chat")?,
1298 ),
1299 reason,
1300 )
1301 .await?;
1302 close_guard = Some(guards);
1303 task.reopen(context)?;
1304 describe(&task, "reopened on hold")
1305 }
1306 Operation::Hold { reason, .. } => {
1307 check_hold_release(&task, "hold")?;
1308 let reason = reason.trim();
1309 task.hold_manual((!reason.is_empty()).then(|| reason.to_owned()));
1310 describe(&task, "held")
1311 }
1312 Operation::Release { .. } => {
1313 check_hold_release(&task, "release")?;
1314 task.release_operator("chat", Some(id));
1315 describe(&task, "released")
1316 }
1317 Operation::Retry {
1318 title, instruction, ..
1319 } => {
1320 ensure!(
1321 !instruction.trim().is_empty(),
1322 "the new instruction is empty"
1323 );
1324 let title = title
1325 .clone()
1326 .unwrap_or_else(|| crate::queue::title_from(instruction, 72));
1327 task.edit(title, instruction.clone())?;
1328 task.release_operator("chat", Some(id));
1329 describe(&task, "retry queued for")
1330 }
1331 _ => unreachable!("task-local operation checked above"),
1332 };
1333 task.decision_effects
1334 .insert(id.to_owned(), request.to_owned());
1335 Ok::<_, anyhow::Error>((_claim, task, message, false, close_guard, expected))
1336 };
1337 let (_claim, mut task, message, already_applied, close_guard, expected) =
1338 prepare.await.map_err(BeforeEffect)?;
1339 if !already_applied {
1340 if close_guard.is_some() {
1341 queue.commit_completion(&mut task, &expected)?;
1342 } else {
1343 queue.put(&mut task)?;
1344 }
1345 }
1346 if matches!(command, Operation::Done { .. }) {
1347 crate::daemon::supersede_prior_runs(&task, home);
1348 }
1349 Ok(Some(message))
1350}
1351
1352fn reconcile_task_decision(queue: &Queue, home: &Path, chat: &str, id: &str) -> Result<()> {
1356 let outbox = crate::task_inquiry::Outbox::at(home);
1357 let inquiry = outbox.get(id)?;
1358 ensure!(
1359 inquiry.delivered_to.as_deref() == Some(chat)
1360 || (inquiry.task.is_empty() && inquiry.delivered_to.is_none()),
1361 "decision belongs to another chat"
1362 );
1363 let decision = inquiry.decision.context("inquiry is informational")?;
1364 if decision.status == crate::task_decision::Status::Resolved {
1365 return Ok(());
1366 }
1367 if decision
1368 .request
1369 .as_ref()
1370 .is_none_or(|request| request.starts_with("decision: "))
1371 {
1372 let source = crate::ask::Questions::at(home.join("questions")).read_history(id)?;
1373 crate::task_chat::sync_effect_receipt(home, queue, &source);
1374 ensure!(
1375 outbox
1376 .get(id)?
1377 .decision
1378 .is_some_and(|d| d.status == crate::task_decision::Status::Resolved),
1379 "source effect remains unconfirmed; no operation was replayed"
1380 );
1381 return Ok(());
1382 }
1383 let request = decision
1384 .request
1385 .context("decision has no accepted operation to reconcile")?;
1386 let command: Operation = serde_json::from_str(&request)?;
1387 if let Operation::Resume { run } = &command {
1388 reconcile_resume_decision(queue, home, &outbox, id, run)?;
1389 ensure!(
1390 outbox.get(id)?.decision.is_some_and(|d| {
1391 d.status == crate::task_decision::Status::Resolved || d.retry_safe
1392 }),
1393 "resume remains queued or executing; no operation was replayed"
1394 );
1395 return Ok(());
1396 }
1397 let (_claim, task) = claimed(queue, &inquiry.task)?;
1398 ensure!(task.repo == inquiry.repo, "decision repository changed");
1399 if let Some(receipt) = task.decision_effects.get(id) {
1400 ensure!(
1401 receipt == &request,
1402 "decision receipt binds another command"
1403 );
1404 return outbox.update_decision(id, |d| {
1405 d.applied("exact task command receipt confirmed; no operation replayed")
1406 });
1407 }
1408 let matches = match command {
1409 Operation::Hold {
1410 task: target,
1411 reason,
1412 } => {
1413 queue.resolve_id(&target)? == task.id
1414 && task.status == TaskStatus::Held
1415 && task.hold_reason.as_deref() == Some(reason.trim())
1416 }
1417 Operation::Release { task: target } => {
1418 queue.resolve_id(&target)? == task.id
1419 && task.status == TaskStatus::Queued
1420 && !task.operator_held()
1421 }
1422 Operation::Done { task: target, .. } => {
1423 queue.resolve_id(&target)? == task.id && task.status == TaskStatus::Done
1424 }
1425 Operation::Retry {
1426 task: target,
1427 title,
1428 instruction,
1429 } => {
1430 queue.resolve_id(&target)? == task.id
1431 && task.instruction == instruction
1432 && title.as_ref().is_none_or(|title| *title == task.title)
1433 && task.status == TaskStatus::Queued
1434 }
1435 Operation::Abandon { run } => abandonment_receipt(home, &task, id, &run, &request)?,
1436 _ => anyhow::bail!(
1437 "external effects require their authoritative receipt; no operation was replayed"
1438 ),
1439 };
1440 ensure!(
1441 matches,
1442 "intended task condition is not confirmed; no operation was replayed"
1443 );
1444 outbox.update_decision(id, |d| d.applied("owner-requested reconciliation: exact intended task condition confirmed under its claim; no effect remains necessary"))
1445}
1446
1447pub(crate) fn resume_started(home: &Path, task: &Task, inquiry: &str, run: &str) -> Result<bool> {
1450 ensure!(
1451 crate::run::is_run_id(run) && task.runs.iter().any(|id| id == run),
1452 "resume run ownership changed"
1453 );
1454 let state = crate::run::RunState::load_under(run, home)?;
1455 ensure!(state.id == run, "resume run identity changed");
1456 ensure!(
1457 crate::git::same_checkout(&state.repo, &task.repo)?,
1458 "resume run repository changed"
1459 );
1460 if task
1461 .superseded_resumes
1462 .get(inquiry)
1463 .is_some_and(|target| target == run)
1464 {
1465 return Ok(true);
1466 }
1467 Ok(state.decision_starts.get(inquiry).is_some_and(|index| {
1468 state
1469 .passes
1470 .get(*index)
1471 .is_some_and(|pass| pass.index == *index)
1472 }))
1473}
1474
1475fn reconcile_resume_decision(
1479 queue: &Queue,
1480 home: &Path,
1481 outbox: &crate::task_inquiry::Outbox,
1482 id: &str,
1483 run: &str,
1484) -> Result<()> {
1485 let Ok(_execution) = outbox.execution_claim(id) else {
1486 return Ok(());
1487 };
1488 reconcile_resume_claimed(queue, home, outbox, id, run)
1489}
1490
1491fn reconcile_resume_claimed(
1493 queue: &Queue,
1494 home: &Path,
1495 outbox: &crate::task_inquiry::Outbox,
1496 id: &str,
1497 run: &str,
1498) -> Result<()> {
1499 let inquiry = outbox.get(id)?;
1500 let Ok(_claim) = queue.claim(&inquiry.task) else {
1501 return Ok(());
1502 };
1503 let task = queue.get(&inquiry.task)?;
1504 ensure!(task.repo == inquiry.repo, "resume task repository changed");
1505 let decision = inquiry.decision.context("inquiry is informational")?;
1506 if decision.status == crate::task_decision::Status::Resolved {
1507 return Ok(());
1508 }
1509 if resume_started(home, &task, id, run)? {
1510 outbox.update_decision(id, |d| {
1511 d.applied("exact resume execution-start or supersession receipt confirmed")
1512 })?;
1513 } else if !task.action_applied(id)
1514 && !task.dispatched_resumes.contains_key(id)
1515 && !task.superseded_resumes.contains_key(id)
1516 && !task
1517 .resume_override
1518 .as_ref()
1519 .is_some_and(|pin| pin.question_id == id)
1520 {
1521 outbox.update_decision(id, |d| {
1522 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.")
1523 })?;
1524 }
1525 Ok(())
1526}
1527
1528fn abandonment_receipt(
1529 home: &Path,
1530 task: &Task,
1531 id: &str,
1532 run: &str,
1533 request: &str,
1534) -> Result<bool> {
1535 ensure!(
1536 task.runs.iter().any(|own| own == run),
1537 "abandon run ownership changed"
1538 );
1539 let state = crate::run::RunState::load_under(run, home)?;
1540 ensure!(state.id == run, "abandon run identity changed");
1541 ensure!(
1542 crate::git::same_checkout(&state.repo, &task.repo)?,
1543 "abandon run repository changed"
1544 );
1545 Ok(state
1546 .abandonment_receipts
1547 .get(id)
1548 .is_some_and(|receipt| receipt == request))
1549}
1550
1551fn merge_receipt(
1552 home: &Path,
1553 chat: &str,
1554 action: &crate::chat_merge::Request,
1555) -> Result<Option<serde_json::Value>> {
1556 ensure!(
1557 crate::ask::valid_asset_name(chat) && crate::ask::valid_asset_name(&action.request),
1558 "invalid merge receipt identity"
1559 );
1560 let path = home
1561 .join("chat-controls")
1562 .join(chat)
1563 .join(format!("{}.json", action.request));
1564 let bytes = match std::fs::read(path) {
1565 Ok(bytes) => bytes,
1566 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
1567 Err(error) => return Err(error.into()),
1568 };
1569 let receipt: serde_json::Value = serde_json::from_slice(&bytes)?;
1570 ensure!(
1571 receipt["action"] == serde_json::to_value(action)?,
1572 "merge receipt names another operation"
1573 );
1574 Ok(Some(receipt))
1575}
1576
1577pub fn reconcile_decisions(queue: &Queue, home: &Path) -> Result<()> {
1580 let outbox = crate::task_inquiry::Outbox::at(home);
1581 let (inquiries, unreadable) = outbox.list_readable()?;
1582 let mut errors = Vec::new();
1583 if unreadable != 0 {
1584 errors.push(format!("{unreadable} unreadable inquiry record(s)"));
1585 }
1586 for inquiry in inquiries {
1587 let id = inquiry.id.clone();
1588 if let Err(error) = reconcile_inquiry(queue, home, &outbox, inquiry) {
1589 let message = format!(
1590 "Decision receipt reconciliation failed: {error:#}. Inspect this inquiry's receipt before retrying."
1591 );
1592 tracing::warn!("decision {id}: {message}");
1593 if let Err(error) = outbox.update_decision(&id, |d| d.fail(&message)) {
1594 tracing::warn!("decision {id} error could not be persisted: {error:#}");
1595 }
1596 errors.push(format!("{id}: {message}"));
1597 }
1598 }
1599 ensure!(
1600 errors.is_empty(),
1601 "{} decision reconciliation problem(s): {}",
1602 errors.len(),
1603 errors.join("; ")
1604 );
1605 Ok(())
1606}
1607
1608fn reconcile_inquiry(
1609 queue: &Queue,
1610 home: &Path,
1611 outbox: &crate::task_inquiry::Outbox,
1612 inquiry: crate::task_inquiry::Inquiry,
1613) -> Result<()> {
1614 use crate::task_decision::Status;
1615 let Some(decision) = inquiry.decision else {
1616 return Ok(());
1617 };
1618 if decision.status == Status::Resolved {
1619 return Ok(());
1620 }
1621 let Some(request) = decision.request else {
1622 return Ok(());
1623 };
1624 let Ok(command) = serde_json::from_str::<Operation>(&request) else {
1625 return Ok(());
1626 };
1627 if let Operation::Resume { run } = &command {
1628 return reconcile_resume_decision(queue, home, outbox, &inquiry.id, run);
1629 }
1630 let task = queue.get(&inquiry.task)?;
1631 ensure!(task.repo == inquiry.repo, "decision repository changed");
1632 if let Some(receipt) = task.decision_effects.get(&inquiry.id) {
1633 ensure!(
1634 receipt == &request,
1635 "decision receipt binds another command"
1636 );
1637 outbox.update_decision(&inquiry.id, |d| {
1638 d.applied("exact task command receipt confirmed after restart")
1639 })?;
1640 return Ok(());
1641 }
1642 let mut pending_external = false;
1643 let receipt = match command {
1644 Operation::Abandon { run } => {
1645 abandonment_receipt(home, &task, &inquiry.id, &run, &request)?
1646 .then(|| format!("run {run}: exact abandonment receipt committed"))
1647 }
1648 Operation::RerunChecks {
1649 request,
1650 run,
1651 head,
1652 workflows,
1653 } => {
1654 let chat = inquiry.delivered_to.as_deref().unwrap_or_default();
1655 let path = home
1656 .join("chat-controls")
1657 .join(chat)
1658 .join(format!("{request}.json"));
1659 let state = crate::run::RunState::load_under(&run, home)?;
1660 let action = serde_json::json!({
1661 "run": run, "repo": state.repo,
1662 "pr": state.pr.as_ref().map(|pr| pr.url.as_str()),
1663 "head": head, "runs": workflows,
1664 });
1665 std::fs::read(path)
1666 .ok()
1667 .and_then(|bytes| serde_json::from_slice::<serde_json::Value>(&bytes).ok())
1668 .filter(|receipt| receipt["status"] == "applied" && receipt["action"] == action)
1669 .map(|_| format!("chat-controls/{chat}/{request}.json: applied"))
1670 }
1671 Operation::MergePr {
1672 repo,
1673 number,
1674 head,
1675 request,
1676 } => {
1677 let action = crate::chat_merge::Request {
1678 repo,
1679 number,
1680 head,
1681 request,
1682 };
1683 let chat = inquiry
1684 .delivered_to
1685 .as_deref()
1686 .context("merge decision has no chat")?;
1687 let receipt = merge_receipt(home, chat, &action)?;
1688 pending_external = receipt
1689 .as_ref()
1690 .is_some_and(|receipt| receipt["status"] == "pending");
1691 if let Some(receipt) = &receipt
1692 && receipt["status"] != "merged"
1693 && receipt["status"] != "pending"
1694 {
1695 outbox.update_decision(&inquiry.id, |d| d.fail(&format!("Merge outcome requires reconciliation: {}. Reuse the same request ID to check only.", receipt["detail"])))?;
1696 }
1697 receipt
1698 .filter(|receipt| receipt["status"] == "merged")
1699 .map(|receipt| format!("confirmed merge receipt: {}", receipt["detail"]))
1700 }
1701 _ => None,
1702 };
1703 if let Some(receipt) = receipt {
1704 outbox.update_decision(&inquiry.id, |d| d.applied(&receipt))?;
1705 } else if decision.status == Status::InProgress
1706 && !pending_external
1707 && outbox
1708 .get(&inquiry.id)?
1709 .decision
1710 .as_ref()
1711 .is_some_and(|d| d.status == Status::InProgress)
1712 {
1713 let talks = Talks::at(home.join("talks"));
1714 let chat = inquiry
1715 .delivered_to
1716 .as_deref()
1717 .context("executing decision has no chat")?;
1718 if !talks.turn_held(chat) && !crate::chat_worker::turn_worker_active(&talks, chat) {
1719 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."))?;
1720 }
1721 }
1722 Ok(())
1723}
1724
1725pub fn decide(
1729 talks: &Talks,
1730 home: &Path,
1731 talk: &str,
1732 question: &str,
1733 choice: &str,
1734) -> Result<crate::ask::Question> {
1735 authorize(talks, talk, crate::queue::CHAT_NODE)?;
1736 record_decision(home, question, choice, None)
1737}
1738
1739fn record_decision(
1745 home: &Path,
1746 question: &str,
1747 choice: &str,
1748 title: Option<&str>,
1749) -> Result<crate::ask::Question> {
1750 use crate::ask::{Answer, Questions};
1751 let questions = Questions::at(home.join("questions"));
1752 let id = questions.resolve_id(question)?;
1753 let q = questions.get(&id)?;
1754 let queue = Queue::at(home.join("queue"));
1755 let _claims = decision_claims(&queue, &q)?;
1756 for task in queue.list() {
1757 if q.run == task.id
1758 || task.runs.contains(&q.run)
1759 || q.routed_task.as_deref() == Some(&task.id)
1760 {
1761 ensure!(
1762 !task.stale_question(&q),
1763 "question predates task repository reassignment; inspect the current task and release it for fresh execution"
1764 );
1765 }
1766 }
1767 ensure!(
1768 crate::task_chat::awaits_decision(&q),
1769 "question {} is not a decision the machinery waits on; answer it with `magi answer`",
1770 q.short()
1771 );
1772 let (q, ()) = questions.update(&q.id, |r| {
1773 if crate::task_chat::saved_reply_requires_confirmation(home, r) {
1774 ensure!(
1775 crate::task_inquiry::Outbox::at(home)
1776 .get(&r.id)?
1777 .decision
1778 .is_some_and(
1779 |decision| decision.status != crate::task_decision::Status::Resolved
1780 ),
1781 "saved decision is settled; no effect remains necessary"
1782 );
1783 r.status = crate::ask::QuestionStatus::Open;
1784 r.answer = None;
1785 r.answered_at = None;
1786 r.answer_authority = None;
1787 }
1788 ensure!(
1789 r.status.open(),
1790 "question {} is already {}",
1791 r.short(),
1792 r.status.as_str()
1793 );
1794 let reply = r.resolve_reply(choice)?.to_owned();
1795 ensure!(
1796 crate::land::approval(Some(&reply)) != crate::land::Approval::Merge || r.merge_target.is_some()
1797 || !(r.node == crate::land::APPROVAL_NODE || (r.node == crate::bump::NOTICE_NODE && r.seat == "release-watch")),
1798 "approval has no recorded PR/head; recover its target or discuss a non-merge operation in chat"
1799 );
1800 let replacement =
1801 r.node == crate::github_text::ASK_NODE && reply == crate::github_text::USE_MY_TEXT;
1802 ensure!(
1803 replacement || title.is_none(),
1804 "--title is only valid for a publication decision's `use my text` choice"
1805 );
1806 let title = if replacement {
1807 let title =
1808 title.context("use my text needs --title with the literal replacement title")?;
1809 ensure!(
1810 !title.trim().is_empty(),
1811 "replacement title must not be empty"
1812 );
1813 Some(title.to_owned())
1814 } else {
1815 None
1816 };
1817 let answer = if r.free_text() {
1818 Answer::Text(reply)
1819 } else {
1820 Answer::Choice(reply)
1821 };
1822 r.publication_title = title;
1823 r.answer(answer)?;
1824 Ok(())
1825 })?;
1826 Ok(q)
1827}
1828
1829pub(crate) fn decision_claims(
1834 queue: &Queue,
1835 q: &crate::ask::Question,
1836) -> Result<Vec<crate::queue::Claim>> {
1837 let mut owners: Vec<_> = queue
1838 .list()
1839 .into_iter()
1840 .filter(|task| {
1841 q.run == task.id
1842 || task.runs.contains(&q.run)
1843 || q.routed_task.as_deref() == Some(&task.id)
1844 })
1845 .map(|task| task.id)
1846 .collect();
1847 owners.sort();
1848 let mut claims = Vec::new();
1849 if matches!(
1850 q.node.as_str(),
1851 crate::triage::NODE | crate::triage::DEPS_NODE
1852 ) {
1853 for id in &owners {
1854 if queue.get(id)?.status != TaskStatus::Running {
1855 claims.push(queue.claim(id)?);
1856 }
1857 }
1858 }
1859 for id in owners {
1860 ensure!(
1861 !crate::repair_budget::reconcile::superseded_question(&queue.get(&id)?, q),
1862 "question was superseded by explicit repair receipt recovery; inspect the reconciliation receipt"
1863 );
1864 }
1865 Ok(claims)
1866}
1867
1868pub fn authorize(talks: &Talks, run: &str, node: &str) -> Result<Talk> {
1870 if node != crate::queue::CHAT_NODE || run.trim().is_empty() {
1871 bail!("task control requires MAGI_NODE=chat and MAGI_RUN from a standing chat");
1872 }
1873 let id = crate::chat_watch::authorize(talks, run, node)?;
1874 talks.get(&id)
1875}
1876
1877fn run_task(queue: &Queue, run: &str) -> Result<Task> {
1879 ensure!(
1880 crate::run::is_run_id(run),
1881 "an execution command needs the full run id"
1882 );
1883 queue
1884 .list()
1885 .into_iter()
1886 .find(|t| t.runs.iter().any(|r| r == run))
1887 .with_context(|| format!("run {run} belongs to no task"))
1888}
1889
1890fn claimed(queue: &Queue, reference: &str) -> Result<(crate::queue::Claim, Task)> {
1893 let id = queue.resolve_id(reference)?;
1894 let claim = queue
1895 .claim(&id)
1896 .with_context(|| format!("task {id} is claimed by a running daemon"))?;
1897 let task = queue.get(&id)?;
1898 Ok((claim, task))
1899}
1900
1901fn claimed_for_chat(
1902 queue: &Queue,
1903 reference: &str,
1904 talks: &Talks,
1905 chat: &str,
1906) -> Result<(crate::queue::Claim, Task)> {
1907 let claimed = claimed(queue, reference)?;
1908 if let crate::chat_goal::Source::Goal { id, generation } = crate::chat_goal::current_source() {
1909 let talk = talks.get(chat)?;
1910 let goal = talk
1911 .goals
1912 .iter()
1913 .find(|goal| goal.id == id)
1914 .context("unknown goal")?;
1915 goal.admit(generation)?;
1916 let task = &claimed.1;
1917 ensure!(
1918 goal.tasks.contains(&task.id),
1919 "effect targets a task outside this goal"
1920 );
1921 crate::chat_goal::require_repo(
1922 "task",
1923 &task.id,
1924 &task.repo,
1925 goal.effective_repo(&talk.repo),
1926 )?;
1927 }
1928 Ok(claimed)
1929}
1930
1931fn check_hold_release(task: &Task, operation: &str) -> Result<()> {
1932 match task.status {
1933 TaskStatus::Queued
1934 | TaskStatus::Held
1935 | TaskStatus::Failed
1936 | TaskStatus::Blocked
1937 | TaskStatus::Parked => Ok(()),
1938 TaskStatus::Done => bail!(
1939 "cannot {operation} task {} (done): completed work must not be restarted; create a new task instead",
1940 task.id
1941 ),
1942 TaskStatus::Running => bail!(
1943 "cannot {operation} task {} (running): its run may still be active; use resume or abandon for the existing run instead",
1944 task.id
1945 ),
1946 }
1947}
1948
1949pub async fn done(
1951 queue: &Queue,
1952 home: &Path,
1953 reference: &str,
1954 reason: Option<String>,
1955 discard: bool,
1956) -> Result<Task> {
1957 crate::task_completion::close(
1958 queue,
1959 home,
1960 reference,
1961 crate::queue::CompletionActor::Cli,
1962 reason,
1963 discard,
1964 )
1965 .await
1966}
1967
1968pub fn set_priority(queue: &Queue, reference: &str, priority: i32) -> Result<Task> {
1970 priority_claimed(queue, claimed(queue, reference)?, priority)
1971}
1972
1973fn priority_claimed(
1974 queue: &Queue,
1975 (_claim, mut task): (crate::queue::Claim, Task),
1976 priority: i32,
1977) -> Result<Task> {
1978 task.set_priority(priority)?;
1979 queue.put(&mut task)?;
1980 Ok(task)
1981}
1982
1983pub fn hold(queue: &Queue, reference: &str, reason: &str) -> Result<Task> {
1985 hold_claimed(queue, claimed(queue, reference)?, reason)
1986}
1987
1988fn hold_claimed(
1989 queue: &Queue,
1990 (_claim, mut task): (crate::queue::Claim, Task),
1991 reason: &str,
1992) -> Result<Task> {
1993 check_hold_release(&task, "hold")?;
1994 let reason = reason.trim();
1995 task.hold_manual((!reason.is_empty()).then(|| reason.to_owned()));
1996 queue.put(&mut task)?;
1997 Ok(task)
1998}
1999
2000pub fn release(queue: &Queue, reference: &str) -> Result<Task> {
2004 release_claimed(queue, claimed(queue, reference)?)
2005}
2006
2007fn release_claimed(queue: &Queue, (_claim, mut task): (crate::queue::Claim, Task)) -> Result<Task> {
2008 check_hold_release(&task, "release")?;
2009 crate::base_sync_recovery::ensure_generic_release(queue, &task)?;
2010 let run = task.execution_runs().last().cloned();
2011 let preserved = match run {
2012 Some(run) => crate::repair_budget::queue_resumption(queue, &mut task, &run)?,
2013 None => false,
2014 };
2015 if !preserved {
2016 task.release_operator("chat", None);
2017 }
2018 queue.put(&mut task)?;
2019 Ok(task)
2020}
2021
2022pub fn retry(
2027 queue: &Queue,
2028 reference: &str,
2029 title: Option<String>,
2030 instruction: &str,
2031) -> Result<Task> {
2032 retry_claimed(queue, claimed(queue, reference)?, title, instruction)
2033}
2034
2035fn retry_claimed(
2036 queue: &Queue,
2037 (_claim, mut task): (crate::queue::Claim, Task),
2038 title: Option<String>,
2039 instruction: &str,
2040) -> Result<Task> {
2041 ensure!(
2042 !instruction.trim().is_empty(),
2043 "the new instruction is empty"
2044 );
2045 if let Some(state) = crate::base_sync_recovery::held_run(queue, &task)
2046 && state
2047 .base_sync_recovery
2048 .stop
2049 .as_ref()
2050 .is_some_and(|stop| stop.kind == crate::base_sync_recovery::StopKind::Conflict)
2051 {
2052 anyhow::bail!(
2053 "retry cannot authorize editing a retained base-sync stop. {}",
2054 state.base_sync_next_action()
2055 );
2056 }
2057 crate::base_sync_recovery::ensure_generic_release(queue, &task)?;
2058 let title = title.unwrap_or_else(|| crate::queue::title_from(instruction, 72));
2059 task.edit(title, instruction.to_owned())?;
2060 task.release_operator("chat", None);
2061 queue.put(&mut task)?;
2062 Ok(task)
2063}
2064
2065pub fn resume(queue: &Queue, home: &Path, run: &str) -> Result<Task> {
2068 let task = run_task(queue, run)?;
2069 ensure!(
2070 task.execution_runs().last().map(String::as_str) == Some(run),
2071 "only the task's latest run can be resumed"
2072 );
2073 crate::resume::validate(home, run)?;
2074 ensure!(
2075 crate::resume::pin_queued(queue, run, None, None)?,
2076 "no queued task owns run {run}"
2077 );
2078 queue.get(&task.id)
2079}
2080
2081fn rerun_preflight(
2084 queue: &Queue,
2085 home: &Path,
2086 run: &str,
2087 request: &str,
2088) -> Result<crate::run::RunState> {
2089 run_task(queue, run)?;
2090 let state = crate::run::RunState::load_under(run, home)?;
2091 ensure!(state.pr.is_some(), "the run recorded no pull request");
2092 ensure!(
2093 crate::ask::valid_asset_name(request),
2094 "request must be a safe filename of at most 64 bytes"
2095 );
2096 Ok(state)
2097}
2098
2099pub async fn rerun_checks(
2101 queue: &Queue,
2102 home: &Path,
2103 talk: &str,
2104 run: &str,
2105 request: &str,
2106 head: &str,
2107 workflows: &[String],
2108) -> Result<Vec<String>> {
2109 let state = rerun_preflight(queue, home, run, request).map_err(BeforeEffect)?;
2110 let dir = home.join("chat-controls").join(talk);
2111 std::fs::create_dir_all(&dir)?;
2112 let lock = std::fs::OpenOptions::new()
2113 .create(true)
2114 .truncate(false)
2115 .write(true)
2116 .open(dir.join(format!("{request}.lock")))?;
2117 crate::pr_head::try_lock_file(&lock).map_err(|error| BeforeEffect(error.into()))?;
2118 let path = dir.join(format!("{request}.json"));
2119 let pr = &state
2120 .pr
2121 .as_ref()
2122 .context("the run recorded no pull request")?
2123 .url;
2124 let action = serde_json::json!({
2125 "run": run, "repo": state.repo, "pr": pr, "head": head, "runs": workflows
2126 });
2127 if path.exists() {
2128 let prior: serde_json::Value = serde_json::from_slice(&std::fs::read(&path)?)?;
2129 if prior["action"] != action {
2130 return Err(BeforeEffect(anyhow::anyhow!(
2131 "request ID already binds a different operation"
2132 ))
2133 .into());
2134 }
2135 ensure!(
2136 prior["status"] == "applied",
2137 "previous request has an uncertain result; inspect its receipt before a new request"
2138 );
2139 return Ok(workflows.to_vec());
2140 }
2141 let record = |status: &str| -> Result<()> {
2142 let tmp = path.with_extension("tmp");
2143 std::fs::write(
2144 &tmp,
2145 serde_json::to_vec(&serde_json::json!({
2146 "action": action, "status": status
2147 }))?,
2148 )?;
2149 std::fs::rename(tmp, &path)?;
2150 Ok(())
2151 };
2152 let operation = format!("chat:{talk}:{request}");
2153 let started = std::sync::atomic::AtomicBool::new(false);
2154 crate::daemon::rerun_checks_once(home, &operation, &state.repo, pr, head, workflows, || {
2155 started.store(true, std::sync::atomic::Ordering::SeqCst);
2158 record("started")
2159 })
2160 .await
2161 .map_err(|error| {
2162 if started.load(std::sync::atomic::Ordering::SeqCst) {
2163 error
2164 } else {
2165 anyhow::Error::new(BeforeEffect(error))
2166 }
2167 })?;
2168 record("applied")?;
2169 Ok(workflows.to_vec())
2170}
2171
2172pub fn abandon(queue: &Queue, home: &Path, run: &str) -> Result<()> {
2176 run_task(queue, run)?;
2177 crate::driver::abandon_proven_dead(home, run)
2178}
2179
2180pub fn describe(task: &Task, what: &str) -> String {
2182 let status = match task.status {
2183 TaskStatus::Queued => "queued",
2184 _ => task.status.as_str(),
2185 };
2186 format!("{what} {} {} ({status})", task.short(), task.title)
2187}
2188
2189#[cfg(test)]
2190mod tests {
2191 use super::*;
2192 use crate::queue::Source;
2193 use jiff::Timestamp;
2194
2195 fn talk(talks: &Talks, id: &str) -> Talk {
2196 let mut t: Talk = serde_json::from_value(serde_json::json!({
2197 "schema":1,"id":id,"repo":".","agent":"worker","status":"open","turns":[],
2198 "created_at":Timestamp::now(),"updated_at":Timestamp::now(),
2199 "seat":crate::agent::SeatState::new("talk","worker",1)
2200 }))
2201 .unwrap();
2202 talks.put(&mut t).unwrap();
2203 t
2204 }
2205
2206 fn filed(queue: &Queue, talk: &str, text: &str) -> Task {
2207 let mut t = Task::new(
2208 text.into(),
2209 text.into(),
2210 ".".into(),
2211 Source::Agent {
2212 run: talk.into(),
2213 node: crate::queue::CHAT_NODE.into(),
2214 },
2215 );
2216 queue.put(&mut t).unwrap();
2217 t
2218 }
2219
2220 #[tokio::test]
2221 async fn direct_chat_completion_supersedes_the_earlier_blocked_run() {
2222 use crate::run::{RunState, RunStatus};
2223
2224 let dir = tempfile::tempdir().unwrap();
2225 let home = dir.path();
2226 let talks = Talks::at(home.join("talks"));
2227 let queue = Queue::at(home.join("queue"));
2228 let talk = talk(&talks, "talk-a");
2229 let mut task = filed(&queue, &talk.id, "deliver");
2230 for status in [RunStatus::Blocked, RunStatus::Merged] {
2231 let mut run = RunState::new(
2232 task.repo.clone(),
2233 "main".into(),
2234 "base".into(),
2235 task.instruction.clone(),
2236 crate::config::Config::default(),
2237 );
2238 run.status = status;
2239 run.driver_exited = true;
2240 run.reserve_under(home).unwrap();
2241 task.link_run(&run.id);
2242 }
2243 queue.put(&mut task).unwrap();
2244 execute(
2245 &queue,
2246 home,
2247 &talks,
2248 &talk.id,
2249 Operation::Done {
2250 task: task.id.clone(),
2251 reason: None,
2252 discard: false,
2253 },
2254 )
2255 .await
2256 .unwrap();
2257 assert_eq!(
2258 RunState::load_under(&task.runs[0], home).unwrap().status,
2259 RunStatus::Superseded
2260 );
2261 }
2262
2263 #[test]
2264 fn ownerless_import_reconciliation_requires_effect_evidence_not_saved_consent() {
2265 use crate::ask::{Answer, Question, Questions};
2266 let home = tempfile::tempdir().unwrap();
2267 let home = home.path();
2268 let queue = Queue::at(home.join("queue"));
2269 let talks = Talks::at(home.join("talks"));
2270 let questions = Questions::at(home.join("questions"));
2271 let mut q = Question::new(
2272 String::new(),
2273 crate::bump::NOTICE_NODE.into(),
2274 "release-watch".into(),
2275 "Historical release hold".into(),
2276 String::new(),
2277 vec!["hold".into()],
2278 );
2279 q.answer(Answer::Choice("hold".into())).unwrap();
2280 q.answer_delivered = true;
2281 questions.put(&mut q).unwrap();
2282 let source = std::fs::read(questions.path_of(&q.id)).unwrap();
2283 crate::task_chat::sweep(&queue, &talks, &questions, home);
2284 assert!(reconcile_task_decision(&queue, home, "authorized-chat", &q.id).is_err());
2285 let outbox = crate::task_inquiry::Outbox::at(home);
2286 assert_eq!(
2287 outbox.get(&q.id).unwrap().decision.unwrap().status,
2288 crate::task_decision::Status::RetryNeeded
2289 );
2290 let dir = home.join("release-watch-receipts");
2291 std::fs::create_dir_all(&dir).unwrap();
2292 std::fs::write(
2293 dir.join(format!("{}.json", q.id)),
2294 serde_json::to_vec(&crate::release_watch::WatchState {
2295 applied: vec![q.id.clone()],
2296 ..Default::default()
2297 })
2298 .unwrap(),
2299 )
2300 .unwrap();
2301 for _ in 0..2 {
2302 reconcile_task_decision(&queue, home, "authorized-chat", &q.id).unwrap();
2303 }
2304 let decision = outbox.get(&q.id).unwrap().decision.unwrap();
2305 assert_eq!(decision.status, crate::task_decision::Status::Resolved);
2306 assert!(decision.request.is_none());
2307 assert!(decision.source_answer_at.is_none());
2308 assert_eq!(std::fs::read(questions.path_of(&q.id)).unwrap(), source);
2309 assert!(queue.list().is_empty());
2310 assert!(talks.list().is_empty());
2311 }
2312
2313 #[test]
2314 fn resume_recovery_waits_for_the_inquiry_publisher() {
2315 let tmp = tempfile::tempdir().unwrap();
2316 let queue = Queue::at(tmp.path().join("queue"));
2317 let mut task = filed(&queue, "talk-a", "work");
2318 let mut state = crate::run::RunState::new(
2319 task.repo.clone(),
2320 "main".into(),
2321 "base".into(),
2322 "work".into(),
2323 crate::config::Config::default(),
2324 );
2325 state.status = crate::run::RunStatus::Blocked;
2326 state.driver_exited = true;
2327 state.save_under(tmp.path()).unwrap();
2328 task.runs.push(state.id.clone());
2329 queue.put(&mut task).unwrap();
2330 let outbox = crate::task_inquiry::Outbox::at(tmp.path());
2331 let inquiry = outbox
2332 .file(
2333 &task,
2334 Some(state.id.clone()),
2335 "resume".into(),
2336 "Resume?",
2337 "",
2338 )
2339 .unwrap();
2340 let request = serde_json::to_string(&Operation::Resume {
2341 run: state.id.clone(),
2342 })
2343 .unwrap();
2344 outbox
2345 .update_decision(&inquiry.id, |d| {
2346 d.accept(&request)?;
2347 d.start()
2348 })
2349 .unwrap();
2350 let before = outbox.get(&inquiry.id).unwrap().decision.unwrap();
2351 let publisher = outbox.execution_claim(&inquiry.id).unwrap();
2352 reconcile_decisions(&queue, tmp.path()).unwrap();
2353 assert_eq!(outbox.get(&inquiry.id).unwrap().decision.unwrap(), before);
2354 drop(publisher);
2355 reconcile_decisions(&queue, tmp.path()).unwrap();
2356 let recovered = outbox.get(&inquiry.id).unwrap().decision.unwrap();
2357 assert_eq!(recovered.status, crate::task_decision::Status::RetryNeeded);
2358 assert!(recovered.retry_safe);
2359 }
2360
2361 #[tokio::test]
2362 async fn resume_receipt_matches_checkout_root_not_filing_directory() {
2363 use crate::task_decision::Status;
2364 let tmp = tempfile::tempdir().unwrap();
2365 let home = tmp.path();
2366 let repo = home.join("checkout");
2367 let subdir = repo.join("src");
2368 let foreign = home.join("foreign");
2369 std::fs::create_dir_all(&subdir).unwrap();
2370 std::fs::create_dir(&foreign).unwrap();
2371 for checkout in [&repo, &foreign] {
2372 crate::git::git(checkout, &["init", "-q"]).await.unwrap();
2373 }
2374 let queue = Queue::at(home.join("queue"));
2375 let mut task = Task::new("work".into(), "work".into(), subdir, Source::Human);
2376 let mut state = crate::run::RunState::new(
2377 repo,
2378 "main".into(),
2379 "base".into(),
2380 "work".into(),
2381 crate::config::Config::default(),
2382 );
2383 state.reserve_under(home).unwrap();
2384 task.runs.push(state.id.clone());
2385 queue.put(&mut task).unwrap();
2386 let outbox = crate::task_inquiry::Outbox::at(home);
2387 let inquiry = outbox
2388 .file(
2389 &task,
2390 Some(state.id.clone()),
2391 "resume".into(),
2392 "Resume?",
2393 "",
2394 )
2395 .unwrap();
2396 let request = serde_json::to_string(&Operation::Resume {
2397 run: state.id.clone(),
2398 })
2399 .unwrap();
2400 outbox
2401 .update_decision(&inquiry.id, |d| {
2402 d.accept(&request)?;
2403 d.start()
2404 })
2405 .unwrap();
2406 task.dispatched_resumes
2407 .insert(inquiry.id.clone(), state.id.clone());
2408 queue.put(&mut task).unwrap();
2409 reconcile_decisions(&queue, home).unwrap();
2410 assert_eq!(
2411 outbox.get(&inquiry.id).unwrap().decision.unwrap().status,
2412 Status::InProgress
2413 );
2414
2415 state.carry_dispatched_resumes(&task);
2416 state.begin_pass();
2417 state.save_under(home).unwrap();
2418 let mut reassigned = task.clone();
2419 reassigned.repo = foreign;
2420 assert!(resume_started(home, &reassigned, &inquiry.id, &state.id).is_err());
2421 reconcile_decisions(&queue, home).unwrap();
2422 assert_eq!(
2423 outbox.get(&inquiry.id).unwrap().decision.unwrap().status,
2424 Status::Resolved
2425 );
2426 }
2427
2428 #[test]
2429 fn only_the_chat_seat_of_an_open_talk_is_authorized() {
2430 let tmp = tempfile::tempdir().unwrap();
2431 let talks = Talks::at(tmp.path().join("talks"));
2432 let t = talk(&talks, "talk-a");
2433 assert!(authorize(&talks, &t.id, "chat").is_ok());
2434 assert!(authorize(&talks, &t.id, "deputy").is_err());
2435 assert!(authorize(&talks, &t.id, "").is_err());
2436 assert!(authorize(&talks, "", "chat").is_err());
2437 assert!(
2438 authorize(&talks, "talk-", "chat").is_err(),
2439 "prefix is not an id"
2440 );
2441 }
2442
2443 #[test]
2444 fn tasks_of_any_origin_are_controlled_on_request() {
2445 let tmp = tempfile::tempdir().unwrap();
2446 let queue = Queue::at(tmp.path().join("queue"));
2447 let theirs = filed(&queue, "talk-b", "theirs");
2448 let mut hand = Task::new("h".into(), "h".into(), ".".into(), Source::Human);
2449 hand.hold_manual(Some("operator".into()));
2450 queue.put(&mut hand).unwrap();
2451 assert_eq!(
2454 hold(&queue, &theirs.id, "wait").unwrap().status,
2455 TaskStatus::Held
2456 );
2457 assert_eq!(
2458 release(&queue, &hand.id).unwrap().status,
2459 TaskStatus::Queued
2460 );
2461 let again = retry(&queue, &theirs.id, None, "new").unwrap();
2462 assert_eq!(again.instruction, "new");
2463 assert_eq!(again.status, TaskStatus::Queued);
2464 }
2465
2466 #[test]
2467 fn hold_then_release_keeps_history_and_restarts_attempts() {
2468 let tmp = tempfile::tempdir().unwrap();
2469 let queue = Queue::at(tmp.path().join("queue"));
2470 let mut t = filed(&queue, "talk-a", "work");
2471 t.attempts = 3;
2472 t.runs.push("20260101-000000-aaaa".into());
2473 queue.put(&mut t).unwrap();
2474 let held = hold(&queue, &t.id, "owner asked").unwrap();
2475 assert_eq!(held.status, TaskStatus::Held);
2476 assert_eq!(held.hold_reason.as_deref(), Some("owner asked"));
2477 let back = release(&queue, &t.id).unwrap();
2478 assert_eq!(back.status, TaskStatus::Queued);
2479 assert_eq!(back.attempts, 0);
2480 assert_eq!(back.runs, t.runs);
2481 assert!(back.resumption.is_some());
2482 }
2483
2484 #[test]
2485 fn hold_and_release_refuse_done_and_running_without_saving() {
2486 let tmp = tempfile::tempdir().unwrap();
2487 let queue = Queue::at(tmp.path().join("queue"));
2488 for status in [TaskStatus::Done, TaskStatus::Running] {
2489 let mut t = filed(&queue, "talk-a", "work");
2490 t.start("20260101-000000-aaaa".into());
2491 if status == TaskStatus::Done {
2492 t.succeed(crate::queue::CompletionContext::new(
2493 crate::queue::CompletionActor::Cli,
2494 None,
2495 tmp.path(),
2496 &t,
2497 ));
2498 }
2499 queue.put(&mut t).unwrap();
2500 let before = std::fs::read(queue.path_of(&t.id)).unwrap();
2501 for operation in ["hold", "release"] {
2502 let error = if operation == "hold" {
2503 hold(&queue, &t.id, "owner asked")
2504 } else {
2505 release(&queue, &t.id)
2506 }
2507 .unwrap_err()
2508 .to_string();
2509 assert!(error.contains(operation), "{error}");
2510 assert!(error.contains(&t.id), "{error}");
2511 assert!(error.contains(status.as_str()), "{error}");
2512 let guidance = if status == TaskStatus::Done {
2513 "create a new task"
2514 } else {
2515 "use resume or abandon"
2516 };
2517 assert!(error.contains(guidance), "{error}");
2518 assert_eq!(std::fs::read(queue.path_of(&t.id)).unwrap(), before);
2519 }
2520 }
2521 }
2522
2523 #[test]
2524 fn hold_and_release_allow_unfinished_inactive_tasks() {
2525 let tmp = tempfile::tempdir().unwrap();
2526 let queue = Queue::at(tmp.path().join("queue"));
2527 for status in [
2528 TaskStatus::Queued,
2529 TaskStatus::Held,
2530 TaskStatus::Failed,
2531 TaskStatus::Blocked,
2532 TaskStatus::Parked,
2533 ] {
2534 for operation in ["hold", "release"] {
2535 let mut t = filed(&queue, "talk-a", "work");
2536 t.status = status;
2537 t.hold_reason = Some("old reason".into());
2538 t.attempts = 3;
2539 t.runs.push("20260101-000000-aaaa".into());
2540 queue.put(&mut t).unwrap();
2541 let changed = if operation == "hold" {
2542 let held = hold(&queue, &t.id, " new reason ").unwrap();
2543 assert_eq!(held.status, TaskStatus::Held);
2544 assert_eq!(held.hold_reason.as_deref(), Some("new reason"));
2545 assert_eq!(held.attempts, t.attempts);
2546 held
2547 } else {
2548 let released = release(&queue, &t.id).unwrap();
2549 assert_eq!(released.status, TaskStatus::Queued);
2550 assert_eq!(released.attempts, 0);
2551 assert_eq!(released.resumption.as_ref().unwrap().source, "chat");
2552 released
2553 };
2554 assert_eq!(changed.runs, t.runs);
2555 assert_eq!(queue.get(&t.id).unwrap().status, changed.status);
2556 }
2557 }
2558 }
2559
2560 #[test]
2561 fn retry_edits_and_requeues_in_one_save() {
2562 let tmp = tempfile::tempdir().unwrap();
2563 let queue = Queue::at(tmp.path().join("queue"));
2564 let mut t = filed(&queue, "talk-a", "old text");
2565 t.runs.push("20260101-000000-aaaa".into());
2566 t.attempts = 2;
2567 t.hold_manual(Some("stopped".into()));
2568 queue.put(&mut t).unwrap();
2569 let again = retry(&queue, &t.id, None, "new text").unwrap();
2570 assert_eq!(again.instruction, "new text");
2571 assert_eq!(again.status, TaskStatus::Queued);
2572 assert_eq!(again.attempts, 0);
2573 assert_eq!(again.runs, t.runs, "run history is kept");
2574 assert_eq!(again.resumption.as_ref().unwrap().source, "chat");
2575 assert_eq!(again.resumption.as_ref().unwrap().instruction, "new text");
2576 let mut running = filed(&queue, "talk-a", "busy");
2578 running.start("20260101-000000-bbbb".into());
2579 queue.put(&mut running).unwrap();
2580 assert!(retry(&queue, &running.id, None, "x").is_err());
2581 assert_eq!(queue.get(&running.id).unwrap().instruction, "busy");
2582 assert!(retry(&queue, &t.id, None, " ").is_err());
2583 }
2584
2585 #[test]
2586 fn execution_commands_need_the_full_id_of_a_recorded_run() {
2587 let tmp = tempfile::tempdir().unwrap();
2588 let queue = Queue::at(tmp.path().join("queue"));
2589 let mut t = filed(&queue, "talk-b", "work");
2590 t.runs.push("20260101-000000-aaaa".into());
2591 queue.put(&mut t).unwrap();
2592 assert_eq!(
2593 run_task(&queue, "20260101-000000-aaaa").unwrap().id,
2594 t.id,
2595 "any chat may address another chat's run"
2596 );
2597 assert!(run_task(&queue, "aaaa").is_err());
2598 assert!(run_task(&queue, "20260101-000000-bbbb").is_err());
2599 assert!(resume(&queue, tmp.path(), "aaaa").is_err());
2600 }
2601
2602 #[test]
2603 fn abandon_needs_no_phrase_but_refuses_unrecorded_and_unknown_runs() {
2604 let tmp = tempfile::tempdir().unwrap();
2605 let queue = Queue::at(tmp.path().join("queue"));
2606 let mut t = filed(&queue, "talk-b", "work");
2607 t.runs.push("20260101-000000-aaaa".into());
2608 queue.put(&mut t).unwrap();
2609 assert!(abandon(&queue, tmp.path(), "20260101-000000-bbbb").is_err());
2611 assert!(abandon(&queue, tmp.path(), "20260101-000000-aaaa").is_err());
2614 }
2615}
2616
2617#[cfg(test)]
2618mod goal_admission_tests {
2619 use super::*;
2620
2621 #[tokio::test]
2622 async fn goal_effects_require_current_generation_scope_and_no_new_owner_input() {
2623 let tmp = tempfile::tempdir().unwrap();
2624 let talks = Talks::at(tmp.path().join("talks"));
2625 let queue = Queue::at(tmp.path().join("queue"));
2626 let target = tmp.path().join("target");
2627 std::fs::create_dir(&target).unwrap();
2628 crate::git::git(&target, &["init", "-q"]).await.unwrap();
2629 let mut talk = crate::talk::seeded_for_test("goal-effect", tmp.path().into());
2630 talk.turns.push(
2631 serde_json::from_value(serde_json::json!({
2632 "sender": "operator", "who": "operator", "body": "Follow this task through",
2633 "at": jiff::Timestamp::now()
2634 }))
2635 .unwrap(),
2636 );
2637 talks.put(&mut talk).unwrap();
2638 let mut task = Task::new(
2639 "work".into(),
2640 "work".into(),
2641 target.clone(),
2642 crate::queue::Source::Agent {
2643 run: talk.id.clone(),
2644 node: crate::queue::CHAT_NODE.into(),
2645 },
2646 );
2647 queue.put(&mut task).unwrap();
2648 let mut unrelated = Task::new(
2649 "other".into(),
2650 "other".into(),
2651 target.clone(),
2652 crate::queue::Source::Agent {
2653 run: talk.id.clone(),
2654 node: crate::queue::CHAT_NODE.into(),
2655 },
2656 );
2657 queue.put(&mut unrelated).unwrap();
2658 crate::chat_goal::apply(
2659 &queue,
2660 tmp.path(),
2661 &talks,
2662 &talk.id,
2663 &crate::chat_goal::Source::Input { turn: 0 },
2664 crate::chat_goal::Command::Establish {
2665 id: "g".into(),
2666 purpose: "Deliver this task".into(),
2667 scope: "This task only".into(),
2668 condition: "Verified delivery".into(),
2669 completion: crate::chat_goal::Completion::TasksDone,
2670 repo: Some(target),
2671 tasks: vec![task.id.clone()],
2672 runs: vec![],
2673 watches: vec![],
2674 },
2675 )
2676 .await
2677 .unwrap();
2678 talks
2679 .mutate(&talk.id, |talk| {
2680 let boundary = talk.turns.len();
2681 let goal = &mut talk.goals[0];
2682 goal.wake = 1;
2683 goal.started = Some(1);
2684 goal.launch_turns = Some(boundary);
2685 Ok(())
2686 })
2687 .unwrap();
2688 let source = crate::chat_goal::Source::Goal {
2689 id: "g".into(),
2690 generation: 1,
2691 };
2692 assert!(
2693 execute_authenticated(
2694 &queue,
2695 tmp.path(),
2696 &talks,
2697 &talk.id,
2698 source.clone(),
2699 Operation::Priority {
2700 task: unrelated.id.clone(),
2701 priority: 8
2702 }
2703 )
2704 .await
2705 .is_err()
2706 );
2707 execute_authenticated(
2708 &queue,
2709 tmp.path(),
2710 &talks,
2711 &talk.id,
2712 source.clone(),
2713 Operation::Priority {
2714 task: task.id.clone(),
2715 priority: 3,
2716 },
2717 )
2718 .await
2719 .unwrap();
2720 let hold = Operation::Hold {
2721 task: task.id.clone(),
2722 reason: "pause".into(),
2723 };
2724 crate::chat_goal::with_source(source.clone(), async {
2725 admit_goal_operation(&queue, tmp.path(), &talks, &talk.id, &hold).unwrap();
2728 let original = task.repo.clone();
2729 {
2730 let claim = queue.claim(&task.id).unwrap();
2731 task = queue.get(&task.id).unwrap();
2732 task.repo = talk.repo.clone();
2733 queue.put(&mut task).unwrap();
2734 drop(claim);
2735 }
2736 let result = claimed_for_chat(&queue, &task.id, &talks, &talk.id)
2737 .and_then(|claimed| hold_claimed(&queue, claimed, "pause"));
2738 assert!(result.unwrap_err().to_string().contains(&task.id));
2739 assert_eq!(queue.get(&task.id).unwrap().status, TaskStatus::Queued);
2740 task.repo = original;
2741 queue.put(&mut task).unwrap();
2742 })
2743 .await;
2744 let error = execute_authenticated(
2745 &queue,
2746 tmp.path(),
2747 &talks,
2748 &talk.id,
2749 source.clone(),
2750 Operation::Done {
2751 task: task.id.clone(),
2752 reason: Some("discard unfinished work".into()),
2753 discard: true,
2754 },
2755 )
2756 .await
2757 .unwrap_err();
2758 assert!(
2759 error.to_string().contains("explicit owner turn"),
2760 "{error:#}"
2761 );
2762 assert_eq!(queue.get(&task.id).unwrap().status, TaskStatus::Queued);
2763 assert!(queue.get(&task.id).unwrap().completion_history.is_empty());
2764 assert!(
2765 execute_authenticated(
2766 &queue,
2767 tmp.path(),
2768 &talks,
2769 &talk.id,
2770 source.clone(),
2771 Operation::Done {
2772 task: unrelated.id.clone(),
2773 reason: None,
2774 discard: false,
2775 },
2776 )
2777 .await
2778 .is_err()
2779 );
2780 execute_authenticated(
2781 &queue,
2782 tmp.path(),
2783 &talks,
2784 &talk.id,
2785 source.clone(),
2786 Operation::Done {
2787 task: task.id.clone(),
2788 reason: Some("goal work finished".into()),
2789 discard: false,
2790 },
2791 )
2792 .await
2793 .unwrap();
2794 let error = execute_authenticated(
2795 &queue,
2796 tmp.path(),
2797 &talks,
2798 &talk.id,
2799 source.clone(),
2800 Operation::Reopen {
2801 task: task.id.clone(),
2802 reason: "recover unfinished work".into(),
2803 },
2804 )
2805 .await
2806 .unwrap_err();
2807 assert!(
2808 error.to_string().contains("explicit owner turn"),
2809 "{error:#}"
2810 );
2811 assert_eq!(queue.get(&task.id).unwrap().status, TaskStatus::Done);
2812 execute_authenticated(
2813 &queue,
2814 tmp.path(),
2815 &talks,
2816 &talk.id,
2817 crate::chat_goal::Source::Input { turn: 0 },
2818 Operation::Reopen {
2819 task: task.id.clone(),
2820 reason: "recover unfinished work".into(),
2821 },
2822 )
2823 .await
2824 .unwrap();
2825 assert_eq!(queue.get(&task.id).unwrap().status, TaskStatus::Held);
2826 talks
2827 .mutate(&talk.id, |talk| {
2828 talk.turns.push(serde_json::from_value(serde_json::json!({
2829 "sender": "operator", "who": "operator", "body": "Stop",
2830 "at": jiff::Timestamp::now()
2831 }))?);
2832 Ok(())
2833 })
2834 .unwrap();
2835 assert!(
2836 execute_authenticated(
2837 &queue,
2838 tmp.path(),
2839 &talks,
2840 &talk.id,
2841 source.clone(),
2842 Operation::Priority {
2843 task: task.id.clone(),
2844 priority: 9
2845 }
2846 )
2847 .await
2848 .is_err()
2849 );
2850 talks
2851 .mutate(&talk.id, |talk| {
2852 talk.turns.pop();
2853 talk.goals[0].state = crate::chat_goal::State::Stopped;
2854 talk.goals[0].wake = 2;
2855 talk.goals[0].started = None;
2856 Ok(())
2857 })
2858 .unwrap();
2859 assert!(
2860 execute_authenticated(
2861 &queue,
2862 tmp.path(),
2863 &talks,
2864 &talk.id,
2865 source,
2866 Operation::Priority {
2867 task: task.id.clone(),
2868 priority: 9
2869 }
2870 )
2871 .await
2872 .is_err()
2873 );
2874 assert_eq!(queue.get(&task.id).unwrap().priority, 3);
2875 }
2876}