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