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