1use std::collections::{BTreeMap, BTreeSet};
44use std::path::{Path, PathBuf};
45use std::time::Duration;
46
47use anyhow::{Context as _, Result};
48use serde::{Deserialize, Serialize};
49
50use crate::agent::{self, Invocation, SeatState};
51use crate::ask::{ChoiceAction, Deputy, Question, Questions};
52use crate::config::Config;
53use crate::prompt;
54use crate::queue::{Queue, Task, TaskStatus};
55use crate::run::RunState;
56use crate::verdict;
57
58const SEAT: &str = "conduct";
61
62pub const NODE: &str = "conduct";
66
67const TURN_TIMEOUT: Duration = Duration::from_secs(300);
72
73#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
76#[serde(rename_all = "lowercase")]
77pub enum Recovery {
78 Requeue,
81 Hold,
84 Review,
89 Done,
97}
98
99#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
102#[serde(rename_all = "snake_case")]
103pub enum QuestionOperation {
104 Recover,
106 Resume,
108 Repair,
110 Complete,
112 Inspect,
114 Configure,
116}
117
118#[derive(Debug, Clone, Deserialize)]
121#[serde(tag = "kind", rename_all = "snake_case")]
122pub enum QuestionTarget {
123 Task,
125 Run {
127 id: String,
129 },
130 Setting {
133 path: String,
135 keys: Vec<String>,
137 },
138 Source {
140 reference: String,
142 },
143}
144
145#[derive(Debug, Clone, Deserialize)]
147pub struct QuestionDecision {
148 pub operation: QuestionOperation,
150 pub target: QuestionTarget,
152}
153
154impl QuestionDecision {
155 fn identity(&self, task: &Task) -> Result<(QuestionOperation, String)> {
156 let target = match &self.target {
157 QuestionTarget::Task => format!("task:{}", task.id),
158 QuestionTarget::Run { id } => {
159 anyhow::ensure!(
160 task.runs.contains(id),
161 "question target is not this task's run"
162 );
163 format!("run:{id}")
164 }
165 QuestionTarget::Setting { path, keys } => {
166 use std::path::Component;
167 anyhow::ensure!(
168 !path.is_empty()
169 && Path::new(path)
170 .components()
171 .all(|c| matches!(c, Component::Normal(_)))
172 && !keys.is_empty()
173 && keys.iter().all(|key| !key.is_empty()),
174 "question setting must name a repository file and concrete keys"
175 );
176 let root = task.repo.canonicalize()?;
177 let file = root.join(path).canonicalize()?;
178 let relative = file
179 .strip_prefix(&root)
180 .context("question setting is outside the repository")?;
181 let content = std::fs::read_to_string(&file)?;
182 let value: toml::Value = toml::from_str(&content)?;
183 let mut setting = &value;
184 for key in keys {
185 setting = setting
186 .get(key)
187 .context("question setting key does not exist")?;
188 }
189 format!("setting:{}", serde_json::to_string(&(relative, keys))?)
190 }
191 QuestionTarget::Source { reference } => {
192 use crate::proc::Quiet as _;
193 let output = std::process::Command::new("git")
194 .args([
195 "rev-parse",
196 "--verify",
197 "--end-of-options",
198 &format!("{reference}^{{commit}}"),
199 ])
200 .current_dir(&task.repo)
201 .quiet()
202 .output()
203 .context("resolve question source")?;
204 anyhow::ensure!(
205 output.status.success(),
206 "question source cannot be resolved"
207 );
208 let commit = String::from_utf8(output.stdout)?.trim().to_owned();
209 anyhow::ensure!(
210 !commit.is_empty() && commit.bytes().all(|c| c.is_ascii_hexdigit()),
211 "invalid question source commit"
212 );
213 format!("source:{commit}")
214 }
215 };
216 Ok((self.operation, target))
217 }
218}
219
220#[derive(Debug, Clone, Default, Deserialize)]
223pub struct Decision {
224 pub id: String,
226 #[serde(default)]
230 pub blocked_by: Vec<String>,
231 #[serde(default)]
236 pub missing_dependencies: Vec<String>,
237 #[serde(default)]
239 pub reason: Option<String>,
240 #[serde(default)]
247 pub recovery: Option<Recovery>,
248 #[serde(default)]
254 pub question: Option<String>,
255 #[serde(default)]
257 pub choices: Vec<String>,
258 #[serde(default)]
260 pub actions: BTreeMap<String, ChoiceAction>,
261 #[serde(default)]
264 pub question_decision: Option<QuestionDecision>,
265 #[serde(default)]
267 pub evidence: Vec<String>,
268}
269
270#[derive(Debug, Clone, Default, Deserialize)]
283pub struct Verdict {
284 pub decisions: Vec<Decision>,
287}
288
289fn view(t: &Task, max_attempts: usize) -> prompt::ConductTask {
292 prompt::ConductTask {
293 id: t.id.clone(),
294 title: t.title.clone(),
295 instruction: t.instruction.clone(),
296 repo: t.repo.display().to_string(),
297 priority: t.priority,
298 status: t.status.as_str().to_owned(),
299 attempts: t.attempts,
300 max_attempts: t.effective_attempt_limit(max_attempts),
301 last_error: t.last_error.clone(),
302 hold_reason: t.hold_reason.clone(),
303 hold_source: t.hold_source.map(|source| source.label().to_owned()),
304 blocked_by: t.blocked_by.clone(),
305 answers: t
306 .answers
307 .iter()
308 .map(|a| prompt::ConductAnswer {
309 question: a.question.clone(),
310 answer: a.answer.clone(),
311 })
312 .collect(),
313 operator_resume: t.resumption.as_ref().map(|r| format!(
314 "Explicit operator resumption generation {} via {} at {}. Approved instruction: {}. \
315 The first {} historical answers and prior hold ({:?}) are superseded as waiting premises. \
316 To block again cite evidence ids from a later owned question, changed dependency, or new failed run; \
317 wording alone is insufficient.",
318 r.generation, r.source, r.at, r.instruction, r.answers_through, r.cleared_reason
319 )).or_else(|| t.resume_override.as_ref().map(|o| {
320 format!(
321 "the operator explicitly answered \"resume\" at {}; do not hold this \
322 task again for the same reason unless there is new information",
323 o.at
324 )
325 })),
326 }
327}
328
329fn pinned_resume(task: &Task) -> bool {
333 task.resume_override
334 .as_ref()
335 .is_some_and(|o| o.pinned_run.is_some())
336}
337
338fn new_blocking_evidence(
341 queue: &Queue,
342 questions: &Questions,
343 task: &Task,
344 d: &Decision,
345) -> Vec<String> {
346 let Some(r) = &task.resumption else {
347 return Vec::new();
348 };
349 d.evidence
350 .iter()
351 .filter_map(|id| {
352 let version = if let Ok(q) = questions.get(id) {
353 (q.asked_at > r.at
354 && (q.run == task.id || task.runs.contains(&q.run))
355 && q.node != NODE
356 && q.status != crate::ask::QuestionStatus::Abandoned)
357 .then(|| {
358 format!(
359 "question:{id}:{}:{:?}:{}",
360 q.asked_at,
361 q.status,
362 q.resolution().unwrap_or_default()
363 )
364 })
365 } else if d.blocked_by.contains(id) {
366 queue
367 .get(id)
368 .ok()
369 .filter(|dep| {
370 dep.id != task.id
371 && dep.status != TaskStatus::Done
372 && (dep.created_at > r.at
373 || dep.held_at.is_some_and(|at| at > r.at)
374 || dep.operator_decided_at.is_some_and(|at| at > r.at)
375 || dep.passes.iter().any(|p| p.settled_at > r.at)
376 || (dep.status == TaskStatus::Blocked
377 && dep.blocked_at.is_some_and(|at| at > r.at)))
378 })
379 .map(|dep| {
380 format!(
381 "dependency:{id}:{:?}:{:?}:{:?}",
382 dep.status,
383 dep.chat_notice_key(),
384 dep.hold_notice_cause
385 )
386 })
387 } else if task.runs.iter().any(|run| run == id) {
388 RunState::load(id)
389 .ok()
390 .filter(|run| {
391 run.updated_at > r.at
394 && run
395 .passes
396 .last()
397 .map_or(run.created_at > r.at, |p| p.started_at > r.at)
398 && matches!(
399 run.status,
400 crate::run::RunStatus::Failed
401 | crate::run::RunStatus::Blocked
402 | crate::run::RunStatus::Stalled
403 )
404 })
405 .map(|run| {
406 format!(
407 "run:{id}:{:?}:{:?}",
408 run.status,
409 run.passes.last().map(|p| p.index)
410 )
411 })
412 } else {
413 None
414 };
415 version.filter(|v| !r.blocking_evidence.contains(v))
416 })
417 .collect()
418}
419
420fn may_hold(task: &mut Task, reason: &str) -> bool {
424 if pinned_resume(task) {
425 return false;
426 }
427 if task.resumption.is_some() {
428 return true; }
430 let Some(o) = task.resume_override.as_mut() else {
431 return true;
432 };
433 if o.forced || o.pinned_run.is_some() {
434 tracing::warn!(
435 "conductor tried to hold task {} after the operator forced a resume: {reason}",
436 task.id
437 );
438 return false;
439 }
440 if o.conductor_rehold.is_some() {
441 return false;
442 }
443 o.conductor_rehold = Some(reason.to_owned());
444 true
445}
446
447fn severity_str(s: crate::verdict::Severity) -> &'static str {
450 match s {
451 crate::verdict::Severity::Nit => "nit",
452 crate::verdict::Severity::Minor => "minor",
453 crate::verdict::Severity::Major => "major",
454 crate::verdict::Severity::Blocker => "blocker",
455 }
456}
457
458fn surviving_branch(task: &Task) -> Option<String> {
463 let last = task.runs.last()?;
464 let state = RunState::load(last).ok()?;
465 if !crate::daemon::compatible_run_instruction(&state, task) {
466 return None;
467 }
468 state.winner().map(|c| c.branch.clone())
469}
470
471fn reaffirmed_hold_reason(task: &Task, d: &Decision) -> Option<String> {
498 let note = match &d.reason {
499 Some(reason) => reason.clone(),
500 None => match task.answers.last() {
501 Some(a) => format!(
502 "conduct held this again with no new reason given; last operator \
503 answer on record: {}",
504 a.answer
505 ),
506 None => "conduct held this again with no reason given".to_owned(),
507 },
508 };
509 match task.hold_reason.as_deref() {
510 Some(prior) if !prior.is_empty() => {
511 let outer = outermost_hold_note(prior);
512 if note.trim() == prior.trim() || note.trim() == outer {
513 None
514 } else {
515 Some(format!("{note}\n\n(previously: {outer})"))
516 }
517 }
518 _ => Some(note),
519 }
520}
521
522const PREVIOUSLY: &str = "\n\n(previously: ";
525
526fn outermost_hold_note(reason: &str) -> &str {
529 reason.split(PREVIOUSLY).next().unwrap_or(reason).trim()
530}
531
532fn hold_note(d: &Decision) -> String {
534 d.reason
535 .clone()
536 .unwrap_or_else(|| "(no reason given)".to_owned())
537}
538
539async fn outcome_for(task: &Task, repo: &Path) -> prompt::ConductOutcome {
541 let Some(run_id) = task.runs.last().cloned() else {
542 return prompt::ConductOutcome {
543 run_id: "(none)".to_owned(),
544 unreadable: Some("this task has not produced a run yet".to_owned()),
545 run_status: None,
546 open_findings: Vec::new(),
547 rounds_used: 0,
548 rounds_max: 0,
549 rounds: Vec::new(),
550 branch: None,
551 branch_head: None,
552 references: None,
553 empty_candidate: false,
554 };
555 };
556 let state = match RunState::load(&run_id) {
557 Ok(s) => s,
558 Err(e) => {
559 tracing::warn!(
564 "conductor: could not read run {run_id} for task {}: {e:#}",
565 task.short()
566 );
567 return prompt::ConductOutcome {
568 run_id,
569 unreadable: Some(format!("{e:#}")),
570 run_status: None,
571 open_findings: Vec::new(),
572 rounds_used: 0,
573 rounds_max: 0,
574 rounds: Vec::new(),
575 branch: None,
576 branch_head: None,
577 references: None,
578 empty_candidate: false,
579 };
580 }
581 };
582
583 let finding_view = |f: &crate::verdict::Finding| prompt::ConductFinding {
584 id: f.id.clone(),
585 title: f.title.clone(),
586 severity: severity_str(f.severity).to_owned(),
587 };
588 let open_findings = state
589 .open_findings()
590 .into_iter()
591 .map(finding_view)
592 .collect();
593 let rounds = state
594 .reviews
595 .iter()
596 .map(|r| prompt::ConductRound {
597 round: r.round,
598 findings: r
599 .reviews
600 .iter()
601 .flat_map(|rec| rec.findings.iter())
602 .map(finding_view)
603 .collect(),
604 addressed: r
605 .fix
606 .as_ref()
607 .map(|fx| fx.addressed.clone())
608 .unwrap_or_default(),
609 rejected: r
610 .fix
611 .as_ref()
612 .map(|fx| {
613 fx.rejected
614 .iter()
615 .map(|rej| prompt::ConductRejection {
616 id: rej.id.clone(),
617 why: rej.why.clone(),
618 })
619 .collect()
620 })
621 .unwrap_or_default(),
622 })
623 .collect();
624 let branch = state.winner().map(|c| c.branch.clone());
625 let branch_head = match &branch {
626 Some(b) => crate::git::rev_parse(repo, b)
627 .await
628 .ok()
629 .map(|h| h.chars().take(8).collect()),
630 None => None,
631 };
632
633 prompt::ConductOutcome {
634 run_id,
635 unreadable: None,
636 run_status: Some(state.status.as_str().to_owned()),
637 open_findings,
638 rounds_used: state.reviews.len(),
639 rounds_max: state.config.graph.review_rounds,
640 rounds,
641 branch,
642 branch_head,
643 references: crate::refs::describe(&state.seeds),
644 empty_candidate: state.merge.as_ref().is_some_and(|m| m.empty),
645 }
646}
647
648async fn open_pr_fact(task: &Task, repo: &Path) -> Option<String> {
652 let id = task.runs.last()?;
653 let state = match RunState::load(id) {
654 Ok(s) => s,
655 Err(e) => return Some(format!("could not check open pull requests: {e:#}")),
656 };
657 let branch = state.winner()?.branch.clone();
658 let base = state.base_branch.clone();
659 match crate::land::find_open_pr(repo, &branch, &base).await {
660 Ok(crate::land::OpenPr::None) => None,
661 Ok(crate::land::OpenPr::One { url, .. }) => Some(format!(
662 "pull request {url} is already open for {branch} into {base}"
663 )),
664 Ok(crate::land::OpenPr::Many(urls)) => Some(format!(
665 "several pull requests are already open for {branch} into {base}: {}",
666 urls.join(" ")
667 )),
668 Err(e) => Some(format!("could not check open pull requests: {e:#}")),
669 }
670}
671
672async fn attach_facts(cfg: &Config, repo: &Path, queue: &Queue, verdict: &mut Verdict) {
679 for d in verdict
680 .decisions
681 .iter_mut()
682 .filter(|d| d.question.is_some())
683 {
684 let Ok(task) = queue.get(&d.id) else {
685 continue;
686 };
687 let text = format!("{}\n{}", task.title, task.instruction);
688 let pr_fact = open_pr_fact(&task, repo_for(&task, repo).as_path()).await;
689 if crate::refs::scan(&text).is_empty() {
690 if let (Some(fact), Some(q)) = (pr_fact, d.question.as_mut()) {
691 q.push_str(&format!(
692 "\n\nChecked against the repository (magi did this, not the model):\n{fact}"
693 ));
694 }
695 continue;
696 }
697 let repo = repo_for(&task, repo);
698 let remote = &cfg.merge.remote;
699 let base = crate::git::merge_base_branch(&repo, remote, cfg.merge.base.as_deref())
700 .await
701 .ok();
702 let facts = match base {
703 Some(base) => {
704 let base_name = base.clone();
705 let tracking = format!("{remote}/{base}");
706 let refreshed = crate::git::fetch(&repo, remote, &base)
709 .await
710 .is_ok_and(|o| o.ok());
711 let against = tracking;
714 match crate::git::rev_parse(&repo, &against).await {
715 Ok(tip) => crate::refs::describe(
716 &crate::refs::resolve(&repo, &tip, remote, &text).await,
717 )
718 .map(|facts| {
719 if refreshed {
720 facts
721 } else {
722 format!(
723 "{facts}\n(could not fetch {remote}/{base_name}: this is \
724 against the last fetched `{against}`, which may be behind \
725 the remote)"
726 )
727 }
728 }),
729 Err(_) => Some(format!(
730 "could NOT be checked against the repository: {against} is not \
731 available here, so whether the work is in the base is unknown"
732 )),
733 }
734 }
735 None => Some("could not check the repository: no base branch known".to_owned()),
736 };
737 let facts = match (facts, pr_fact) {
738 (Some(f), Some(p)) => Some(format!("{f}\n{p}")),
739 (f, p) => f.or(p),
740 };
741 if let (Some(facts), Some(q)) = (facts, d.question.as_mut()) {
742 q.push_str(&format!(
743 "\n\nChecked against the repository (magi did this, not the model):\n{facts}"
744 ));
745 }
746 }
747}
748
749async fn finished_view(t: &Task, repo: &Path, max_attempts: usize) -> prompt::ConductFinished {
751 prompt::ConductFinished {
752 task: view(t, max_attempts),
753 outcome: outcome_for(t, &repo_for(t, repo)).await,
754 }
755}
756
757fn repo_for(task: &Task, fallback: &Path) -> PathBuf {
760 if task.repo.as_os_str().is_empty() || task.repo == Path::new(".") {
761 fallback.to_path_buf()
762 } else {
763 task.repo.clone()
764 }
765}
766
767fn apply_one(
784 queue: &Queue,
785 questions: &Questions,
786 d: &Decision,
787 snapshot: Option<&Task>,
788) -> Result<()> {
789 let _claim = queue
790 .claim(&d.id)
791 .with_context(|| format!("task {} is claimed elsewhere right now", d.id))?;
792 let mut task = queue.get(&d.id).context("no such task")?;
793
794 if snapshot.is_some_and(|old| decision_input(old) != decision_input(&task)) {
797 return Ok(());
798 }
799 let blocking =
800 d.question.is_some() || !d.blocked_by.is_empty() || d.recovery == Some(Recovery::Hold);
801 let evidence = new_blocking_evidence(queue, questions, &task, d);
802 if blocking && task.resumption.is_some() && evidence.is_empty() {
803 crate::notices::raise(crate::notices::conductor_resumption(
804 &task.id,
805 task.short(),
806 d.reason.as_deref(),
807 &d.blocked_by,
808 &d.evidence,
809 d.question.is_some(),
810 ));
811 return Ok(());
812 }
813
814 if blocking && !evidence.is_empty() {
815 let mut cause = evidence.clone();
816 cause.sort();
817 cause.dedup();
818 task.notice_cause(
819 &format!("conductor-evidence:{}", cause.join(",")),
820 None,
821 None,
822 );
823 }
824 if blocking {
825 if let Some(r) = task.resumption.as_mut() {
826 r.blocking_evidence.extend(evidence);
827 }
828 }
829
830 if task.operator_held() {
834 return Ok(());
835 }
836
837 if task.status == TaskStatus::Held && crate::triage::pending_for(questions, &task) {
841 return Ok(());
842 }
843
844 let pinned = pinned_resume(&task);
847 if pinned && (d.question.is_some() || !d.blocked_by.is_empty()) {
848 return Ok(());
849 }
850
851 if matches!(task.status, TaskStatus::Queued | TaskStatus::Held)
855 && !d.missing_dependencies.is_empty()
856 && (d.question.is_some() || d.recovery == Some(Recovery::Hold))
857 && d.missing_dependencies
858 .iter()
859 .any(|id| !d.blocked_by.contains(id))
860 && d.missing_dependencies
861 .iter()
862 .chain(&d.blocked_by)
863 .any(|id| {
864 matches!(
865 crate::queue::dependency(queue, questions, id),
866 crate::queue::Dependency::Ambiguous | crate::queue::Dependency::Unknown
867 )
868 })
869 {
870 return Ok(());
871 }
872
873 if matches!(task.status, TaskStatus::Queued | TaskStatus::Held)
879 && !d.missing_dependencies.is_empty()
880 && d.missing_dependencies.iter().all(|id| {
881 let claim = crate::queue::dependency(queue, questions, id);
882 claim != crate::queue::Dependency::Missing
883 && d.blocked_by.iter().any(|blocker| {
884 blocker == id
885 || (matches!(
886 &claim,
887 crate::queue::Dependency::Task(_)
888 | crate::queue::Dependency::Question(_)
889 | crate::queue::Dependency::Deleted(_)
890 ) && crate::queue::dependency(queue, questions, blocker) == claim)
891 })
892 })
893 && (d.question.is_some() || d.recovery == Some(Recovery::Hold))
894 && crate::queue::missing_blockers(queue, questions, &d.blocked_by).is_empty()
895 {
896 let mut ids = d.blocked_by.clone();
897 crate::queue::normalize_blockers(queue, questions, &mut ids);
898 let reason = format!("Waiting on dependencies: {}", ids.join(", "));
899 task.block(ids, Some(reason));
900 return queue.put(&mut task);
901 }
902
903 if let Some(text) = &d.question {
904 if task.status == TaskStatus::Done {
905 return Ok(());
906 }
907 let mut held = task.clone();
908 held.status = TaskStatus::Held;
909 let targets: BTreeSet<_> = d
910 .blocked_by
911 .iter()
912 .filter_map(|id| {
913 if let Ok(dep) = queue.get(id) {
914 Some(format!("task:{id}:{:?}", dep.chat_notice_key()))
915 } else if questions.get(id).is_ok() {
916 Some(format!("question:{id}"))
917 } else {
918 None
919 }
920 })
921 .collect();
922 let decision = d
923 .question_decision
924 .as_ref()
925 .and_then(|q| match q.identity(&task) {
926 Ok(identity) => Some(identity),
927 Err(error) => {
928 tracing::warn!(task = %task.id, %error, "ignoring invalid question decision target");
931 None
932 }
933 });
934 let context_value =
935 serde_json::json!([&task.instruction, held.chat_notice_key(), targets, decision]);
936 let context = serde_json::to_string(&context_value)?;
937 if questions.list().iter().any(|q| {
941 q.node == NODE
942 && q.run == task.id
943 && q.status == crate::ask::QuestionStatus::Answered
944 && q.decision_context.as_ref().is_some_and(|stored| {
945 if stored == &context {
946 return true;
947 }
948 decision.is_none()
951 && serde_json::from_str::<serde_json::Value>(stored)
952 .ok()
953 .and_then(|v| {
954 v.as_array().map(|items| {
955 items.len() == 4
956 && items[..3]
957 == context_value.as_array().expect("context")[..3]
958 })
959 })
960 == Some(true)
961 })
962 }) {
963 return Ok(());
964 }
965 let question_id = match questions
969 .list()
970 .into_iter()
971 .find(|q| q.status.open() && q.node == NODE && q.run == task.id)
972 {
973 Some(existing) => existing.id,
974 None => {
975 let mut q = Question::new(
976 task.id.clone(),
977 NODE.to_owned(),
978 SEAT.to_owned(),
979 text.clone(),
980 d.reason.clone().unwrap_or_default(),
981 d.choices.clone(),
982 );
983 q.actions = d.actions.clone();
984 anyhow::ensure!(
985 q.actions.keys().all(|label| q.choices.contains(label)),
986 "question action must name an offered choice"
987 );
988 q.decision_context = Some(context);
989 q.deputy = Some(Deputy::new(crate::deputy::brief(
994 &task.id,
995 d.reason.as_deref().unwrap_or_default(),
996 &q.choices,
997 &q.actions,
998 )));
999 if task.repo.is_dir() && task.repo != Path::new(".") {
1000 q.cwd = Some(task.repo.to_string_lossy().into_owned());
1001 }
1002 questions.put(&mut q)?;
1003 q.id
1004 }
1005 };
1006 task.block(vec![question_id], d.reason.clone());
1007 return queue.put(&mut task);
1008 }
1009
1010 match task.status {
1011 TaskStatus::Queued if d.recovery == Some(Recovery::Hold) => {
1015 if may_hold(&mut task, &hold_note(d)) {
1016 task.hold_machine(d.reason.clone());
1017 queue.put(&mut task)?;
1018 }
1019 }
1020 TaskStatus::Queued if !d.blocked_by.is_empty() => {
1021 let mut ids = d.blocked_by.clone();
1022 crate::queue::normalize_blockers(queue, questions, &mut ids);
1023 task.block(ids, d.reason.clone());
1024 queue.put(&mut task)?;
1025 }
1026 TaskStatus::Running => match d.recovery {
1027 Some(Recovery::Requeue) if pinned_resume(&task) => {}
1028 Some(Recovery::Requeue) => {
1029 task.requeue();
1030 queue.put(&mut task)?;
1031 }
1032 Some(Recovery::Hold) if may_hold(&mut task, &hold_note(d)) => {
1033 task.hold_machine(d.reason.clone());
1034 queue.put(&mut task)?;
1035 }
1036 _ => {}
1040 },
1041 TaskStatus::Failed | TaskStatus::Held => match d.recovery {
1042 Some(Recovery::Requeue) if pinned_resume(&task) => {}
1045 Some(Recovery::Requeue) => {
1046 task.requeue();
1047 queue.put(&mut task)?;
1048 }
1049 Some(Recovery::Hold) => {
1050 if let Some(reason) = reaffirmed_hold_reason(&task, d) {
1054 if may_hold(&mut task, &hold_note(d)) {
1055 task.hold_machine(Some(reason));
1056 queue.put(&mut task)?;
1057 }
1058 }
1059 }
1060 Some(Recovery::Review) => {
1061 if let Some(branch) = surviving_branch(&task) {
1062 task.request_review(branch);
1063 queue.put(&mut task)?;
1064 }
1065 }
1071 Some(Recovery::Done) => {
1072 task.succeed();
1073 crate::daemon::supersede_prior_runs(&task, &crate::run::home());
1077 queue.put(&mut task)?;
1078 }
1079 None => {}
1080 },
1081 _ => {}
1084 }
1085 Ok(())
1086}
1087
1088pub fn apply(queue: &Queue, questions: &Questions, verdict: &Verdict) -> Result<()> {
1092 for d in &verdict.decisions {
1093 if let Err(e) = apply_one(queue, questions, d, None) {
1094 tracing::warn!("conductor decision for task {}: {e:#}", d.id);
1095 }
1096 }
1097 Ok(())
1098}
1099
1100pub fn seat_path(home: &Path) -> PathBuf {
1106 home.join("conduct").join("seat.json")
1107}
1108
1109pub fn load_seat(home: &Path) -> Option<SeatState> {
1111 serde_json::from_str(&std::fs::read_to_string(seat_path(home)).ok()?).ok()
1112}
1113
1114fn busy_path(home: &Path) -> PathBuf {
1115 home.join("conduct").join("busy")
1116}
1117
1118pub fn busy(home: &Path) -> bool {
1124 std::fs::metadata(busy_path(home))
1125 .and_then(|m| m.modified())
1126 .ok()
1127 .and_then(|t| t.elapsed().ok())
1128 .is_some_and(|age| age < TURN_TIMEOUT + Duration::from_secs(30))
1129}
1130
1131struct Busy(PathBuf);
1133
1134impl Busy {
1135 fn mark(home: &Path) -> Self {
1136 let path = busy_path(home);
1137 if let Some(dir) = path.parent() {
1138 let _ = std::fs::create_dir_all(dir);
1139 }
1140 let _ = std::fs::write(&path, std::process::id().to_string());
1141 Self(path)
1142 }
1143}
1144
1145impl Drop for Busy {
1146 fn drop(&mut self) {
1147 let _ = std::fs::remove_file(&self.0);
1148 }
1149}
1150
1151#[derive(Debug, Default)]
1154pub struct Conductor {
1155 seat: Option<SeatState>,
1156 last_seen: Option<(u64, BTreeSet<String>)>,
1157 considered: BTreeMap<String, String>,
1161}
1162
1163fn decision_input(task: &Task) -> serde_json::Value {
1168 let mut v = serde_json::to_value(task).unwrap_or_default();
1169 if let Some(o) = v.as_object_mut() {
1170 o.remove("chat_notice");
1171 o.remove("chat_notices");
1172 o.remove("updated_at");
1174 }
1175 v
1176}
1177
1178fn input_fingerprint(task: &Task) -> String {
1179 let mut v = decision_input(task);
1180 if let Some(o) = v.as_object_mut() {
1181 o.remove("hold_reason");
1182 if let Some(ro) = o.get_mut("resume_override").and_then(|r| r.as_object_mut()) {
1183 ro.remove("conductor_rehold");
1184 }
1185 }
1186 v.to_string()
1187}
1188
1189impl Conductor {
1190 #[must_use]
1192 pub fn new() -> Self {
1193 Self::default()
1194 }
1195
1196 fn settled(
1201 considered: &BTreeMap<String, String>,
1202 stalled: &[Task],
1203 finished: &[Task],
1204 ) -> BTreeSet<String> {
1205 stalled
1206 .iter()
1207 .chain(finished)
1208 .filter(|t| t.status == TaskStatus::Held)
1209 .filter(|t| considered.get(&t.id) == Some(&input_fingerprint(t)))
1210 .map(|t| t.id.clone())
1211 .collect()
1212 }
1213
1214 fn snapshot_with(
1215 considered: &BTreeMap<String, String>,
1216 queue: &Queue,
1217 stalled: &[Task],
1218 finished: &[Task],
1219 ) -> (u64, BTreeSet<String>) {
1220 let ids = stalled
1221 .iter()
1222 .chain(finished)
1223 .map(|t| t.id.clone())
1224 .collect();
1225 let skip = Self::settled(considered, stalled, finished);
1226 (queue.revision_excluding(&skip), ids)
1227 }
1228
1229 fn snapshot(
1230 &self,
1231 queue: &Queue,
1232 stalled: &[Task],
1233 finished: &[Task],
1234 ) -> (u64, BTreeSet<String>) {
1235 Self::snapshot_with(&self.considered, queue, stalled, finished)
1236 }
1237
1238 #[must_use]
1255 pub fn worth_a_look(&self, queue: &Queue, stalled: &[Task], finished: &[Task]) -> bool {
1256 self.last_seen.as_ref() != Some(&self.snapshot(queue, stalled, finished))
1257 }
1258
1259 #[allow(clippy::too_many_arguments)]
1263 pub async fn maybe_run(
1264 &mut self,
1265 cfg: &Config,
1266 repo: &Path,
1267 queue: &Queue,
1268 questions: &Questions,
1269 home: &Path,
1270 queued: &[Task],
1271 stalled: &[Task],
1272 finished: &[Task],
1273 max_attempts: usize,
1274 ) {
1275 if self.last_seen.as_ref() == Some(&self.snapshot(queue, stalled, finished)) {
1276 return;
1277 }
1278 self.considered = stalled
1281 .iter()
1282 .chain(finished)
1283 .filter(|t| t.status == TaskStatus::Held)
1284 .map(|t| (t.id.clone(), input_fingerprint(t)))
1285 .collect();
1286 self.last_seen = Some(self.snapshot(queue, stalled, finished));
1287 if let Err(e) = self
1288 .run_once(
1289 cfg,
1290 repo,
1291 queue,
1292 questions,
1293 home,
1294 queued,
1295 stalled,
1296 finished,
1297 max_attempts,
1298 )
1299 .await
1300 {
1301 tracing::warn!("conductor: {e:#}");
1307 }
1308 }
1309
1310 #[allow(clippy::too_many_arguments)]
1311 async fn run_once(
1312 &mut self,
1313 cfg: &Config,
1314 repo: &Path,
1315 queue: &Queue,
1316 questions: &Questions,
1317 home: &Path,
1318 queued: &[Task],
1319 stalled: &[Task],
1320 finished: &[Task],
1321 max_attempts: usize,
1322 ) -> Result<()> {
1323 if queued.is_empty() && stalled.is_empty() && finished.is_empty() {
1324 return Ok(());
1325 }
1326
1327 let primary = cfg
1328 .resolve_roles()
1329 .context("resolving the conductor seat")?
1330 .conductor;
1331 let chain = match cfg.roles.conductor.as_ref() {
1335 Some(c) if c.ids().len() > 1 => {
1336 agent::pick_chain(&cfg.agents, Some(c), &agent::installed, "conductor")?
1337 }
1338 _ => vec![primary],
1339 };
1340
1341 let runnable_views: Vec<prompt::ConductTask> =
1342 queued.iter().map(|t| view(t, max_attempts)).collect();
1343 let stalled_views: Vec<prompt::ConductTask> =
1344 stalled.iter().map(|t| view(t, max_attempts)).collect();
1345 let mut finished_views = Vec::with_capacity(finished.len());
1346 for t in finished {
1347 finished_views.push(finished_view(t, repo, max_attempts).await);
1348 }
1349
1350 let body = prompt::with_overlay(
1351 prompt::conduct(
1352 &runnable_views,
1353 &stalled_views,
1354 &finished_views,
1355 &cfg.graph.language,
1356 ),
1357 cfg.prompts.overlay(NODE),
1358 );
1359
1360 let body = format!(
1361 "{body}\n\n{}",
1362 crate::queue::dependency_facts(queue, questions)
1363 );
1364 let artifacts = home.join("conduct").join("artifacts");
1365 let cache_dir = cfg.cache_dir();
1368
1369 let busy = Busy::mark(home);
1371 let mut result: Result<Verdict> = Err(anyhow::anyhow!("no conductor agent ran"));
1372 for spec in &chain {
1373 let needs_new_seat = !matches!(&self.seat, Some(s) if s.agent == spec.id);
1376 if needs_new_seat {
1377 self.seat = Some(SeatState::new(SEAT, &spec.id, crate::rng::entropy()));
1378 }
1379 let seat = self.seat.as_mut().expect("just ensured a seat exists");
1380 let stem = if std::ptr::eq(spec, &chain[0]) {
1383 format!("turn-{}", seat.turns + 1)
1384 } else {
1385 format!("turn-{}-{}", seat.turns + 1, spec.id)
1386 };
1387 let inv = Invocation {
1388 coordination: cfg.coordination.as_ref(),
1389 cwd: repo,
1390 prompt: &body,
1391 timeout: TURN_TIMEOUT,
1392 allow_write: false,
1395 unsandboxed: false,
1396 sessions: cfg.graph.sessions,
1397 artifacts: &artifacts,
1398 stem: &stem,
1399 run: NODE,
1400 node: NODE,
1401 cache_dir: cache_dir.as_deref(),
1402 attachments: &[],
1403 writable: &[],
1404 };
1405 let out = agent::invoke(spec, seat, &inv).await;
1406 if let Ok(body) = serde_json::to_string(&*seat) {
1409 let path = seat_path(home);
1410 if let Some(dir) = path.parent() {
1411 let _ = std::fs::create_dir_all(dir);
1412 }
1413 let _ = std::fs::write(path, body);
1414 }
1415 let advance = agent::chain_advances(&out);
1416 result = match out {
1417 Err(e) => Err(e.context("invoking the conductor")),
1418 Ok(out) if advance => Err(anyhow::anyhow!(
1419 "no usable reply (exit {:?}, timed out {})",
1420 out.exit_code,
1421 out.timed_out
1422 )),
1423 Ok(out) => verdict::extract_json(&out.text)
1424 .context("the conductor's reply could not be parsed"),
1425 };
1426 if result.is_ok() {
1427 break;
1428 }
1429 if chain.len() > 1 {
1430 tracing::warn!("conductor: `{}` failed, trying the next agent", spec.id);
1431 }
1432 }
1433 drop(busy);
1434 let mut verdict = result?;
1435 attach_facts(cfg, repo, queue, &mut verdict).await;
1436 for d in &verdict.decisions {
1437 let snapshot = queued
1438 .iter()
1439 .chain(stalled)
1440 .chain(finished)
1441 .find(|t| t.id == d.id);
1442 if let Some(snapshot) = snapshot {
1443 if let Err(e) = apply_one(queue, questions, d, Some(snapshot)) {
1444 tracing::warn!("conductor decision for task {}: {e:#}", d.id);
1445 }
1446 }
1447 }
1448 Ok(())
1449 }
1450}
1451
1452#[cfg(test)]
1453mod tests {
1454 use std::collections::BTreeMap;
1455
1456 use tempfile::tempdir;
1457
1458 use super::*;
1459 use crate::ask::{Answer, QuestionStatus};
1460 use crate::config::{AgentKind, AgentSpec, Graph};
1461 use crate::queue::Source;
1462
1463 fn mock_agent(dir: &Path, script: &str, env: BTreeMap<String, String>) -> AgentSpec {
1464 let path = dir.join("mock-conduct-agent.sh");
1465 std::fs::write(&path, script).expect("write mock");
1466 AgentSpec {
1467 id: "mock".to_owned(),
1468 kind: AgentKind::Command,
1469 model: None,
1470 command: vec!["sh".to_owned(), path.to_string_lossy().into_owned()],
1471 extra_args: Vec::new(),
1472 env,
1473 prompt_delivery: None,
1474 }
1475 }
1476
1477 fn config(spec: AgentSpec) -> Config {
1478 Config {
1479 agents: vec![spec],
1480 graph: Graph {
1481 language: "en".to_owned(),
1482 ..Graph::default()
1483 },
1484 ..Config::default()
1485 }
1486 }
1487
1488 fn task(title: &str) -> Task {
1489 Task::new(
1490 title.to_owned(),
1491 format!("do {title}"),
1492 std::path::PathBuf::from("."),
1493 Source::Human,
1494 )
1495 }
1496
1497 #[test]
1498 fn delivery_bookkeeping_does_not_restart_conductor_deliberation() {
1499 let mut t = task("waiting");
1500 t.hold_machine(Some("waiting for recovery".into()));
1501 let before = input_fingerprint(&t);
1502 let snapshot = decision_input(&t);
1503 t.chat_notice = Some(crate::queue::ChatNotice {
1504 key: t.chat_notice_key().unwrap(),
1505 at: jiff::Timestamp::now(),
1506 outcome: crate::queue::ChatNoticeOutcome::Posted,
1507 });
1508 t.chat_notices.push(t.chat_notice_key().unwrap());
1509 t.updated_at = jiff::Timestamp::now();
1510 assert_eq!(before, input_fingerprint(&t));
1511 assert_eq!(snapshot, decision_input(&t));
1512 t.hold_reason = Some("recovery remains under consideration".into());
1513 assert_eq!(before, input_fingerprint(&t));
1514 t.record_answer("a different question".into(), "a new decision".into());
1515 assert_ne!(before, input_fingerprint(&t));
1516 }
1517
1518 const BROKEN: &str = "#!/bin/sh\ncat >/dev/null\nexit 3\n";
1519 const GARBAGE: &str = "#!/bin/sh\ncat >/dev/null\nprintf 'not json at all\\n'\n";
1520
1521 fn env(reply: &str) -> BTreeMap<String, String> {
1522 BTreeMap::from([("MOCK_REPLY".to_owned(), reply.to_owned())])
1523 }
1524
1525 const REPLY: &str = "#!/bin/sh\ncat >/dev/null\nprintf '%s\\n' \"$MOCK_REPLY\"\n";
1526
1527 fn init_repo_with_branch(dir: &Path, branch: &str) {
1531 use crate::proc::Quiet as _;
1532 let run = |args: &[&str]| {
1533 let out = std::process::Command::new("git")
1534 .args(args)
1535 .current_dir(dir)
1536 .quiet()
1537 .output()
1538 .expect("spawn git");
1539 assert!(
1540 out.status.success(),
1541 "git {args:?} failed: {}",
1542 String::from_utf8_lossy(&out.stderr)
1543 );
1544 };
1545 run(&["init", "-b", "main"]);
1546 run(&["config", "user.name", "magi test"]);
1547 run(&["config", "user.email", "magi@example.com"]);
1548 std::fs::write(dir.join("README.md"), "# fixture\n").unwrap();
1549 run(&["add", "-A"]);
1550 run(&["commit", "-m", "init"]);
1551 run(&["checkout", "-b", branch]);
1552 std::fs::write(dir.join("change.txt"), "x\n").unwrap();
1553 run(&["add", "-A"]);
1554 run(&["commit", "-m", "candidate work"]);
1555 }
1556
1557 fn review_round_with_finding(
1558 round: usize,
1559 finding_id: &str,
1560 title: &str,
1561 addressed: &[&str],
1562 rejected: &[(&str, &str)],
1563 ) -> crate::run::ReviewRound {
1564 crate::run::ReviewRound {
1565 round,
1566 head: "deadbeef".to_owned(),
1567 verified_head: None,
1568 verified_at: None,
1569 reviews: vec![crate::run::ReviewRecord {
1570 attempts: 0,
1571 reviewer: 1,
1572 agent: "mock".to_owned(),
1573 summary: String::new(),
1574 findings: vec![crate::verdict::Finding {
1575 id: finding_id.to_owned(),
1576 severity: crate::verdict::Severity::Major,
1577 file: None,
1578 line: None,
1579 title: title.to_owned(),
1580 detail: String::new(),
1581 }],
1582 vote: None,
1583 failed: None,
1584 duration_ms: 0,
1585 }],
1586 e2e: Vec::new(),
1587 verify_retried: false,
1588 e2e_deferred: false,
1589 e2e_defer_reason: None,
1590 fix: Some(crate::run::FixRecord {
1591 agent: "mock".to_owned(),
1592 addressed: addressed.iter().map(|s| (*s).to_owned()).collect(),
1593 rejected: rejected
1594 .iter()
1595 .map(|(id, why)| crate::verdict::Rejection {
1596 id: (*id).to_owned(),
1597 why: (*why).to_owned(),
1598 })
1599 .collect(),
1600 notes: String::new(),
1601 committed: false,
1602 failed: None,
1603 duration_ms: 0,
1604 continuation: None,
1605 }),
1606 blocking: 1,
1607 answered: 1,
1608 expected: 1,
1609 clean: false,
1610 progressed: true,
1611 vote_split: false,
1612 reconsideration: Vec::new(),
1613 verdict: None,
1614 }
1615 }
1616
1617 #[test]
1618 fn explicit_resumption_supersedes_history_and_rejects_stale_decisions() {
1619 crate::run::pin_test_home();
1620 let dir = tempdir().unwrap();
1621 let queue = Queue::at(dir.path().join("queue"));
1622 let questions = Questions::at(dir.path().join("questions"));
1623 let mut t = task("recover");
1624 t.answers.push(crate::queue::AnsweredQuestion {
1625 question: "Inspect remote first?".into(),
1626 answer: "Inspect, then await resumption instructions".into(),
1627 });
1628 t.hold_machine(Some("waiting for remote inspection".into()));
1629 queue.put(&mut t).unwrap();
1630 let snapshot = queue.get(&t.id).unwrap();
1631 t.edit(
1632 "recover".into(),
1633 "Reuse the measured PR head; fix Clippy; review".into(),
1634 )
1635 .unwrap();
1636 t.release_operator("cli", None);
1637 queue.put(&mut t).unwrap();
1638 let approval = t.resumption.clone();
1639 let d = Decision {
1640 id: t.id.clone(),
1641 recovery: Some(Recovery::Hold),
1642 reason: Some("remote inspection still required".into()),
1643 ..Decision::default()
1644 };
1645 apply_one(&queue, &questions, &d, Some(&snapshot)).unwrap();
1646 let stale_question = Decision {
1647 question: Some("Inspect remote?".into()),
1648 ..d.clone()
1649 };
1650 apply_one(&queue, &questions, &stale_question, Some(&snapshot)).unwrap();
1651 assert!(questions.list().is_empty());
1652 for reason in [
1653 "waiting for remote inspection",
1654 "inspection has not been confirmed",
1655 ] {
1656 let repeated = Decision {
1657 reason: Some(reason.into()),
1658 ..d.clone()
1659 };
1660 apply(
1661 &queue,
1662 &questions,
1663 &Verdict {
1664 decisions: vec![repeated],
1665 },
1666 )
1667 .unwrap();
1668 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
1669 }
1670 let reloaded = Queue::at(dir.path().join("queue")).get(&t.id).unwrap();
1671 assert_eq!(reloaded.resumption, approval);
1672 assert_eq!(reloaded.answers, t.answers);
1673 let v = view(&reloaded, 3);
1674 assert!(v.operator_resume.unwrap().contains("superseded"));
1675 let mut dep = task("new prerequisite");
1676 dep.hold_machine(Some("new authentication failure".into()));
1677 queue.put(&mut dep).unwrap();
1678 let new_blocker = Decision {
1679 blocked_by: vec![dep.id.clone()],
1680 evidence: vec![dep.id.clone()],
1681 recovery: None,
1683 reason: Some("new prerequisite failed".into()),
1684 ..d.clone()
1685 };
1686 apply(
1687 &queue,
1688 &questions,
1689 &Verdict {
1690 decisions: vec![new_blocker.clone()],
1691 },
1692 )
1693 .unwrap();
1694 let mut after = queue.get(&t.id).unwrap();
1695 assert_eq!(after.status, TaskStatus::Blocked);
1696 after.release();
1699 queue.put(&mut after).unwrap();
1700 apply(
1701 &queue,
1702 &questions,
1703 &Verdict {
1704 decisions: vec![new_blocker],
1705 },
1706 )
1707 .unwrap();
1708 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
1709 after.start("new-run".into());
1710 assert_eq!(after.resumption.as_ref().unwrap().generation, 1);
1711 after.hold_manual(Some("operator says wait".into()));
1712 queue.put(&mut after).unwrap();
1713 apply(&queue, &questions, &Verdict { decisions: vec![d] }).unwrap();
1714 assert!(queue.get(&t.id).unwrap().operator_held());
1715 }
1716
1717 #[test]
1718 fn newly_blocked_dependency_is_material_evidence_after_approval() {
1719 let dir = tempdir().unwrap();
1720 let queue = Queue::at(dir.path().join("queue"));
1721 let questions = Questions::at(dir.path().join("questions"));
1722 let mut dep = task("old queued dependency");
1723 queue.put(&mut dep).unwrap();
1724 let mut t = task("approved task");
1725 t.release_operator("test", None);
1726 queue.put(&mut t).unwrap();
1727 let mut q = Question::new(
1728 dep.id.clone(),
1729 "check".into(),
1730 "check".into(),
1731 "New dependency approval".into(),
1732 String::new(),
1733 Vec::new(),
1734 );
1735 questions.put(&mut q).unwrap();
1736 dep.block(vec![q.id.clone()], Some("new decision needed".into()));
1737 let changed = dep.blocked_at;
1738 queue.put(&mut dep).unwrap();
1739 dep.block(vec![q.id], Some("same decision paraphrased".into()));
1740 assert_eq!(
1741 dep.blocked_at, changed,
1742 "prose is not new blocking evidence"
1743 );
1744 queue.put(&mut dep).unwrap();
1745 let d = Decision {
1746 id: t.id.clone(),
1747 blocked_by: vec![dep.id.clone()],
1748 evidence: vec![dep.id],
1749 ..Decision::default()
1750 };
1751 assert_eq!(new_blocking_evidence(&queue, &questions, &t, &d).len(), 1);
1752 apply_one(&queue, &questions, &d, None).unwrap();
1753 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
1754 }
1755
1756 #[test]
1757 fn resumed_run_evidence_uses_approval_time_not_run_list_offsets() {
1758 crate::run::pin_test_home();
1759 let dir = tempdir().unwrap();
1760 let queue = Queue::at(dir.path().join("queue"));
1761 let questions = Questions::at(dir.path().join("questions"));
1762 let mut t = task("resume evidence");
1763 let mut run = RunState::new(
1764 t.repo.clone(),
1765 "main".into(),
1766 "base".into(),
1767 "work".into(),
1768 crate::config::Config::default(),
1769 );
1770 run.begin_pass();
1771 run.status = crate::run::RunStatus::Failed;
1772 run.save().unwrap();
1773 t.start(run.id.clone());
1774 t.runs.push(run.id.clone());
1776 t.release_operator("cli", None);
1777 let approval = t.resumption.as_ref().unwrap().at;
1778 let decision = Decision {
1779 evidence: vec![run.id.clone()],
1780 ..Decision::default()
1781 };
1782 assert!(new_blocking_evidence(&queue, &questions, &t, &decision).is_empty());
1783 t.start(run.id.clone());
1784 assert_eq!(t.runs.len(), 1);
1785 run.begin_pass();
1786 run.save().unwrap();
1787 assert!(run.passes.last().unwrap().started_at > approval);
1788 let evidence = new_blocking_evidence(&queue, &questions, &t, &decision);
1789 assert_eq!(evidence.len(), 1);
1790 t.resumption.as_mut().unwrap().blocking_evidence = evidence;
1791 assert!(new_blocking_evidence(&queue, &questions, &t, &decision).is_empty());
1792 run.begin_pass();
1793 run.save().unwrap();
1794 assert_eq!(
1795 new_blocking_evidence(&queue, &questions, &t, &decision).len(),
1796 1
1797 );
1798
1799 let mut q = Question::new(
1800 run.id.clone(),
1801 "review".into(),
1802 "check".into(),
1803 "New failure".into(),
1804 String::new(),
1805 Vec::new(),
1806 );
1807 questions.put(&mut q).unwrap();
1808 let decision = Decision {
1809 evidence: vec![q.id.clone()],
1810 ..Decision::default()
1811 };
1812 assert_eq!(
1813 new_blocking_evidence(&queue, &questions, &t, &decision).len(),
1814 1
1815 );
1816 q.asked_at = approval;
1817 questions.put(&mut q).unwrap();
1818 assert!(new_blocking_evidence(&queue, &questions, &t, &decision).is_empty());
1819 q.asked_at = jiff::Timestamp::now();
1820 q.run = "unrelated".into();
1821 questions.put(&mut q).unwrap();
1822 assert!(new_blocking_evidence(&queue, &questions, &t, &decision).is_empty());
1823
1824 let mut fresh = RunState::new(
1825 t.repo.clone(),
1826 "main".into(),
1827 "base".into(),
1828 "fresh work".into(),
1829 crate::config::Config::default(),
1830 );
1831 fresh.status = crate::run::RunStatus::Failed;
1832 fresh.save().unwrap();
1833 t.start(fresh.id.clone());
1834 let decision = Decision {
1835 evidence: vec![fresh.id.clone()],
1836 ..Decision::default()
1837 };
1838 assert_eq!(
1839 new_blocking_evidence(&queue, &questions, &t, &decision).len(),
1840 1
1841 );
1842 }
1843
1844 #[test]
1845 fn outcome_for_carries_every_rounds_findings_and_the_branch_head() {
1846 crate::run::pin_test_home();
1847 let dir = tempdir().unwrap();
1848 let default_repo = dir.path().join("default");
1849 let task_repo = dir.path().join("task");
1850 std::fs::create_dir_all(&default_repo).unwrap();
1851 std::fs::create_dir_all(&task_repo).unwrap();
1852 init_repo_with_branch(&default_repo, "other-branch");
1853 init_repo_with_branch(&task_repo, "magi/f00d/A");
1854
1855 let mut config = Config::default();
1856 config.graph.review_rounds = 6;
1857 let mut state = crate::run::RunState::new(
1858 task_repo.clone(),
1859 "main".to_owned(),
1860 "deadbeef".to_owned(),
1861 "task".to_owned(),
1862 config,
1863 );
1864 state.status = crate::run::RunStatus::Blocked;
1865 state.candidates.push(crate::run::Candidate {
1866 index: 0,
1867 label: 'A',
1868 agent: "mock".to_owned(),
1869 branch: "magi/f00d/A".to_owned(),
1870 worktree: task_repo.clone(),
1871 summary: String::new(),
1872 stat: String::new(),
1873 files: 1,
1874 commits: 1,
1875 empty: false,
1876 failed: None,
1877 verified_noop: None,
1878 duration_ms: 0,
1879 folded: false,
1880 });
1881 state.tally = Some(crate::run::Tally {
1882 first_choice: std::collections::BTreeMap::new(),
1883 borda: std::collections::BTreeMap::new(),
1884 winner: 'A',
1885 rankings: 0,
1886 unanimous_initial: false,
1887 deliberated: false,
1888 changed_votes: 0,
1889 unanimous_final: false,
1890 tie_break: None,
1891 judges: 0,
1892 present: 0,
1893 quorum: 0,
1894 met_quorum: true,
1895 uncontested: Some("solo".to_owned()),
1896 });
1897 state.reviews = vec![
1898 review_round_with_finding(
1899 1,
1900 "R1-1-2",
1901 "answer content is dropped",
1902 &[],
1903 &[("R1-1-2", "the id leaving blocked_by is enough")],
1904 ),
1905 review_round_with_finding(2, "R2-1-3", "answer content is still dropped", &[], &[]),
1906 ];
1907 state.save().unwrap();
1908
1909 let mut t = task("outcome test");
1910 t.repo = task_repo;
1911 t.runs.push(state.id.clone());
1912
1913 let finished = tokio_test_block_on(finished_view(&t, &default_repo, 2));
1914 let outcome = finished.outcome;
1915
1916 assert!(outcome.unreadable.is_none());
1917 assert_eq!(outcome.run_status.as_deref(), Some("blocked"));
1918 assert_eq!(outcome.rounds_used, 2);
1919 assert_eq!(outcome.rounds_max, 6);
1920 assert_eq!(outcome.rounds.len(), 2);
1921 assert_eq!(outcome.rounds[0].findings[0].id, "R1-1-2");
1922 assert_eq!(outcome.rounds[0].rejected[0].id, "R1-1-2");
1923 assert!(outcome.rounds[1].addressed.is_empty());
1924 assert!(outcome.rounds[1].rejected.is_empty());
1925 assert_eq!(outcome.branch.as_deref(), Some("magi/f00d/A"));
1926 assert!(
1927 outcome.branch_head.is_some(),
1928 "a real branch must resolve a head commit: {outcome:?}"
1929 );
1930 }
1931
1932 fn tokio_test_block_on<F: std::future::Future>(f: F) -> F::Output {
1936 tokio::runtime::Builder::new_current_thread()
1937 .enable_all()
1938 .build()
1939 .unwrap()
1940 .block_on(f)
1941 }
1942
1943 #[test]
1944 fn view_resolves_task_attempt_limit_before_daemon_default() {
1945 let mut t = task("budget");
1946 assert_eq!(view(&t, 7).max_attempts, 7);
1947 t.change_attempt_limit(std::num::NonZeroUsize::new(3))
1948 .unwrap();
1949 assert_eq!(view(&t, 7).max_attempts, 3);
1950 t.change_attempt_limit(None).unwrap();
1951 assert_eq!(view(&t, 7).max_attempts, 7);
1952 }
1953
1954 #[test]
1955 fn view_carries_a_tasks_recorded_answers_into_the_conductor_prompt_input() {
1956 let mut t = task("answered");
1957 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
1958 let v = view(&t, 2);
1959 assert_eq!(v.answers.len(), 1);
1960 assert_eq!(v.answers[0].question, "Which backend?");
1961 assert_eq!(v.answers[0].answer, "SQLite");
1962 }
1963
1964 #[tokio::test]
1965 async fn dependency_resolution_rechecks_questions_in_the_production_conductor_path() {
1966 for held in [false, true] {
1967 for reference in ["ca5b", "20261013-193611-ca5b"] {
1968 for question in [false, true] {
1969 let dir = tempdir().unwrap();
1970 let queue = Queue::at(dir.path().join("queue"));
1971 let questions = Questions::at(dir.path().join("questions"));
1972 let mut dep = task("prerequisite");
1973 dep.id = "20261013-193611-ca5b".into();
1974 dep.start("existing-run".into());
1975 queue.put(&mut dep).unwrap();
1976 let mut waiting = task("waiting");
1977 if held {
1978 waiting.hold_machine(Some("dependency could not be located".into()));
1979 }
1980 queue.put(&mut waiting).unwrap();
1981 let missing_reference = if reference == "ca5b" {
1982 dep.id.as_str()
1983 } else {
1984 "ca5b"
1985 };
1986 let reply = serde_json::json!({"decisions": [{
1987 "id": waiting.id, "blocked_by": [reference],
1988 "missing_dependencies": [missing_reference],
1989 "question": question.then_some("ca5b is missing; where is its replacement?"),
1990 "recovery": (!question).then_some("hold"),
1991 "reason": "ca5b is missing"
1992 }]}).to_string();
1993 let cfg = config(mock_agent(dir.path(), REPLY, env(&reply)));
1994 let (queued, finished) = if held {
1995 (vec![], vec![waiting.clone()])
1996 } else {
1997 (vec![waiting.clone()], vec![])
1998 };
1999 Conductor::new()
2000 .run_once(
2001 &cfg,
2002 dir.path(),
2003 &queue,
2004 &questions,
2005 dir.path(),
2006 &queued,
2007 &[],
2008 &finished,
2009 2,
2010 )
2011 .await
2012 .unwrap();
2013 let after = queue.get(&waiting.id).unwrap();
2014 assert_eq!(after.status, TaskStatus::Blocked);
2015 assert_eq!(after.blocked_by, [dep.id]);
2016 assert_eq!(after.blocked_from, Some(waiting.status));
2017 assert!(!after.block_reason.unwrap().contains("missing"));
2018 assert!(questions.list().is_empty());
2019 assert_eq!(after.instruction, waiting.instruction);
2020 }
2021 }
2022 }
2023 }
2024
2025 #[tokio::test]
2026 async fn dependency_resolution_inconclusive_missing_only_decisions_keep_waiting() {
2027 for held in [false, true] {
2028 for unknown in [false, true] {
2029 for question in [false, true] {
2030 let dir = tempdir().unwrap();
2031 let queue = Queue::at(dir.path().join("queue"));
2032 let questions = Questions::at(dir.path().join("questions"));
2033 let mut dep = task("running prerequisite");
2034 dep.id = "20261013-193611-ca5b".into();
2035 dep.start("existing-run".into());
2036 queue.put(&mut dep).unwrap();
2037 let reference = if unknown {
2038 std::fs::write(questions.root(), "not a directory").unwrap();
2041 dep.id.clone()
2042 } else {
2043 let mut other = task("another prerequisite");
2044 other.id = "20261014-193611-ca5b".into();
2045 queue.put(&mut other).unwrap();
2046 "ca5b".to_owned()
2047 };
2048 assert_eq!(
2049 crate::queue::dependency(&queue, &questions, &reference),
2050 if unknown {
2051 crate::queue::Dependency::Unknown
2052 } else {
2053 crate::queue::Dependency::Ambiguous
2054 }
2055 );
2056 let mut waiting = task("waiting");
2057 if held {
2058 waiting.hold_machine(Some("dependency could not be located".into()));
2059 }
2060 queue.put(&mut waiting).unwrap();
2061 let reply = serde_json::json!({"decisions": [{
2062 "id": waiting.id, "blocked_by": [reference],
2063 "missing_dependencies": [reference],
2064 "question": question.then_some("ca5b is missing"),
2065 "recovery": (!question).then_some("hold"),
2066 "reason": "ca5b is missing"
2067 }]})
2068 .to_string();
2069 let cfg = config(mock_agent(dir.path(), REPLY, env(&reply)));
2070 let (queued, finished) = if held {
2071 (vec![], vec![waiting.clone()])
2072 } else {
2073 (vec![waiting.clone()], vec![])
2074 };
2075 Conductor::new()
2076 .run_once(
2077 &cfg,
2078 dir.path(),
2079 &queue,
2080 &questions,
2081 dir.path(),
2082 &queued,
2083 &[],
2084 &finished,
2085 2,
2086 )
2087 .await
2088 .unwrap();
2089 let after = queue.get(&waiting.id).unwrap();
2090 assert_eq!(after.status, TaskStatus::Blocked);
2091 assert_eq!(after.blocked_by, [reference]);
2092 assert_eq!(after.blocked_from, Some(waiting.status));
2093 assert!(!after.block_reason.unwrap().contains("missing"));
2094 assert_eq!(after.instruction, waiting.instruction);
2095 if unknown {
2096 assert!(questions.root().is_file());
2097 } else {
2098 assert!(questions.list().is_empty());
2099 }
2100 }
2101 }
2102 }
2103 }
2104
2105 #[tokio::test]
2106 async fn dependency_resolution_unverifiable_alias_decisions_are_discarded() {
2107 for held in [false, true] {
2108 for unknown in [false, true] {
2109 for question in [false, true] {
2110 for short_blocker in [false, true] {
2111 let dir = tempdir().unwrap();
2112 let queue = Queue::at(dir.path().join("queue"));
2113 let questions = Questions::at(dir.path().join("questions"));
2114 let mut dep = task("running prerequisite");
2115 dep.id = "20261013-193611-ca5b".into();
2116 dep.start("existing-run".into());
2117 queue.put(&mut dep).unwrap();
2118 if unknown {
2119 std::fs::write(questions.root(), "not a directory").unwrap();
2120 } else {
2121 let mut other = task("another prerequisite");
2122 other.id = "20261014-193611-ca5b".into();
2123 queue.put(&mut other).unwrap();
2124 }
2125 let (blocker, missing) = if short_blocker {
2126 ("ca5b", dep.id.as_str())
2127 } else {
2128 (dep.id.as_str(), "ca5b")
2129 };
2130 let mut waiting = task("waiting");
2131 if held {
2132 waiting.hold_machine(Some("dependency could not be located".into()));
2133 }
2134 queue.put(&mut waiting).unwrap();
2135 let reply = serde_json::json!({"decisions": [{
2136 "id": waiting.id, "blocked_by": [blocker],
2137 "missing_dependencies": [missing],
2138 "question": question.then_some("ca5b is missing"),
2139 "recovery": (!question).then_some("hold"),
2140 "reason": "ca5b is missing"
2141 }]})
2142 .to_string();
2143 let cfg = config(mock_agent(dir.path(), REPLY, env(&reply)));
2144 let (queued, finished) = if held {
2145 (vec![], vec![waiting.clone()])
2146 } else {
2147 (vec![waiting.clone()], vec![])
2148 };
2149 Conductor::new()
2150 .run_once(
2151 &cfg,
2152 dir.path(),
2153 &queue,
2154 &questions,
2155 dir.path(),
2156 &queued,
2157 &[],
2158 &finished,
2159 2,
2160 )
2161 .await
2162 .unwrap();
2163 assert_eq!(
2164 serde_json::to_value(queue.get(&waiting.id).unwrap()).unwrap(),
2165 serde_json::to_value(&waiting).unwrap(),
2166 "unverifiable aliases must leave the entire task unchanged"
2167 );
2168 if unknown {
2169 assert!(questions.root().is_file());
2170 } else {
2171 assert!(questions.list().is_empty());
2172 }
2173 }
2174 }
2175 }
2176 }
2177 }
2178
2179 #[tokio::test]
2180 async fn dependency_resolution_genuine_missing_reference_still_asks() {
2181 let dir = tempdir().unwrap();
2182 let queue = Queue::at(dir.path().join("queue"));
2183 let questions = Questions::at(dir.path().join("questions"));
2184 let mut waiting = task("missing prerequisite");
2185 queue.put(&mut waiting).unwrap();
2186 let reply = serde_json::json!({"decisions": [{
2187 "id": waiting.id, "blocked_by": ["not-present"],
2188 "missing_dependencies": ["not-present"],
2189 "question": "Which prerequisite replaces the missing task?"
2190 }]})
2191 .to_string();
2192 let cfg = config(mock_agent(dir.path(), REPLY, env(&reply)));
2193 Conductor::new()
2194 .run_once(
2195 &cfg,
2196 dir.path(),
2197 &queue,
2198 &questions,
2199 dir.path(),
2200 &[waiting.clone()],
2201 &[],
2202 &[],
2203 2,
2204 )
2205 .await
2206 .unwrap();
2207 let after = queue.get(&waiting.id).unwrap();
2208 assert_eq!(after.status, TaskStatus::Blocked);
2209 assert_eq!(
2210 questions.get(&after.blocked_by[0]).unwrap().summary,
2211 "Which prerequisite replaces the missing task?"
2212 );
2213 }
2214
2215 #[tokio::test]
2216 async fn dependency_resolution_keeps_decisions_during_unrelated_task_progress() {
2217 let dir = tempdir().unwrap();
2218 let queue = Queue::at(dir.path().join("queue"));
2219 let questions = Questions::at(dir.path().join("questions"));
2220 let mut dep = task("prerequisite");
2221 dep.id = "20261013-193611-ca5b".into();
2222 dep.start("existing-run".into());
2223 queue.put(&mut dep).unwrap();
2224 let mut unrelated = task("unrelated work");
2225 unrelated.start("other-run".into());
2226 queue.put(&mut unrelated).unwrap();
2227 std::fs::File::options()
2230 .write(true)
2231 .open(queue.path_of(&unrelated.id))
2232 .unwrap()
2233 .set_times(std::fs::FileTimes::new().set_modified(std::time::UNIX_EPOCH))
2234 .unwrap();
2235 unrelated.succeed();
2236 let mut waiting = task("waiting");
2237 let mut asking = task("needs a product decision");
2238 let mut holding = task("must stay held");
2239 queue.put(&mut waiting).unwrap();
2240 queue.put(&mut asking).unwrap();
2241 queue.put(&mut holding).unwrap();
2242 let reply = serde_json::json!({"decisions": [
2243 {"id": waiting.id, "blocked_by": ["ca5b"], "reason": "wait for implementation"},
2244 {"id": asking.id, "question": "Which behavior do you want?"},
2245 {"id": holding.id, "recovery": "hold", "reason": "already implemented elsewhere"}
2246 ]})
2247 .to_string();
2248 let mut vars = env(&reply);
2249 vars.insert(
2250 "UNRELATED_PATH".into(),
2251 queue.path_of(&unrelated.id).to_string_lossy().into_owned(),
2252 );
2253 vars.insert(
2254 "UNRELATED_RECORD".into(),
2255 serde_json::to_string(&unrelated).unwrap(),
2256 );
2257 let script = r#"#!/bin/sh
2258cat >/dev/null
2259printf '%s' "$UNRELATED_RECORD" > "$UNRELATED_PATH"
2260printf '%s\n' "$MOCK_REPLY"
2261"#;
2262 let cfg = config(mock_agent(dir.path(), script, vars));
2263 Conductor::new()
2264 .run_once(
2265 &cfg,
2266 dir.path(),
2267 &queue,
2268 &questions,
2269 dir.path(),
2270 &[waiting.clone(), asking.clone(), holding.clone()],
2271 &[],
2272 &[],
2273 2,
2274 )
2275 .await
2276 .unwrap();
2277 assert_eq!(queue.get(&unrelated.id).unwrap().status, TaskStatus::Done);
2278 let after = queue.get(&waiting.id).unwrap();
2279 assert_eq!(after.status, TaskStatus::Blocked);
2280 assert_eq!(after.blocked_by, [dep.id]);
2281 let asked = queue.get(&asking.id).unwrap();
2282 assert_eq!(asked.status, TaskStatus::Blocked);
2283 assert_eq!(
2284 questions.get(&asked.blocked_by[0]).unwrap().summary,
2285 "Which behavior do you want?"
2286 );
2287 assert_eq!(queue.get(&holding.id).unwrap().status, TaskStatus::Held);
2288 }
2289
2290 #[test]
2291 fn a_dependency_decision_blocks_the_task_and_leaves_priority_alone() {
2292 let dir = tempdir().unwrap();
2293 let queue = Queue::at(dir.path().join("queue"));
2294 let questions = Questions::at(dir.path().join("questions"));
2295 let mut a = task("a");
2296 a.priority = 9;
2297 queue.put(&mut a).unwrap();
2298
2299 let verdict = Verdict {
2300 decisions: vec![Decision {
2301 id: a.id.clone(),
2302 blocked_by: vec!["20260101-000000-dead".to_owned()],
2303 reason: Some("waits on the other task".to_owned()),
2304 recovery: None,
2305 question: None,
2306 choices: Vec::new(),
2307 actions: BTreeMap::new(),
2308 question_decision: None,
2309 evidence: Vec::new(),
2310 missing_dependencies: Vec::new(),
2311 }],
2312 };
2313 apply(&queue, &questions, &verdict).unwrap();
2314
2315 let back = queue.get(&a.id).unwrap();
2316 assert_eq!(back.status, TaskStatus::Blocked);
2317 assert_eq!(back.blocked_by, ["20260101-000000-dead"]);
2318 assert_eq!(
2319 back.priority, 9,
2320 "the conductor's reply cannot carry priority"
2321 );
2322 }
2323
2324 #[test]
2325 fn a_question_decision_files_one_and_blocks_on_its_id() {
2326 let dir = tempdir().unwrap();
2327 let queue = Queue::at(dir.path().join("queue"));
2328 let questions = Questions::at(dir.path().join("questions"));
2329 let mut t = task("ambiguous");
2330 queue.put(&mut t).unwrap();
2331
2332 let verdict = Verdict {
2333 decisions: vec![Decision {
2334 id: t.id.clone(),
2335 blocked_by: Vec::new(),
2336 reason: Some("which backend?".to_owned()),
2337 recovery: None,
2338 question: Some("Which storage backend?".to_owned()),
2339 choices: vec!["SQLite".to_owned(), "Redis".to_owned()],
2340 actions: BTreeMap::new(),
2341 question_decision: None,
2342 evidence: Vec::new(),
2343 missing_dependencies: Vec::new(),
2344 }],
2345 };
2346 apply(&queue, &questions, &verdict).unwrap();
2347
2348 let back = queue.get(&t.id).unwrap();
2349 assert_eq!(back.status, TaskStatus::Blocked);
2350 assert_eq!(back.blocked_by.len(), 1);
2351 let q = questions.get(&back.blocked_by[0]).unwrap();
2352 assert_eq!(q.summary, "Which storage backend?");
2353 assert_eq!(q.node, NODE);
2354 assert!(q.status.open());
2355 }
2356
2357 #[test]
2358 fn a_task_with_an_open_question_already_reuses_it_rather_than_filing_a_second_one() {
2359 let dir = tempdir().unwrap();
2360 let queue = Queue::at(dir.path().join("queue"));
2361 let questions = Questions::at(dir.path().join("questions"));
2362 let mut t = task("asked once");
2363 queue.put(&mut t).unwrap();
2364
2365 let decision = Decision {
2366 id: t.id.clone(),
2367 reason: Some("still deciding".to_owned()),
2368 question: Some("Which backend?".to_owned()),
2369 ..Decision::default()
2370 };
2371 apply(
2372 &queue,
2373 &questions,
2374 &Verdict {
2375 decisions: vec![decision.clone()],
2376 },
2377 )
2378 .unwrap();
2379 assert_eq!(questions.list().len(), 1);
2380 let first_question_id = queue.get(&t.id).unwrap().blocked_by[0].clone();
2381
2382 let mut released = queue.get(&t.id).unwrap();
2387 released.release();
2388 queue.put(&mut released).unwrap();
2389
2390 apply(
2391 &queue,
2392 &questions,
2393 &Verdict {
2394 decisions: vec![decision],
2395 },
2396 )
2397 .unwrap();
2398 assert_eq!(questions.list().len(), 1, "no duplicate question was filed");
2399 let after = queue.get(&t.id).unwrap();
2400 assert_eq!(
2401 after.blocked_by,
2402 [first_question_id],
2403 "the existing open question is reused, not replaced"
2404 );
2405 }
2406
2407 #[test]
2408 fn a_same_id_question_from_another_node_is_not_reused() {
2409 let dir = tempdir().unwrap();
2410 let queue = Queue::at(dir.path().join("queue"));
2411 let questions = Questions::at(dir.path().join("questions"));
2412 let mut t = task("must ask the conductor");
2413 queue.put(&mut t).unwrap();
2414
2415 let mut unrelated = Question::new(
2416 t.id.clone(),
2417 "review".to_owned(),
2418 "reviewer-1".to_owned(),
2419 "An unrelated review question".to_owned(),
2420 String::new(),
2421 Vec::new(),
2422 );
2423 questions.put(&mut unrelated).unwrap();
2424
2425 apply(
2426 &queue,
2427 &questions,
2428 &Verdict {
2429 decisions: vec![Decision {
2430 id: t.id.clone(),
2431 question: Some("Which backend?".to_owned()),
2432 ..Decision::default()
2433 }],
2434 },
2435 )
2436 .unwrap();
2437
2438 let blocked_by = &queue.get(&t.id).unwrap().blocked_by;
2439 assert_eq!(blocked_by.len(), 1);
2440 assert_ne!(blocked_by[0], unrelated.id);
2441 assert!(questions.get(&unrelated.id).unwrap().status.open());
2442 assert_eq!(questions.get(&blocked_by[0]).unwrap().node, NODE);
2443 }
2444
2445 #[test]
2446 fn answering_the_question_lets_the_resolver_clear_the_block_with_the_answer_kept() {
2447 let dir = tempdir().unwrap();
2448 let queue = Queue::at(dir.path().join("queue"));
2449 let questions = Questions::at(dir.path().join("questions"));
2450 let mut t = task("waits on an answer");
2451 queue.put(&mut t).unwrap();
2452
2453 apply(
2454 &queue,
2455 &questions,
2456 &Verdict {
2457 decisions: vec![Decision {
2458 id: t.id.clone(),
2459 blocked_by: Vec::new(),
2460 reason: None,
2461 recovery: None,
2462 question: Some("Which backend?".to_owned()),
2463 choices: Vec::new(),
2464 actions: BTreeMap::new(),
2465 question_decision: None,
2466 evidence: Vec::new(),
2467 missing_dependencies: Vec::new(),
2468 }],
2469 },
2470 )
2471 .unwrap();
2472 let blocked = queue.get(&t.id).unwrap();
2473 let question_id = blocked.blocked_by[0].clone();
2474
2475 let mut q = questions.get(&question_id).unwrap();
2476 q.answer(Answer::Text("SQLite".to_owned())).unwrap();
2477 questions.put(&mut q).unwrap();
2478 assert_eq!(q.status, QuestionStatus::Answered);
2479
2480 let mut task_after = queue.get(&t.id).unwrap();
2484 task_after.record_answer(q.summary.clone(), "SQLite".to_owned());
2485 task_after.unblock(&question_id);
2486 assert_eq!(task_after.status, TaskStatus::Queued);
2487 assert_eq!(task_after.answers[0].answer, "SQLite");
2488 }
2489
2490 #[test]
2491 fn a_stalled_task_can_be_requeued_or_held() {
2492 let dir = tempdir().unwrap();
2493 let queue = Queue::at(dir.path().join("queue"));
2494 let questions = Questions::at(dir.path().join("questions"));
2495
2496 let mut requeue_me = task("stuck a");
2497 requeue_me.start("run-1".to_owned());
2498 queue.put(&mut requeue_me).unwrap();
2499
2500 let mut hold_me = task("stuck b");
2501 hold_me.start("run-2".to_owned());
2502 queue.put(&mut hold_me).unwrap();
2503
2504 apply(
2505 &queue,
2506 &questions,
2507 &Verdict {
2508 decisions: vec![
2509 Decision {
2510 id: requeue_me.id.clone(),
2511 recovery: Some(Recovery::Requeue),
2512 ..Decision::default()
2513 },
2514 Decision {
2515 id: hold_me.id.clone(),
2516 recovery: Some(Recovery::Hold),
2517 reason: Some("looks broken".to_owned()),
2518 ..Decision::default()
2519 },
2520 ],
2521 },
2522 )
2523 .unwrap();
2524
2525 let requeued = queue.get(&requeue_me.id).unwrap();
2526 assert_eq!(requeued.status, TaskStatus::Queued);
2527 assert_eq!(requeued.attempts, 0);
2528
2529 let held = queue.get(&hold_me.id).unwrap();
2530 assert_eq!(held.status, TaskStatus::Held);
2531 assert_eq!(held.hold_reason.as_deref(), Some("looks broken"));
2532 }
2533
2534 #[test]
2535 fn a_machine_held_task_asked_about_restores_to_held_once_answered() {
2536 let dir = tempdir().unwrap();
2541 let queue = Queue::at(dir.path().join("queue"));
2542 let questions = Questions::at(dir.path().join("questions"));
2543 let mut t = task("held out of attempts");
2544 t.hold_machine(Some("out of attempts".to_owned()));
2545 queue.put(&mut t).unwrap();
2546
2547 apply(
2548 &queue,
2549 &questions,
2550 &Verdict {
2551 decisions: vec![Decision {
2552 id: t.id.clone(),
2553 reason: Some("what should happen to this one?".to_owned()),
2554 question: Some("Hold it, or try again?".to_owned()),
2555 ..Decision::default()
2556 }],
2557 },
2558 )
2559 .unwrap();
2560 let blocked = queue.get(&t.id).unwrap();
2561 assert_eq!(blocked.status, TaskStatus::Blocked);
2562 let question_id = blocked.blocked_by[0].clone();
2563
2564 let mut q = questions.get(&question_id).unwrap();
2565 q.answer(Answer::Text("leave it held".to_owned())).unwrap();
2566 questions.put(&mut q).unwrap();
2567
2568 let mut after = queue.get(&t.id).unwrap();
2570 after.record_answer(q.summary.clone(), "leave it held".to_owned());
2571 after.unblock(&question_id);
2572 assert_eq!(
2573 after.status,
2574 TaskStatus::Held,
2575 "must not fall back to queued"
2576 );
2577 assert_eq!(after.hold_reason.as_deref(), Some("out of attempts"));
2578 }
2579
2580 #[test]
2581 fn a_reaffirmed_hold_with_no_new_reason_is_not_silently_auto_released_by_triage() {
2582 let dir = tempdir().unwrap();
2592 let queue = Queue::at(dir.path().join("queue"));
2593 let questions = Questions::at(dir.path().join("questions"));
2594 let mut t = task("disk pressure, then reconsidered");
2595 t.hold_machine(Some(
2596 "not enough free space to start a run: 10 bytes free, 100 required by \
2597 `[disk] min_free_bytes`"
2598 .to_owned(),
2599 ));
2600 t.record_answer(
2601 "How should this be handled?".to_owned(),
2602 "keep it held, a human will look at it later".to_owned(),
2603 );
2604 queue.put(&mut t).unwrap();
2605
2606 apply(
2607 &queue,
2608 &questions,
2609 &Verdict {
2610 decisions: vec![Decision {
2611 id: t.id.clone(),
2612 recovery: Some(Recovery::Hold),
2613 ..Decision::default()
2614 }],
2615 },
2616 )
2617 .unwrap();
2618
2619 let after = queue.get(&t.id).unwrap();
2620 assert_eq!(after.status, TaskStatus::Held);
2621 assert!(
2622 !after
2623 .hold_reason
2624 .as_deref()
2625 .unwrap_or_default()
2626 .starts_with("not enough free space"),
2627 "the stale disk-pressure text must not survive a reconfirmed hold: {:?}",
2628 after.hold_reason
2629 );
2630
2631 let cfg_dir = tempdir().unwrap();
2634 let config = cfg_dir.path().join("magi.toml");
2635 std::fs::write(&config, "[disk]\nmin_free_bytes = 0\n").unwrap();
2636 let report =
2637 crate::triage::run_once(&queue, &questions, Some(&config), jiff::Timestamp::now());
2638 assert!(report.resumed.is_empty(), "must not be auto-released");
2639 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
2640 }
2641
2642 #[test]
2643 fn explicit_resumption_rehold_requires_new_evidence_and_another_answer() {
2644 crate::run::pin_test_home();
2645 let dir = tempdir().unwrap();
2646 let queue = Queue::at(dir.path().join("queue"));
2647 let questions = Questions::at(dir.path().join("questions"));
2648 let config = dir.path().join("magi.toml");
2649 std::fs::write(&config, "[disk]\nmin_free_bytes = 0\n").unwrap();
2650 let now = jiff::Timestamp::now();
2651 let triage = || crate::triage::run_once(&queue, &questions, Some(&config), now);
2652 let open = || {
2653 questions
2654 .list()
2655 .into_iter()
2656 .filter(|q| q.node == "triage" && q.status.open())
2657 .collect::<Vec<_>>()
2658 };
2659 let hold = Decision {
2660 recovery: Some(Recovery::Hold),
2661 reason: Some("waiting on manual worktree cleanup".to_owned()),
2662 ..Decision::default()
2663 };
2664
2665 let mut t = task("looping hold");
2666 t.hold_machine(Some("waiting on manual worktree cleanup".to_owned()));
2667 queue.put(&mut t).unwrap();
2668 let hold = Decision {
2669 id: t.id.clone(),
2670 ..hold
2671 };
2672
2673 assert_eq!(triage().asked.len(), 1);
2675 let first = open().remove(0);
2676 let mut q = questions.get(&first.id).unwrap();
2677 let resume = q.choices[0].clone();
2678 q.answer(Answer::Choice(resume)).unwrap();
2679 questions.put(&mut q).unwrap();
2680 assert_eq!(triage().answered.len(), 1);
2681 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
2682
2683 apply(
2685 &queue,
2686 &questions,
2687 &Verdict {
2688 decisions: vec![hold.clone()],
2689 },
2690 )
2691 .unwrap();
2692 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
2693 assert!(triage().asked.is_empty());
2694
2695 let mut evidence = Question::new(
2697 t.id.clone(),
2698 "preflight".into(),
2699 "check".into(),
2700 "New permission failure".into(),
2701 String::new(),
2702 Vec::new(),
2703 );
2704 questions.put(&mut evidence).unwrap();
2705 let hold = Decision {
2706 evidence: vec![evidence.id.clone()],
2707 reason: Some("new permission check failed".into()),
2708 ..hold
2709 };
2710 apply(
2711 &queue,
2712 &questions,
2713 &Verdict {
2714 decisions: vec![hold.clone()],
2715 },
2716 )
2717 .unwrap();
2718 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
2719
2720 assert_eq!(triage().asked.len(), 1);
2722 let second = open().remove(0);
2723 assert!(second.detail.contains("new permission check failed"));
2724 assert!(triage().asked.is_empty(), "no duplicate question");
2725 assert_eq!(open().len(), 1);
2726
2727 let mut q = questions.get(&second.id).unwrap();
2729 let force = q.choices[0].clone();
2730 q.answer(Answer::Choice(force)).unwrap();
2731 questions.put(&mut q).unwrap();
2732 assert_eq!(triage().answered.len(), 1);
2733 apply(
2734 &queue,
2735 &questions,
2736 &Verdict {
2737 decisions: vec![hold],
2738 },
2739 )
2740 .unwrap();
2741 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
2742 }
2743
2744 #[test]
2745 fn conductor_resumption_notice_does_not_solicit_unregistered_questions() {
2746 crate::run::pin_test_home();
2747 let dir = tempdir().unwrap();
2748 let queue = Queue::at(dir.path().join("queue"));
2749 let questions = Questions::at(dir.path().join("questions"));
2750
2751 let mut t = task("task with explicit resumption");
2752 t.status = TaskStatus::Queued;
2753 t.resumption = Some(crate::queue::Resumption {
2754 generation: 1,
2755 source: "test".into(),
2756 question_id: Some("q1".into()),
2757 at: jiff::Timestamp::now(),
2758 instruction: "resume".into(),
2759 answers_through: 0,
2760 runs_through: 0,
2761 cleared_reason: None,
2762 blocking_evidence: Vec::new(),
2763 });
2764 queue.put(&mut t).unwrap();
2765
2766 let decision = Decision {
2768 id: t.id.clone(),
2769 question: Some("How should we proceed with this task?".into()),
2770 blocked_by: vec!["dep-x".into()],
2771 reason: Some("needs clarification".into()),
2772 recovery: Some(Recovery::Hold),
2773 ..Decision::default()
2774 };
2775
2776 apply(
2777 &queue,
2778 &questions,
2779 &Verdict {
2780 decisions: vec![decision],
2781 },
2782 )
2783 .unwrap();
2784
2785 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
2787 assert!(questions.list().is_empty());
2789
2790 let notices = crate::notices::Notices::open();
2792 let notice = notices
2793 .get(&crate::notices::id_of(&format!(
2794 "conductor-resumption:{}",
2795 t.id
2796 )))
2797 .expect("conductor-resumption notice filed");
2798
2799 assert_eq!(
2800 notice.link,
2801 Some(crate::notices::Link::Task { id: t.id.clone() })
2802 );
2803 assert!(!notice.message.contains("How should we proceed"));
2805 assert!(
2807 notice
2808 .message
2809 .contains("No reply to this notice is needed.")
2810 );
2811 assert!(!notice.message.contains("Some("));
2813 assert!(!notice.message.contains("None"));
2814 assert!(!notice.message.contains("[]"));
2815 assert!(!notice.message.contains("{:?}"));
2816 assert!(notice.message.contains("Proposed dependencies: dep-x."));
2818 }
2819
2820 #[test]
2821 fn a_runnable_task_can_be_held_directly_without_a_question() {
2822 let dir = tempdir().unwrap();
2823 let queue = Queue::at(dir.path().join("queue"));
2824 let questions = Questions::at(dir.path().join("questions"));
2825 let mut t = task("already answered, should stay put");
2826 queue.put(&mut t).unwrap();
2827
2828 apply(
2829 &queue,
2830 &questions,
2831 &Verdict {
2832 decisions: vec![Decision {
2833 id: t.id.clone(),
2834 recovery: Some(Recovery::Hold),
2835 reason: Some("operator already said keep this held".to_owned()),
2836 ..Decision::default()
2837 }],
2838 },
2839 )
2840 .unwrap();
2841
2842 let after = queue.get(&t.id).unwrap();
2843 assert_eq!(after.status, TaskStatus::Held);
2844 assert_eq!(after.hold_source, Some(crate::queue::HoldSource::Machine));
2845 }
2846
2847 #[test]
2848 fn done_recovery_closes_a_held_task_whose_goal_is_already_met() {
2849 crate::run::pin_test_home();
2850 let dir = tempdir().unwrap();
2856 let queue = Queue::at(dir.path().join("queue"));
2857 let questions = Questions::at(dir.path().join("questions"));
2858 let mut t = task("already merged by hand");
2859 t.hold_machine(Some("branch survived, awaiting a decision".to_owned()));
2860 t.record_answer(
2861 "Handle this one?".to_owned(),
2862 "already merged and cleaned up, close it".to_owned(),
2863 );
2864 queue.put(&mut t).unwrap();
2865
2866 apply(
2867 &queue,
2868 &questions,
2869 &Verdict {
2870 decisions: vec![Decision {
2871 id: t.id.clone(),
2872 recovery: Some(Recovery::Done),
2873 reason: Some("operator confirmed this already landed".to_owned()),
2874 ..Decision::default()
2875 }],
2876 },
2877 )
2878 .unwrap();
2879
2880 let after = queue.get(&t.id).unwrap();
2881 assert_eq!(after.status, TaskStatus::Done);
2882 assert!(after.hold_reason.is_none());
2883 assert_eq!(after.answers.len(), 1, "the record of why is kept");
2884 }
2885
2886 #[test]
2887 fn done_recovery_is_ignored_for_a_runnable_or_running_task() {
2888 let dir = tempdir().unwrap();
2889 let queue = Queue::at(dir.path().join("queue"));
2890 let questions = Questions::at(dir.path().join("questions"));
2891
2892 let mut queued = task("never ran yet");
2893 queue.put(&mut queued).unwrap();
2894
2895 let mut running = task("mid-run");
2896 running.start("run-1".to_owned());
2897 queue.put(&mut running).unwrap();
2898
2899 for id in [queued.id.clone(), running.id.clone()] {
2900 apply(
2901 &queue,
2902 &questions,
2903 &Verdict {
2904 decisions: vec![Decision {
2905 id,
2906 recovery: Some(Recovery::Done),
2907 ..Decision::default()
2908 }],
2909 },
2910 )
2911 .unwrap();
2912 }
2913
2914 assert_eq!(queue.get(&queued.id).unwrap().status, TaskStatus::Queued);
2915 assert_eq!(queue.get(&running.id).unwrap().status, TaskStatus::Running);
2916 }
2917
2918 #[test]
2919 fn a_question_after_two_settled_answers_is_still_filed_and_blocks() {
2920 let dir = tempdir().unwrap();
2923 let queue = Queue::at(dir.path().join("queue"));
2924 let questions = Questions::at(dir.path().join("questions"));
2925 let mut t = task("asked about repeatedly");
2926 t.hold_machine(Some("out of attempts".to_owned()));
2927 t.record_answer("Handle this one? (1)".to_owned(), "not yet".to_owned());
2928 t.record_answer(
2929 "Handle this one? (2)".to_owned(),
2930 "still not yet".to_owned(),
2931 );
2932 queue.put(&mut t).unwrap();
2933 assert_eq!(questions.list().len(), 0);
2934
2935 let verdict = Verdict {
2936 decisions: vec![Decision {
2937 id: t.id.clone(),
2938 question: Some("Branch conflicts with origin/main, how do we proceed?".to_owned()),
2939 ..Decision::default()
2940 }],
2941 };
2942 apply(&queue, &questions, &verdict).unwrap();
2943
2944 let filed = questions.list();
2945 assert_eq!(filed.len(), 1, "the question was filed");
2946 assert_eq!(
2947 filed[0].summary,
2948 "Branch conflicts with origin/main, how do we proceed?"
2949 );
2950 let deputy = filed[0]
2951 .deputy
2952 .as_ref()
2953 .expect("the wait is handed to a deputy");
2954 assert!(deputy.brief.contains(&t.id), "{}", deputy.brief);
2955 assert_eq!(
2956 deputy.starts, 0,
2957 "filing never starts anything: the loop does not wait"
2958 );
2959 assert!(filed[0].status.open());
2960 assert_eq!(filed[0].node, NODE);
2961 let after = queue.get(&t.id).unwrap();
2962 assert_eq!(after.status, TaskStatus::Blocked);
2963 assert_eq!(after.blocked_by, vec![filed[0].id.clone()]);
2964 assert_eq!(after.answers.len(), 2, "the prior answers are untouched");
2965 assert!(
2966 !after
2967 .hold_reason
2968 .clone()
2969 .unwrap_or_default()
2970 .contains("conduct tried to ask"),
2971 "no hold was applied"
2972 );
2973
2974 apply(&queue, &questions, &verdict).unwrap();
2975 let again = questions.list();
2976 assert_eq!(again.len(), 1, "the open question is reused");
2977 assert_eq!(again[0].id, filed[0].id);
2978 }
2979
2980 #[test]
2981 fn question_source_identity_resolves_aliases_and_rejects_invented_targets() {
2982 let dir = tempdir().unwrap();
2983 init_repo_with_branch(dir.path(), "source-a");
2984 let mut t = task("source decision");
2985 t.repo = dir.path().into();
2986 let decision = |reference: &str| QuestionDecision {
2987 operation: QuestionOperation::Recover,
2988 target: QuestionTarget::Source {
2989 reference: reference.into(),
2990 },
2991 };
2992 assert_eq!(
2993 decision("source-a").identity(&t).unwrap(),
2994 decision("refs/heads/source-a").identity(&t).unwrap()
2995 );
2996 assert_ne!(
2997 decision("source-a").identity(&t).unwrap(),
2998 decision("main").identity(&t).unwrap()
2999 );
3000 assert!(decision("invented-source-label").identity(&t).is_err());
3001 let unrelated = QuestionDecision {
3002 operation: QuestionOperation::Resume,
3003 target: QuestionTarget::Run {
3004 id: "unrelated-run".into(),
3005 },
3006 };
3007 assert!(unrelated.identity(&t).is_err());
3008 }
3009
3010 #[test]
3011 fn invalid_question_targets_still_file_and_block_queued_tasks() {
3012 let dir = tempdir().unwrap();
3013 init_repo_with_branch(dir.path(), "source-a");
3014 let queue = Queue::at(dir.path().join("queue"));
3015 let questions = Questions::at(dir.path().join("questions"));
3016 for target in [
3017 QuestionTarget::Source {
3018 reference: "missing-source".into(),
3019 },
3020 QuestionTarget::Run {
3021 id: "unrelated-run".into(),
3022 },
3023 ] {
3024 let mut t = task("decision with invalid metadata");
3025 t.repo = dir.path().into();
3026 queue.put(&mut t).unwrap();
3027 let d = Decision {
3028 id: t.id.clone(),
3029 question: Some("Which recovery should proceed?".into()),
3030 choices: vec!["inspect first".into(), "keep waiting".into()],
3031 question_decision: Some(QuestionDecision {
3032 operation: QuestionOperation::Recover,
3033 target,
3034 }),
3035 ..Decision::default()
3036 };
3037 apply_one(&queue, &questions, &d, None).unwrap();
3038 let q = questions
3039 .list()
3040 .into_iter()
3041 .find(|q| q.run == t.id)
3042 .unwrap();
3043 assert_eq!(q.summary, d.question.as_deref().unwrap());
3044 assert_eq!(q.choices, d.choices);
3045 assert!(q.status.open());
3046 let context: serde_json::Value =
3047 serde_json::from_str(q.decision_context.as_ref().unwrap()).unwrap();
3048 assert!(context[3].is_null(), "invalid metadata was discarded");
3049 let after = queue.get(&t.id).unwrap();
3050 assert_eq!(after.status, TaskStatus::Blocked);
3051 assert_eq!(after.blocked_by, vec![q.id.clone()]);
3052 apply_one(&queue, &questions, &d, None).unwrap();
3053 assert_eq!(questions.list().iter().filter(|q| q.run == t.id).count(), 1);
3054 }
3055 }
3056
3057 #[test]
3058 fn answered_conductor_question_needs_changed_facts_before_reasking() {
3059 let dir = tempdir().unwrap();
3060 let queue = Queue::at(dir.path().join("queue"));
3061 let questions = Questions::at(dir.path().join("questions"));
3062 let mut t = task("recovery decision");
3063 t.hold_machine(Some("out of attempts".into()));
3064 t.runs = vec!["source-run-a".into(), "source-run-b".into()];
3065 queue.put(&mut t).unwrap();
3066 let mut d = Decision {
3067 id: t.id.clone(),
3068 question: Some("Recover from source A?".into()),
3069 choices: vec!["approve source A".into(), "keep held".into()],
3070 question_decision: Some(QuestionDecision {
3071 operation: QuestionOperation::Recover,
3072 target: QuestionTarget::Run {
3073 id: "source-run-a".into(),
3074 },
3075 }),
3076 ..Decision::default()
3077 };
3078 apply_one(&queue, &questions, &d, None).unwrap();
3079 let mut q = questions.list().pop().unwrap();
3080 q.answer(crate::ask::Answer::Choice("keep held".into()))
3081 .unwrap();
3082 questions.put(&mut q).unwrap();
3083 queue
3084 .modify(&t.id, |task| {
3085 task.unblock(&q.id);
3086 task.hold_machine(Some("recovery remains under consideration".into()));
3087 true
3088 })
3089 .unwrap();
3090 d.question = Some("Should we keep waiting on recovery?".into());
3091 d.choices = vec!["recover using source A".into(), "remain on hold".into()];
3092 apply_one(&queue, &questions, &d, None).unwrap();
3093 assert_eq!(questions.list().len(), 1, "no repeated operator turn");
3094 d.question = Some("Recover from source B?".into());
3095 d.question_decision.as_mut().unwrap().target = QuestionTarget::Run {
3097 id: "source-run-b".into(),
3098 };
3099 apply_one(&queue, &questions, &d, None).unwrap();
3100 assert_eq!(
3101 questions.list().len(),
3102 2,
3103 "new decision with unchanged task facts"
3104 );
3105 let after = queue.get(&t.id).unwrap();
3106 assert_eq!(after.instruction, t.instruction);
3107 assert_eq!(after.runs, t.runs);
3108 assert_eq!(after.status, TaskStatus::Blocked);
3109 }
3110
3111 #[test]
3112 fn a_second_conductor_question_is_still_allowed_after_one_settled_answer() {
3113 let dir = tempdir().unwrap();
3114 let queue = Queue::at(dir.path().join("queue"));
3115 let questions = Questions::at(dir.path().join("questions"));
3116 let mut t = task("asked about once already");
3117 t.hold_machine(Some("out of attempts".to_owned()));
3118 t.record_answer("Handle this one?".to_owned(), "not yet".to_owned());
3119 queue.put(&mut t).unwrap();
3120
3121 apply(
3122 &queue,
3123 &questions,
3124 &Verdict {
3125 decisions: vec![Decision {
3126 id: t.id.clone(),
3127 question: Some("Still not sure - now what?".to_owned()),
3128 ..Decision::default()
3129 }],
3130 },
3131 )
3132 .unwrap();
3133
3134 assert_eq!(questions.list().len(), 1, "the second question was filed");
3135 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
3136 }
3137
3138 #[test]
3139 fn a_held_task_with_an_open_triage_question_is_left_to_triage() {
3140 let dir = tempdir().unwrap();
3146 let queue = Queue::at(dir.path().join("queue"));
3147 let questions = Questions::at(dir.path().join("questions"));
3148 let mut t = task("held, triage already asking about it");
3149 t.hold_machine(Some("cause unclear".to_owned()));
3150 queue.put(&mut t).unwrap();
3151
3152 let mut triage_q = Question::new(
3153 t.id.clone(),
3154 crate::triage::NODE.to_owned(),
3155 "triage".to_owned(),
3156 "Still needed?".to_owned(),
3157 String::new(),
3158 vec![
3159 "resume".to_owned(),
3160 "not yet".to_owned(),
3161 "discard".to_owned(),
3162 ],
3163 );
3164 questions.put(&mut triage_q).unwrap();
3165
3166 for decision in [
3167 Decision {
3168 id: t.id.clone(),
3169 question: Some("what now?".to_owned()),
3170 ..Decision::default()
3171 },
3172 Decision {
3173 id: t.id.clone(),
3174 recovery: Some(Recovery::Requeue),
3175 ..Decision::default()
3176 },
3177 ] {
3178 apply(
3179 &queue,
3180 &questions,
3181 &Verdict {
3182 decisions: vec![decision],
3183 },
3184 )
3185 .unwrap();
3186 }
3187
3188 let after = queue.get(&t.id).unwrap();
3189 assert_eq!(
3190 after.status,
3191 TaskStatus::Held,
3192 "triage still owns this hold"
3193 );
3194 assert!(after.blocked_by.is_empty());
3195 assert_eq!(
3196 questions.list().len(),
3197 1,
3198 "no second, conductor-owned question was filed"
3199 );
3200 }
3201
3202 #[test]
3203 fn a_held_task_with_an_answered_but_unapplied_triage_question_is_still_left_alone() {
3204 let dir = tempdir().unwrap();
3212 let queue = Queue::at(dir.path().join("queue"));
3213 let questions = Questions::at(dir.path().join("questions"));
3214 let mut t = task("held, triage question answered but not yet applied");
3215 t.hold_machine(Some("cause unclear".to_owned()));
3216 queue.put(&mut t).unwrap();
3217
3218 let mut triage_q = Question::new(
3219 t.id.clone(),
3220 crate::triage::NODE.to_owned(),
3221 "triage".to_owned(),
3222 "Still needed?".to_owned(),
3223 String::new(),
3224 vec![
3225 "resume".to_owned(),
3226 "not yet".to_owned(),
3227 "discard".to_owned(),
3228 ],
3229 );
3230 questions.put(&mut triage_q).unwrap();
3231 triage_q
3232 .answer(Answer::Choice("not yet".to_owned()))
3233 .unwrap();
3234 questions.put(&mut triage_q).unwrap();
3235 assert!(!triage_q.status.open());
3236
3237 apply(
3238 &queue,
3239 &questions,
3240 &Verdict {
3241 decisions: vec![Decision {
3242 id: t.id.clone(),
3243 question: Some("what now?".to_owned()),
3244 ..Decision::default()
3245 }],
3246 },
3247 )
3248 .unwrap();
3249
3250 let after = queue.get(&t.id).unwrap();
3251 assert_eq!(
3252 after.status,
3253 TaskStatus::Held,
3254 "triage's own answer is not yet applied - conduct must wait"
3255 );
3256 assert_eq!(
3257 questions.list().len(),
3258 1,
3259 "no conductor question was filed over the pending triage answer"
3260 );
3261 }
3262
3263 #[test]
3264 fn manual_hold_rejects_hostile_or_stale_conductor_recovery() {
3265 let dir = tempdir().unwrap();
3266 let queue = Queue::at(dir.path().join("queue"));
3267 let questions = Questions::at(dir.path().join("questions"));
3268 let mut held = task("manual recovery");
3269 held.priority = 300;
3270 held.runs.push("run20260912-224242-daf5".to_owned());
3271 held.hold_manual(Some(
3272 "active manual recovery run20260912-224242-daf5".to_owned(),
3273 ));
3274 queue.put(&mut held).unwrap();
3275
3276 for decision in [
3280 Decision {
3281 id: held.id.clone(),
3282 recovery: Some(Recovery::Requeue),
3283 ..Decision::default()
3284 },
3285 Decision {
3286 id: held.id.clone(),
3287 recovery: Some(Recovery::Hold),
3288 reason: Some("stale replacement reason".to_owned()),
3289 ..Decision::default()
3290 },
3291 Decision {
3292 id: held.id.clone(),
3293 recovery: Some(Recovery::Review),
3294 ..Decision::default()
3295 },
3296 Decision {
3297 id: held.id.clone(),
3298 blocked_by: vec!["other-task".to_owned()],
3299 question: Some("retry now?".to_owned()),
3300 ..Decision::default()
3301 },
3302 ] {
3303 apply(
3304 &queue,
3305 &questions,
3306 &Verdict {
3307 decisions: vec![decision],
3308 },
3309 )
3310 .unwrap();
3311 }
3312
3313 let after = queue.get(&held.id).unwrap();
3314 assert_eq!(after.status, TaskStatus::Held);
3315 assert!(after.operator_held());
3316 assert_eq!(after.priority, 300);
3317 assert_eq!(after.runs, ["run20260912-224242-daf5"]);
3318 assert_eq!(
3319 after.hold_reason.as_deref(),
3320 Some("active manual recovery run20260912-224242-daf5")
3321 );
3322 assert!(after.blocked_by.is_empty());
3323 assert!(questions.list().is_empty());
3324 assert!(
3325 queue.next_runnable().is_none(),
3326 "must not dispatch a duplicate"
3327 );
3328 }
3329
3330 #[test]
3331 fn machine_holds_remain_recoverable_and_manual_release_is_authorization() {
3332 let dir = tempdir().unwrap();
3333 let queue = Queue::at(dir.path().join("queue"));
3334 let questions = Questions::at(dir.path().join("questions"));
3335
3336 let mut automatic = task("disk gate");
3337 automatic.hold_machine(Some("disk full".to_owned()));
3338 queue.put(&mut automatic).unwrap();
3339 let requeue = || Verdict {
3340 decisions: vec![Decision {
3341 id: automatic.id.clone(),
3342 recovery: Some(Recovery::Requeue),
3343 ..Decision::default()
3344 }],
3345 };
3346 apply(&queue, &questions, &requeue()).unwrap();
3347 assert_eq!(queue.get(&automatic.id).unwrap().status, TaskStatus::Queued);
3348
3349 let mut manual = task("operator gate");
3350 manual.hold_manual(Some("wait for operator".to_owned()));
3351 queue.put(&mut manual).unwrap();
3352 apply(
3353 &queue,
3354 &questions,
3355 &Verdict {
3356 decisions: vec![Decision {
3357 id: manual.id.clone(),
3358 recovery: Some(Recovery::Requeue),
3359 ..Decision::default()
3360 }],
3361 },
3362 )
3363 .unwrap();
3364 assert_eq!(queue.get(&manual.id).unwrap().status, TaskStatus::Held);
3365
3366 let mut released = queue.get(&manual.id).unwrap();
3369 released.release();
3370 queue.put(&mut released).unwrap();
3371 assert_eq!(queue.get(&manual.id).unwrap().status, TaskStatus::Queued);
3372 }
3373
3374 #[test]
3375 fn legacy_reasoned_hold_is_protected_without_losing_its_metadata() {
3376 let dir = tempdir().unwrap();
3377 let queue = Queue::at(dir.path().join("queue"));
3378 let questions = Questions::at(dir.path().join("questions"));
3379 let mut legacy = task("old explicit hold");
3380 legacy.status = TaskStatus::Held;
3381 legacy.hold_reason = Some("manual recovery already active".to_owned());
3382 legacy.hold_source = None;
3383 legacy.blocked_by = vec!["dependency".to_owned()];
3384 queue.put(&mut legacy).unwrap();
3385
3386 apply(
3387 &queue,
3388 &questions,
3389 &Verdict {
3390 decisions: vec![Decision {
3391 id: legacy.id.clone(),
3392 recovery: Some(Recovery::Requeue),
3393 ..Decision::default()
3394 }],
3395 },
3396 )
3397 .unwrap();
3398
3399 let after = queue.get(&legacy.id).unwrap();
3400 assert_eq!(after.status, TaskStatus::Held);
3401 assert_eq!(after.hold_source, None);
3402 assert_eq!(after.hold_reason, legacy.hold_reason);
3403 assert_eq!(after.blocked_by, legacy.blocked_by);
3404 }
3405
3406 #[test]
3407 fn review_recovery_is_a_no_op_without_a_survivable_branch() {
3408 crate::run::pin_test_home();
3414 let dir = tempdir().unwrap();
3415 let queue = Queue::at(dir.path().join("queue"));
3416 let questions = Questions::at(dir.path().join("questions"));
3417 let mut t = task("blocked with no readable run");
3418 t.start("20260101-000000-dead".to_owned()); t.fail("blocked", 5);
3420 queue.put(&mut t).unwrap();
3421
3422 apply(
3423 &queue,
3424 &questions,
3425 &Verdict {
3426 decisions: vec![Decision {
3427 id: t.id.clone(),
3428 recovery: Some(Recovery::Review),
3429 ..Decision::default()
3430 }],
3431 },
3432 )
3433 .unwrap();
3434
3435 let after = queue.get(&t.id).unwrap();
3436 assert_eq!(
3437 after.status,
3438 TaskStatus::Failed,
3439 "with nothing to reopen, the decision is dropped rather than guessed at"
3440 );
3441 assert!(after.review_branch.is_none());
3442 }
3443
3444 #[test]
3445 fn requeue_and_review_recovery_are_ignored_for_a_runnable_task() {
3446 let dir = tempdir().unwrap();
3450 let queue = Queue::at(dir.path().join("queue"));
3451 let questions = Questions::at(dir.path().join("questions"));
3452
3453 for recovery in [Recovery::Requeue, Recovery::Review] {
3454 let mut t = task("ordinary");
3455 queue.put(&mut t).unwrap();
3456
3457 apply(
3458 &queue,
3459 &questions,
3460 &Verdict {
3461 decisions: vec![Decision {
3462 id: t.id.clone(),
3463 recovery: Some(recovery),
3464 ..Decision::default()
3465 }],
3466 },
3467 )
3468 .unwrap();
3469
3470 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
3471 }
3472 }
3473
3474 #[tokio::test]
3475 async fn a_broken_agent_leaves_the_queue_untouched_and_does_not_error() {
3476 let dir = tempdir().unwrap();
3477 let cfg = config(mock_agent(dir.path(), BROKEN, BTreeMap::new()));
3478 let queue = Queue::at(dir.path().join("queue"));
3479 let questions = Questions::at(dir.path().join("questions"));
3480 let mut t = task("normal");
3481 queue.put(&mut t).unwrap();
3482
3483 let mut conductor = Conductor::new();
3484 conductor
3485 .maybe_run(
3486 &cfg,
3487 dir.path(),
3488 &queue,
3489 &questions,
3490 dir.path(),
3491 &[t.clone()],
3492 &[],
3493 &[],
3494 2,
3495 )
3496 .await;
3497
3498 assert_eq!(
3499 queue.get(&t.id).unwrap().status,
3500 TaskStatus::Queued,
3501 "a failed invocation must change nothing"
3502 );
3503 assert!(
3504 queue.next_runnable().is_some(),
3505 "the loop must still be able to take the next task"
3506 );
3507 }
3508
3509 #[tokio::test]
3510 async fn a_reply_with_no_json_leaves_the_queue_untouched() {
3511 let dir = tempdir().unwrap();
3512 let cfg = config(mock_agent(dir.path(), GARBAGE, BTreeMap::new()));
3513 let queue = Queue::at(dir.path().join("queue"));
3514 let questions = Questions::at(dir.path().join("questions"));
3515 let mut t = task("normal");
3516 queue.put(&mut t).unwrap();
3517
3518 let mut conductor = Conductor::new();
3519 conductor
3520 .maybe_run(
3521 &cfg,
3522 dir.path(),
3523 &queue,
3524 &questions,
3525 dir.path(),
3526 &[t.clone()],
3527 &[],
3528 &[],
3529 2,
3530 )
3531 .await;
3532
3533 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
3534 }
3535
3536 #[tokio::test]
3537 async fn a_conductor_chain_falls_to_the_next_agent_once_each() {
3538 let dir = tempdir().unwrap();
3539 let mut t = task("chained");
3540 let reply = format!(
3541 "{{\"decisions\":[{{\"id\":\"{}\",\"blocked_by\":[\"x\"],\"reason\":\"why\"}}]}}",
3542 t.id
3543 );
3544 let counted = |id: &str, tail: &str| {
3545 let calls = dir.path().join(format!("{id}.calls"));
3546 let path = dir.path().join(format!("{id}.sh"));
3547 std::fs::write(
3548 &path,
3549 format!(
3550 "#!/bin/sh\ncat >/dev/null\necho x >> '{}'\n{tail}\n",
3551 calls.display()
3552 ),
3553 )
3554 .unwrap();
3555 AgentSpec {
3556 id: id.to_owned(),
3557 kind: AgentKind::Command,
3558 model: None,
3559 command: vec!["sh".to_owned(), path.to_string_lossy().into_owned()],
3560 extra_args: Vec::new(),
3561 env: BTreeMap::new(),
3562 prompt_delivery: None,
3563 }
3564 };
3565 let n_calls = |id: &str| {
3566 std::fs::read_to_string(dir.path().join(format!("{id}.calls")))
3567 .map_or(0, |s| s.lines().count())
3568 };
3569 let mut cfg = config(counted("a", "exit 3"));
3570 cfg.agents = vec![
3571 counted("a", "exit 3"),
3572 counted("b", &format!("printf '%s' '{reply}'")),
3573 ];
3574 cfg.roles.conductor = Some(crate::config::AgentChoice::Chain(vec![
3575 "a".into(),
3576 "b".into(),
3577 "a".into(),
3578 ]));
3579 let queue = Queue::at(dir.path().join("queue"));
3580 let questions = Questions::at(dir.path().join("questions"));
3581 queue.put(&mut t).unwrap();
3582
3583 let mut conductor = Conductor::new();
3584 conductor
3585 .maybe_run(
3586 &cfg,
3587 dir.path(),
3588 &queue,
3589 &questions,
3590 dir.path(),
3591 &[t.clone()],
3592 &[],
3593 &[],
3594 2,
3595 )
3596 .await;
3597
3598 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
3599 assert_eq!(n_calls("a"), 1, "each id is tried once");
3600 assert_eq!(n_calls("b"), 1);
3601 let saved = std::fs::read_to_string(seat_path(dir.path())).unwrap();
3602 assert!(
3603 saved.contains("\"b\""),
3604 "the seat on disk is the one that ran: {saved}"
3605 );
3606 }
3607
3608 #[tokio::test]
3609 async fn json_survives_code_fences_and_a_preamble() {
3610 let dir = tempdir().unwrap();
3611 let mut t = task("fenced");
3612 let reply = format!(
3613 "Sure, here is my decision.\n\n```json\n{{\"decisions\":[{{\"id\":\"{}\",\
3614 \"blocked_by\":[\"x\"],\"reason\":\"why\"}}]}}\n```\n",
3615 t.id
3616 );
3617 let cfg = config(mock_agent(dir.path(), REPLY, env(&reply)));
3618 let queue = Queue::at(dir.path().join("queue"));
3619 let questions = Questions::at(dir.path().join("questions"));
3620 queue.put(&mut t).unwrap();
3621
3622 let mut conductor = Conductor::new();
3623 conductor
3624 .maybe_run(
3625 &cfg,
3626 dir.path(),
3627 &queue,
3628 &questions,
3629 dir.path(),
3630 &[t.clone()],
3631 &[],
3632 &[],
3633 2,
3634 )
3635 .await;
3636
3637 let back = queue.get(&t.id).unwrap();
3638 assert_eq!(back.status, TaskStatus::Blocked);
3639 assert_eq!(back.blocked_by, ["x"]);
3640 }
3641
3642 #[tokio::test]
3643 async fn the_conductor_is_not_called_again_when_nothing_worth_looking_at_has_changed() {
3644 let dir = tempdir().unwrap();
3647 let cfg = config(mock_agent(dir.path(), REPLY, env("{\"decisions\":[]}")));
3648 let queue = Queue::at(dir.path().join("queue"));
3649 let questions = Questions::at(dir.path().join("questions"));
3650 let mut t = task("stable");
3651 queue.put(&mut t).unwrap();
3652 let artifacts = dir.path().join("conduct").join("artifacts");
3653 let turn = |n: usize| artifacts.join(format!("turn-{n}.out"));
3654
3655 let mut conductor = Conductor::new();
3656 conductor
3657 .maybe_run(
3658 &cfg,
3659 dir.path(),
3660 &queue,
3661 &questions,
3662 dir.path(),
3663 &[t.clone()],
3664 &[],
3665 &[],
3666 2,
3667 )
3668 .await;
3669 assert!(turn(1).is_file(), "the first cycle must call the conductor");
3670
3671 conductor
3672 .maybe_run(
3673 &cfg,
3674 dir.path(),
3675 &queue,
3676 &questions,
3677 dir.path(),
3678 &[t.clone()],
3679 &[],
3680 &[],
3681 2,
3682 )
3683 .await;
3684 assert!(
3685 !turn(2).is_file(),
3686 "an unchanged revision and an unchanged stalled/finished set must not call the \
3687 conductor twice"
3688 );
3689
3690 t.priority = 1;
3692 queue.put(&mut t).unwrap();
3693 conductor
3694 .maybe_run(
3695 &cfg,
3696 dir.path(),
3697 &queue,
3698 &questions,
3699 dir.path(),
3700 &[t.clone()],
3701 &[],
3702 &[],
3703 2,
3704 )
3705 .await;
3706 assert!(turn(2).is_file(), "a moved revision calls it again");
3707 }
3708
3709 #[tokio::test]
3710 async fn a_task_turning_stalled_calls_the_conductor_again_despite_an_unchanged_revision() {
3711 let dir = tempdir().unwrap();
3717 let cfg = config(mock_agent(dir.path(), REPLY, env("{\"decisions\":[]}")));
3718 let queue = Queue::at(dir.path().join("queue"));
3719 let questions = Questions::at(dir.path().join("questions"));
3720 let mut t = task("quiet");
3721 queue.put(&mut t).unwrap();
3722 let artifacts = dir.path().join("conduct").join("artifacts");
3723 let turn = |n: usize| artifacts.join(format!("turn-{n}.out"));
3724
3725 let mut conductor = Conductor::new();
3726 conductor
3727 .maybe_run(
3728 &cfg,
3729 dir.path(),
3730 &queue,
3731 &questions,
3732 dir.path(),
3733 &[t.clone()],
3734 &[],
3735 &[],
3736 2,
3737 )
3738 .await;
3739 assert!(turn(1).is_file());
3740
3741 conductor
3742 .maybe_run(
3743 &cfg,
3744 dir.path(),
3745 &queue,
3746 &questions,
3747 dir.path(),
3748 &[],
3749 &[t.clone()],
3750 &[],
3751 2,
3752 )
3753 .await;
3754 assert!(
3755 turn(2).is_file(),
3756 "a task turning stalled must call the conductor again"
3757 );
3758
3759 conductor
3762 .maybe_run(
3763 &cfg,
3764 dir.path(),
3765 &queue,
3766 &questions,
3767 dir.path(),
3768 &[],
3769 &[t.clone()],
3770 &[],
3771 2,
3772 )
3773 .await;
3774 assert!(
3775 !turn(3).is_file(),
3776 "the same stalled task lingering must not call the conductor every cycle"
3777 );
3778 }
3779
3780 fn rehold(queue: &Queue, questions: &Questions, id: &str, note: &str) {
3781 apply(
3782 queue,
3783 questions,
3784 &Verdict {
3785 decisions: vec![Decision {
3786 id: id.to_owned(),
3787 reason: Some(note.to_owned()),
3788 recovery: Some(Recovery::Hold),
3789 ..Decision::default()
3790 }],
3791 },
3792 )
3793 .unwrap();
3794 }
3795
3796 #[test]
3797 fn reholding_with_an_identical_note_changes_nothing() {
3798 let dir = tempdir().unwrap();
3799 let queue = Queue::at(dir.path().join("queue"));
3800 let questions = Questions::at(dir.path().join("questions"));
3801 let mut t = task("held");
3802 t.hold_machine(Some("waiting on a human".to_owned()));
3803 queue.put(&mut t).unwrap();
3804
3805 rehold(&queue, &questions, &t.id, "owner said keep it held");
3806 let first = queue.get(&t.id).unwrap();
3807 let rev = queue.revision();
3808 for _ in 0..5 {
3809 rehold(&queue, &questions, &t.id, "owner said keep it held");
3810 }
3811 let after = queue.get(&t.id).unwrap();
3812 assert_eq!(after.hold_reason, first.hold_reason);
3813 assert_eq!(after.updated_at, first.updated_at);
3814 assert_eq!(queue.revision(), rev, "nothing was written");
3815 }
3816
3817 #[test]
3818 fn reholding_with_different_notes_keeps_one_previously_level() {
3819 let dir = tempdir().unwrap();
3820 let queue = Queue::at(dir.path().join("queue"));
3821 let questions = Questions::at(dir.path().join("questions"));
3822 let mut t = task("held");
3823 t.hold_machine(Some("original".to_owned()));
3824 queue.put(&mut t).unwrap();
3825
3826 for i in 0..20 {
3827 rehold(&queue, &questions, &t.id, &format!("note {}", i % 2));
3828 }
3829 let reason = queue.get(&t.id).unwrap().hold_reason.unwrap();
3830 assert_eq!(reason.matches("(previously:").count(), 1, "{reason}");
3831 assert!(reason.starts_with("note "), "the new note leads: {reason}");
3832 }
3833
3834 #[test]
3835 fn an_already_nested_reason_is_matched_by_its_outermost_note() {
3836 let mut t = task("deep");
3837 let nested = "same\n\n(previously: same\n\n(previously: same))";
3838 t.hold_machine(Some(nested.to_owned()));
3839 let d = Decision {
3840 id: t.id.clone(),
3841 reason: Some("same".to_owned()),
3842 ..Decision::default()
3843 };
3844 assert_eq!(reaffirmed_hold_reason(&t, &d), None);
3845 let d2 = Decision {
3846 reason: Some("other".to_owned()),
3847 ..d
3848 };
3849 assert_eq!(
3850 reaffirmed_hold_reason(&t, &d2).as_deref(),
3851 Some("other\n\n(previously: same)")
3852 );
3853 }
3854
3855 #[tokio::test]
3856 async fn a_repeated_hold_decision_settles_instead_of_looping() {
3857 let dir = tempdir().unwrap();
3858 let queue = Queue::at(dir.path().join("queue"));
3859 let questions = Questions::at(dir.path().join("questions"));
3860 let reply = r#"{"decisions":[{"id":"ID","reason":"keep held","recovery":"hold"}]}"#;
3861 let mut t = task("held");
3862 t.hold_machine(Some("first".to_owned()));
3863 queue.put(&mut t).unwrap();
3864 let cfg = config(mock_agent(
3865 dir.path(),
3866 REPLY,
3867 env(&reply.replace("ID", &t.id)),
3868 ));
3869 let mut conductor = Conductor::new();
3870 for _ in 0..2 {
3872 let held = queue.get(&t.id).unwrap();
3873 conductor
3874 .maybe_run(
3875 &cfg,
3876 dir.path(),
3877 &queue,
3878 &questions,
3879 dir.path(),
3880 &[],
3881 &[],
3882 &[held],
3883 2,
3884 )
3885 .await;
3886 }
3887 let held = queue.get(&t.id).unwrap();
3888 assert!(
3889 held.hold_reason
3890 .as_deref()
3891 .unwrap()
3892 .starts_with("keep held")
3893 );
3894 assert!(
3895 !conductor.worth_a_look(&queue, &[], &[held]),
3896 "an unchanged held task must stop being reconsidered"
3897 );
3898 }
3899
3900 #[tokio::test]
3901 async fn alternating_wording_does_not_keep_a_held_task_in_the_loop() {
3902 let dir = tempdir().unwrap();
3903 let queue = Queue::at(dir.path().join("queue"));
3904 let questions = Questions::at(dir.path().join("questions"));
3905 let mut t = task("held");
3906 t.hold_machine(Some("first".to_owned()));
3907 queue.put(&mut t).unwrap();
3908 let reply = |note: &str| {
3909 format!(
3910 r#"{{"decisions":[{{"id":"{}","reason":"{note}","recovery":"hold"}}]}}"#,
3911 t.id
3912 )
3913 };
3914 let cfg_a = config(mock_agent(dir.path(), REPLY, env(&reply("keep held"))));
3915 let cfg_b = config(mock_agent(dir.path(), REPLY, env(&reply("leave held"))));
3916 let mut conductor = Conductor::new();
3917 let mut writes = 0;
3918 for i in 0..6 {
3919 let held = queue.get(&t.id).unwrap();
3920 let before = queue.revision();
3921 conductor
3922 .maybe_run(
3923 if i % 2 == 0 { &cfg_a } else { &cfg_b },
3924 dir.path(),
3925 &queue,
3926 &questions,
3927 dir.path(),
3928 &[],
3929 &[],
3930 &[held],
3931 2,
3932 )
3933 .await;
3934 if queue.revision() != before {
3935 writes += 1;
3936 }
3937 }
3938 assert!(writes <= 2, "the loop must settle, saw {writes} writes");
3939 let mut held = queue.get(&t.id).unwrap();
3940 held.instruction.push_str(" (edited)");
3941 queue.put(&mut held).unwrap();
3942 let held = queue.get(&t.id).unwrap();
3943 assert!(conductor.worth_a_look(&queue, &[], &[held]));
3944 }
3945
3946 #[test]
3947 fn worth_a_look_is_config_free_and_matches_maybe_runs_own_gate() {
3948 let dir = tempdir().unwrap();
3949 let queue = Queue::at(dir.path().join("queue"));
3950 let mut t = task("t");
3951 queue.put(&mut t).unwrap();
3952
3953 let mut conductor = Conductor::new();
3954 assert!(
3955 conductor.worth_a_look(&queue, &[], &[]),
3956 "a conductor that has never run has something to look at"
3957 );
3958
3959 conductor.last_seen = Some(conductor.snapshot(&queue, &[], &[]));
3960 assert!(
3961 !conductor.worth_a_look(&queue, &[], &[]),
3962 "nothing changed and nothing is stalled or finished"
3963 );
3964 assert!(
3965 conductor.worth_a_look(&queue, &[t.clone()], &[]),
3966 "a stalled task is worth a look even at the same revision"
3967 );
3968 assert!(
3969 conductor.worth_a_look(&queue, &[], &[t.clone()]),
3970 "a finished task is worth a look even at the same revision"
3971 );
3972 }
3973
3974 #[tokio::test]
3975 async fn the_conduct_path_never_calls_ask_and_wait() {
3976 let dir = tempdir().unwrap();
3982 let queue = Queue::at(dir.path().join("queue"));
3983 let questions = Questions::at(dir.path().join("questions"));
3984 let mut t = task("asks without blocking");
3985 queue.put(&mut t).unwrap();
3986
3987 apply(
3988 &queue,
3989 &questions,
3990 &Verdict {
3991 decisions: vec![Decision {
3992 id: t.id.clone(),
3993 question: Some("ok?".to_owned()),
3994 ..Decision::default()
3995 }],
3996 },
3997 )
3998 .unwrap();
3999 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
4001 }
4002
4003 #[test]
4004 fn a_pinned_resume_is_not_held_or_requeued_by_the_conductor() {
4005 let mut t = Task::new("t".into(), "t".into(), PathBuf::new(), Source::Human);
4006 t.resume_override = Some(crate::queue::OperatorResume {
4007 question_id: "q".into(),
4008 at: jiff::Timestamp::now(),
4009 conductor_rehold: None,
4010 forced: false,
4011 pinned_run: Some("run-1".into()),
4012 });
4013 assert!(pinned_resume(&t));
4014 assert!(!may_hold(&mut t, "waiting for magi resume"));
4015 assert!(
4016 t.resume_override
4017 .as_ref()
4018 .unwrap()
4019 .conductor_rehold
4020 .is_none(),
4021 "a refused hold is not recorded as an override"
4022 );
4023 t.resume_override = None;
4024 assert!(!pinned_resume(&t));
4025 assert!(may_hold(&mut t, "no override, so a hold is allowed"));
4026 }
4027
4028 #[test]
4029 fn a_pinned_resume_is_not_blocked_by_a_conductor_question_or_dependency() {
4030 let dir = tempdir().unwrap();
4031 let queue = Queue::at(dir.path().join("queue"));
4032 let questions = Questions::at(dir.path().join("questions"));
4033 let mut t = task("resume me");
4034 t.resume_override = Some(crate::queue::OperatorResume {
4035 question_id: "q".into(),
4036 at: jiff::Timestamp::now(),
4037 conductor_rehold: None,
4038 forced: true,
4039 pinned_run: Some("run-1".into()),
4040 });
4041 queue.put(&mut t).unwrap();
4042
4043 apply(
4044 &queue,
4045 &questions,
4046 &Verdict {
4047 decisions: vec![
4048 Decision {
4049 id: t.id.clone(),
4050 question: Some("really?".to_owned()),
4051 ..Decision::default()
4052 },
4053 Decision {
4054 id: t.id.clone(),
4055 blocked_by: vec!["other".to_owned()],
4056 ..Decision::default()
4057 },
4058 ],
4059 },
4060 )
4061 .unwrap();
4062
4063 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
4064 assert!(questions.list().is_empty());
4065 }
4066}