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 fetched_base: None,
1390 cwd: repo,
1391 prompt: &body,
1392 timeout: TURN_TIMEOUT,
1393 allow_write: false,
1396 unsandboxed: false,
1397 sessions: cfg.graph.sessions,
1398 artifacts: &artifacts,
1399 stem: &stem,
1400 run: NODE,
1401 node: NODE,
1402 cache_dir: cache_dir.as_deref(),
1403 attachments: &[],
1404 writable: &[],
1405 };
1406 let out = agent::invoke(spec, seat, &inv).await;
1407 if let Ok(body) = serde_json::to_string(&*seat) {
1410 let path = seat_path(home);
1411 if let Some(dir) = path.parent() {
1412 let _ = std::fs::create_dir_all(dir);
1413 }
1414 let _ = std::fs::write(path, body);
1415 }
1416 let advance = agent::chain_advances(&out);
1417 result = match out {
1418 Err(e) => Err(e.context("invoking the conductor")),
1419 Ok(out) if advance => Err(anyhow::anyhow!(
1420 "no usable reply ({})",
1421 crate::notices::turn_status(
1422 out.exit_code,
1423 out.timed_out,
1424 out.quota_exhausted()
1425 )
1426 )),
1427 Ok(out) => verdict::extract_json(&out.text)
1428 .context("the conductor's reply could not be parsed"),
1429 };
1430 if result.is_ok() {
1431 break;
1432 }
1433 if chain.len() > 1 {
1434 tracing::warn!("conductor: `{}` failed, trying the next agent", spec.id);
1435 }
1436 }
1437 drop(busy);
1438 let mut verdict = result?;
1439 attach_facts(cfg, repo, queue, &mut verdict).await;
1440 for d in &verdict.decisions {
1441 let snapshot = queued
1442 .iter()
1443 .chain(stalled)
1444 .chain(finished)
1445 .find(|t| t.id == d.id);
1446 if let Some(snapshot) = snapshot {
1447 if let Err(e) = apply_one(queue, questions, d, Some(snapshot)) {
1448 tracing::warn!("conductor decision for task {}: {e:#}", d.id);
1449 }
1450 }
1451 }
1452 Ok(())
1453 }
1454}
1455
1456#[cfg(test)]
1457mod tests {
1458 use std::collections::BTreeMap;
1459
1460 use tempfile::tempdir;
1461
1462 use super::*;
1463 use crate::ask::{Answer, QuestionStatus};
1464 use crate::config::{AgentKind, AgentSpec, Graph};
1465 use crate::queue::Source;
1466
1467 fn mock_agent(dir: &Path, script: &str, env: BTreeMap<String, String>) -> AgentSpec {
1468 let path = dir.join("mock-conduct-agent.sh");
1469 std::fs::write(&path, script).expect("write mock");
1470 AgentSpec {
1471 id: "mock".to_owned(),
1472 kind: AgentKind::Command,
1473 model: None,
1474 command: vec!["sh".to_owned(), path.to_string_lossy().into_owned()],
1475 extra_args: Vec::new(),
1476 env,
1477 prompt_delivery: None,
1478 }
1479 }
1480
1481 fn config(spec: AgentSpec) -> Config {
1482 Config {
1483 agents: vec![spec],
1484 graph: Graph {
1485 language: "en".to_owned(),
1486 ..Graph::default()
1487 },
1488 ..Config::default()
1489 }
1490 }
1491
1492 fn task(title: &str) -> Task {
1493 Task::new(
1494 title.to_owned(),
1495 format!("do {title}"),
1496 std::path::PathBuf::from("."),
1497 Source::Human,
1498 )
1499 }
1500
1501 #[test]
1502 fn delivery_bookkeeping_does_not_restart_conductor_deliberation() {
1503 let mut t = task("waiting");
1504 t.hold_machine(Some("waiting for recovery".into()));
1505 let before = input_fingerprint(&t);
1506 let snapshot = decision_input(&t);
1507 t.chat_notice = Some(crate::queue::ChatNotice {
1508 key: t.chat_notice_key().unwrap(),
1509 at: jiff::Timestamp::now(),
1510 outcome: crate::queue::ChatNoticeOutcome::Posted,
1511 });
1512 t.chat_notices.push(t.chat_notice_key().unwrap());
1513 t.updated_at = jiff::Timestamp::now();
1514 assert_eq!(before, input_fingerprint(&t));
1515 assert_eq!(snapshot, decision_input(&t));
1516 t.hold_reason = Some("recovery remains under consideration".into());
1517 assert_eq!(before, input_fingerprint(&t));
1518 t.record_answer("a different question".into(), "a new decision".into());
1519 assert_ne!(before, input_fingerprint(&t));
1520 }
1521
1522 const BROKEN: &str = "#!/bin/sh\ncat >/dev/null\nexit 3\n";
1523 const GARBAGE: &str = "#!/bin/sh\ncat >/dev/null\nprintf 'not json at all\\n'\n";
1524
1525 fn env(reply: &str) -> BTreeMap<String, String> {
1526 BTreeMap::from([("MOCK_REPLY".to_owned(), reply.to_owned())])
1527 }
1528
1529 const REPLY: &str = "#!/bin/sh\ncat >/dev/null\nprintf '%s\\n' \"$MOCK_REPLY\"\n";
1530
1531 fn init_repo_with_branch(dir: &Path, branch: &str) {
1535 use crate::proc::Quiet as _;
1536 let run = |args: &[&str]| {
1537 let out = std::process::Command::new("git")
1538 .args(args)
1539 .current_dir(dir)
1540 .quiet()
1541 .output()
1542 .expect("spawn git");
1543 assert!(
1544 out.status.success(),
1545 "git {args:?} failed: {}",
1546 String::from_utf8_lossy(&out.stderr)
1547 );
1548 };
1549 run(&["init", "-b", "main"]);
1550 run(&["config", "user.name", "magi test"]);
1551 run(&["config", "user.email", "magi@example.com"]);
1552 std::fs::write(dir.join("README.md"), "# fixture\n").unwrap();
1553 run(&["add", "-A"]);
1554 run(&["commit", "-m", "init"]);
1555 run(&["checkout", "-b", branch]);
1556 std::fs::write(dir.join("change.txt"), "x\n").unwrap();
1557 run(&["add", "-A"]);
1558 run(&["commit", "-m", "candidate work"]);
1559 }
1560
1561 fn review_round_with_finding(
1562 round: usize,
1563 finding_id: &str,
1564 title: &str,
1565 addressed: &[&str],
1566 rejected: &[(&str, &str)],
1567 ) -> crate::run::ReviewRound {
1568 crate::run::ReviewRound {
1569 round,
1570 head: "deadbeef".to_owned(),
1571 verified_head: None,
1572 verified_at: None,
1573 reviews: vec![crate::run::ReviewRecord {
1574 attempts: 0,
1575 reviewer: 1,
1576 agent: "mock".to_owned(),
1577 summary: String::new(),
1578 findings: vec![crate::verdict::Finding {
1579 id: finding_id.to_owned(),
1580 severity: crate::verdict::Severity::Major,
1581 file: None,
1582 line: None,
1583 title: title.to_owned(),
1584 detail: String::new(),
1585 }],
1586 vote: None,
1587 failed: None,
1588 duration_ms: 0,
1589 }],
1590 e2e: Vec::new(),
1591 verify_retried: false,
1592 e2e_deferred: false,
1593 e2e_defer_reason: None,
1594 fix: Some(crate::run::FixRecord {
1595 agent: "mock".to_owned(),
1596 addressed: addressed.iter().map(|s| (*s).to_owned()).collect(),
1597 rejected: rejected
1598 .iter()
1599 .map(|(id, why)| crate::verdict::Rejection {
1600 id: (*id).to_owned(),
1601 why: (*why).to_owned(),
1602 })
1603 .collect(),
1604 notes: String::new(),
1605 committed: false,
1606 failed: None,
1607 duration_ms: 0,
1608 continuation: None,
1609 }),
1610 blocking: 1,
1611 answered: 1,
1612 expected: 1,
1613 clean: false,
1614 progressed: true,
1615 vote_split: false,
1616 reconsideration: Vec::new(),
1617 verdict: None,
1618 }
1619 }
1620
1621 #[test]
1622 fn explicit_resumption_supersedes_history_and_rejects_stale_decisions() {
1623 crate::run::pin_test_home();
1624 let dir = tempdir().unwrap();
1625 let queue = Queue::at(dir.path().join("queue"));
1626 let questions = Questions::at(dir.path().join("questions"));
1627 let mut t = task("recover");
1628 t.answers.push(crate::queue::AnsweredQuestion {
1629 question: "Inspect remote first?".into(),
1630 answer: "Inspect, then await resumption instructions".into(),
1631 });
1632 t.hold_machine(Some("waiting for remote inspection".into()));
1633 queue.put(&mut t).unwrap();
1634 let snapshot = queue.get(&t.id).unwrap();
1635 t.edit(
1636 "recover".into(),
1637 "Reuse the measured PR head; fix Clippy; review".into(),
1638 )
1639 .unwrap();
1640 t.release_operator("cli", None);
1641 queue.put(&mut t).unwrap();
1642 let approval = t.resumption.clone();
1643 let d = Decision {
1644 id: t.id.clone(),
1645 recovery: Some(Recovery::Hold),
1646 reason: Some("remote inspection still required".into()),
1647 ..Decision::default()
1648 };
1649 apply_one(&queue, &questions, &d, Some(&snapshot)).unwrap();
1650 let stale_question = Decision {
1651 question: Some("Inspect remote?".into()),
1652 ..d.clone()
1653 };
1654 apply_one(&queue, &questions, &stale_question, Some(&snapshot)).unwrap();
1655 assert!(questions.list().is_empty());
1656 for reason in [
1657 "waiting for remote inspection",
1658 "inspection has not been confirmed",
1659 ] {
1660 let repeated = Decision {
1661 reason: Some(reason.into()),
1662 question: Some("How should we proceed?".into()),
1663 ..d.clone()
1664 };
1665 apply(
1666 &queue,
1667 &questions,
1668 &Verdict {
1669 decisions: vec![repeated],
1670 },
1671 )
1672 .unwrap();
1673 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
1674 }
1675 assert!(
1676 questions.list().is_empty(),
1677 "a rejected proposal registers no question"
1678 );
1679 let notice = crate::notices::Notices::open()
1680 .get(&crate::notices::id_of(&format!(
1681 "conductor-resumption:{}",
1682 t.id
1683 )))
1684 .unwrap();
1685 assert!(!notice.message.contains("How should we proceed?"));
1686 assert!(!notice.message.contains("Some("));
1687 assert!(notice.message.contains("No reply to this notice is needed"));
1688 let reloaded = Queue::at(dir.path().join("queue")).get(&t.id).unwrap();
1689 assert_eq!(reloaded.resumption, approval);
1690 assert_eq!(reloaded.answers, t.answers);
1691 let v = view(&reloaded, 3);
1692 assert!(v.operator_resume.unwrap().contains("superseded"));
1693 let mut dep = task("new prerequisite");
1694 dep.hold_machine(Some("new authentication failure".into()));
1695 queue.put(&mut dep).unwrap();
1696 let new_blocker = Decision {
1697 blocked_by: vec![dep.id.clone()],
1698 evidence: vec![dep.id.clone()],
1699 recovery: None,
1701 reason: Some("new prerequisite failed".into()),
1702 ..d.clone()
1703 };
1704 apply(
1705 &queue,
1706 &questions,
1707 &Verdict {
1708 decisions: vec![new_blocker.clone()],
1709 },
1710 )
1711 .unwrap();
1712 let mut after = queue.get(&t.id).unwrap();
1713 assert_eq!(after.status, TaskStatus::Blocked);
1714 after.release();
1717 queue.put(&mut after).unwrap();
1718 apply(
1719 &queue,
1720 &questions,
1721 &Verdict {
1722 decisions: vec![new_blocker],
1723 },
1724 )
1725 .unwrap();
1726 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
1727 after.start("new-run".into());
1728 assert_eq!(after.resumption.as_ref().unwrap().generation, 1);
1729 after.hold_manual(Some("operator says wait".into()));
1730 queue.put(&mut after).unwrap();
1731 apply(&queue, &questions, &Verdict { decisions: vec![d] }).unwrap();
1732 assert!(queue.get(&t.id).unwrap().operator_held());
1733 }
1734
1735 #[test]
1736 fn newly_blocked_dependency_is_material_evidence_after_approval() {
1737 let dir = tempdir().unwrap();
1738 let queue = Queue::at(dir.path().join("queue"));
1739 let questions = Questions::at(dir.path().join("questions"));
1740 let mut dep = task("old queued dependency");
1741 queue.put(&mut dep).unwrap();
1742 let mut t = task("approved task");
1743 t.release_operator("test", None);
1744 queue.put(&mut t).unwrap();
1745 let mut q = Question::new(
1746 dep.id.clone(),
1747 "check".into(),
1748 "check".into(),
1749 "New dependency approval".into(),
1750 String::new(),
1751 Vec::new(),
1752 );
1753 questions.put(&mut q).unwrap();
1754 dep.block(vec![q.id.clone()], Some("new decision needed".into()));
1755 let changed = dep.blocked_at;
1756 queue.put(&mut dep).unwrap();
1757 dep.block(vec![q.id], Some("same decision paraphrased".into()));
1758 assert_eq!(
1759 dep.blocked_at, changed,
1760 "prose is not new blocking evidence"
1761 );
1762 queue.put(&mut dep).unwrap();
1763 let d = Decision {
1764 id: t.id.clone(),
1765 blocked_by: vec![dep.id.clone()],
1766 evidence: vec![dep.id],
1767 ..Decision::default()
1768 };
1769 assert_eq!(new_blocking_evidence(&queue, &questions, &t, &d).len(), 1);
1770 apply_one(&queue, &questions, &d, None).unwrap();
1771 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
1772 }
1773
1774 #[test]
1775 fn resumed_run_evidence_uses_approval_time_not_run_list_offsets() {
1776 crate::run::pin_test_home();
1777 let dir = tempdir().unwrap();
1778 let queue = Queue::at(dir.path().join("queue"));
1779 let questions = Questions::at(dir.path().join("questions"));
1780 let mut t = task("resume evidence");
1781 let mut run = RunState::new(
1782 t.repo.clone(),
1783 "main".into(),
1784 "base".into(),
1785 "work".into(),
1786 crate::config::Config::default(),
1787 );
1788 run.begin_pass();
1789 run.status = crate::run::RunStatus::Failed;
1790 run.save().unwrap();
1791 t.start(run.id.clone());
1792 t.runs.push(run.id.clone());
1794 t.release_operator("cli", None);
1795 let approval = t.resumption.as_ref().unwrap().at;
1796 let decision = Decision {
1797 evidence: vec![run.id.clone()],
1798 ..Decision::default()
1799 };
1800 assert!(new_blocking_evidence(&queue, &questions, &t, &decision).is_empty());
1801 t.start(run.id.clone());
1802 assert_eq!(t.runs.len(), 1);
1803 run.begin_pass();
1804 run.save().unwrap();
1805 assert!(run.passes.last().unwrap().started_at > approval);
1806 let evidence = new_blocking_evidence(&queue, &questions, &t, &decision);
1807 assert_eq!(evidence.len(), 1);
1808 t.resumption.as_mut().unwrap().blocking_evidence = evidence;
1809 assert!(new_blocking_evidence(&queue, &questions, &t, &decision).is_empty());
1810 run.begin_pass();
1811 run.save().unwrap();
1812 assert_eq!(
1813 new_blocking_evidence(&queue, &questions, &t, &decision).len(),
1814 1
1815 );
1816
1817 let mut q = Question::new(
1818 run.id.clone(),
1819 "review".into(),
1820 "check".into(),
1821 "New failure".into(),
1822 String::new(),
1823 Vec::new(),
1824 );
1825 questions.put(&mut q).unwrap();
1826 let decision = Decision {
1827 evidence: vec![q.id.clone()],
1828 ..Decision::default()
1829 };
1830 assert_eq!(
1831 new_blocking_evidence(&queue, &questions, &t, &decision).len(),
1832 1
1833 );
1834 q.asked_at = approval;
1835 questions.put(&mut q).unwrap();
1836 assert!(new_blocking_evidence(&queue, &questions, &t, &decision).is_empty());
1837 q.asked_at = jiff::Timestamp::now();
1838 q.run = "unrelated".into();
1839 questions.put(&mut q).unwrap();
1840 assert!(new_blocking_evidence(&queue, &questions, &t, &decision).is_empty());
1841
1842 let mut fresh = RunState::new(
1843 t.repo.clone(),
1844 "main".into(),
1845 "base".into(),
1846 "fresh work".into(),
1847 crate::config::Config::default(),
1848 );
1849 fresh.status = crate::run::RunStatus::Failed;
1850 fresh.save().unwrap();
1851 t.start(fresh.id.clone());
1852 let decision = Decision {
1853 evidence: vec![fresh.id.clone()],
1854 ..Decision::default()
1855 };
1856 assert_eq!(
1857 new_blocking_evidence(&queue, &questions, &t, &decision).len(),
1858 1
1859 );
1860 }
1861
1862 #[test]
1863 fn outcome_for_carries_every_rounds_findings_and_the_branch_head() {
1864 crate::run::pin_test_home();
1865 let dir = tempdir().unwrap();
1866 let default_repo = dir.path().join("default");
1867 let task_repo = dir.path().join("task");
1868 std::fs::create_dir_all(&default_repo).unwrap();
1869 std::fs::create_dir_all(&task_repo).unwrap();
1870 init_repo_with_branch(&default_repo, "other-branch");
1871 init_repo_with_branch(&task_repo, "magi/f00d/A");
1872
1873 let mut config = Config::default();
1874 config.graph.review_rounds = 6;
1875 let mut state = crate::run::RunState::new(
1876 task_repo.clone(),
1877 "main".to_owned(),
1878 "deadbeef".to_owned(),
1879 "task".to_owned(),
1880 config,
1881 );
1882 state.status = crate::run::RunStatus::Blocked;
1883 state.candidates.push(crate::run::Candidate {
1884 index: 0,
1885 label: 'A',
1886 agent: "mock".to_owned(),
1887 branch: "magi/f00d/A".to_owned(),
1888 worktree: task_repo.clone(),
1889 summary: String::new(),
1890 stat: String::new(),
1891 files: 1,
1892 commits: 1,
1893 empty: false,
1894 failed: None,
1895 verified_noop: None,
1896 duration_ms: 0,
1897 folded: false,
1898 });
1899 state.tally = Some(crate::run::Tally {
1900 first_choice: std::collections::BTreeMap::new(),
1901 borda: std::collections::BTreeMap::new(),
1902 winner: 'A',
1903 rankings: 0,
1904 unanimous_initial: false,
1905 deliberated: false,
1906 changed_votes: 0,
1907 unanimous_final: false,
1908 tie_break: None,
1909 judges: 0,
1910 present: 0,
1911 quorum: 0,
1912 met_quorum: true,
1913 uncontested: Some("solo".to_owned()),
1914 });
1915 state.reviews = vec![
1916 review_round_with_finding(
1917 1,
1918 "R1-1-2",
1919 "answer content is dropped",
1920 &[],
1921 &[("R1-1-2", "the id leaving blocked_by is enough")],
1922 ),
1923 review_round_with_finding(2, "R2-1-3", "answer content is still dropped", &[], &[]),
1924 ];
1925 state.save().unwrap();
1926
1927 let mut t = task("outcome test");
1928 t.repo = task_repo;
1929 t.runs.push(state.id.clone());
1930
1931 let finished = tokio_test_block_on(finished_view(&t, &default_repo, 2));
1932 let outcome = finished.outcome;
1933
1934 assert!(outcome.unreadable.is_none());
1935 assert_eq!(outcome.run_status.as_deref(), Some("blocked"));
1936 assert_eq!(outcome.rounds_used, 2);
1937 assert_eq!(outcome.rounds_max, 6);
1938 assert_eq!(outcome.rounds.len(), 2);
1939 assert_eq!(outcome.rounds[0].findings[0].id, "R1-1-2");
1940 assert_eq!(outcome.rounds[0].rejected[0].id, "R1-1-2");
1941 assert!(outcome.rounds[1].addressed.is_empty());
1942 assert!(outcome.rounds[1].rejected.is_empty());
1943 assert_eq!(outcome.branch.as_deref(), Some("magi/f00d/A"));
1944 assert!(
1945 outcome.branch_head.is_some(),
1946 "a real branch must resolve a head commit: {outcome:?}"
1947 );
1948 }
1949
1950 fn tokio_test_block_on<F: std::future::Future>(f: F) -> F::Output {
1954 tokio::runtime::Builder::new_current_thread()
1955 .enable_all()
1956 .build()
1957 .unwrap()
1958 .block_on(f)
1959 }
1960
1961 #[test]
1962 fn view_resolves_task_attempt_limit_before_daemon_default() {
1963 let mut t = task("budget");
1964 assert_eq!(view(&t, 7).max_attempts, 7);
1965 t.change_attempt_limit(std::num::NonZeroUsize::new(3))
1966 .unwrap();
1967 assert_eq!(view(&t, 7).max_attempts, 3);
1968 t.change_attempt_limit(None).unwrap();
1969 assert_eq!(view(&t, 7).max_attempts, 7);
1970 }
1971
1972 #[test]
1973 fn view_carries_a_tasks_recorded_answers_into_the_conductor_prompt_input() {
1974 let mut t = task("answered");
1975 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
1976 let v = view(&t, 2);
1977 assert_eq!(v.answers.len(), 1);
1978 assert_eq!(v.answers[0].question, "Which backend?");
1979 assert_eq!(v.answers[0].answer, "SQLite");
1980 }
1981
1982 #[tokio::test]
1983 async fn dependency_resolution_rechecks_questions_in_the_production_conductor_path() {
1984 for held in [false, true] {
1985 for reference in ["ca5b", "20261013-193611-ca5b"] {
1986 for question in [false, true] {
1987 let dir = tempdir().unwrap();
1988 let queue = Queue::at(dir.path().join("queue"));
1989 let questions = Questions::at(dir.path().join("questions"));
1990 let mut dep = task("prerequisite");
1991 dep.id = "20261013-193611-ca5b".into();
1992 dep.start("existing-run".into());
1993 queue.put(&mut dep).unwrap();
1994 let mut waiting = task("waiting");
1995 if held {
1996 waiting.hold_machine(Some("dependency could not be located".into()));
1997 }
1998 queue.put(&mut waiting).unwrap();
1999 let missing_reference = if reference == "ca5b" {
2000 dep.id.as_str()
2001 } else {
2002 "ca5b"
2003 };
2004 let reply = serde_json::json!({"decisions": [{
2005 "id": waiting.id, "blocked_by": [reference],
2006 "missing_dependencies": [missing_reference],
2007 "question": question.then_some("ca5b is missing; where is its replacement?"),
2008 "recovery": (!question).then_some("hold"),
2009 "reason": "ca5b is missing"
2010 }]}).to_string();
2011 let cfg = config(mock_agent(dir.path(), REPLY, env(&reply)));
2012 let (queued, finished) = if held {
2013 (vec![], vec![waiting.clone()])
2014 } else {
2015 (vec![waiting.clone()], vec![])
2016 };
2017 Conductor::new()
2018 .run_once(
2019 &cfg,
2020 dir.path(),
2021 &queue,
2022 &questions,
2023 dir.path(),
2024 &queued,
2025 &[],
2026 &finished,
2027 2,
2028 )
2029 .await
2030 .unwrap();
2031 let after = queue.get(&waiting.id).unwrap();
2032 assert_eq!(after.status, TaskStatus::Blocked);
2033 assert_eq!(after.blocked_by, [dep.id]);
2034 assert_eq!(after.blocked_from, Some(waiting.status));
2035 assert!(!after.block_reason.unwrap().contains("missing"));
2036 assert!(questions.list().is_empty());
2037 assert_eq!(after.instruction, waiting.instruction);
2038 }
2039 }
2040 }
2041 }
2042
2043 #[tokio::test]
2044 async fn dependency_resolution_inconclusive_missing_only_decisions_keep_waiting() {
2045 for held in [false, true] {
2046 for unknown in [false, true] {
2047 for question in [false, true] {
2048 let dir = tempdir().unwrap();
2049 let queue = Queue::at(dir.path().join("queue"));
2050 let questions = Questions::at(dir.path().join("questions"));
2051 let mut dep = task("running prerequisite");
2052 dep.id = "20261013-193611-ca5b".into();
2053 dep.start("existing-run".into());
2054 queue.put(&mut dep).unwrap();
2055 let reference = if unknown {
2056 std::fs::write(questions.root(), "not a directory").unwrap();
2059 dep.id.clone()
2060 } else {
2061 let mut other = task("another prerequisite");
2062 other.id = "20261014-193611-ca5b".into();
2063 queue.put(&mut other).unwrap();
2064 "ca5b".to_owned()
2065 };
2066 assert_eq!(
2067 crate::queue::dependency(&queue, &questions, &reference),
2068 if unknown {
2069 crate::queue::Dependency::Unknown
2070 } else {
2071 crate::queue::Dependency::Ambiguous
2072 }
2073 );
2074 let mut waiting = task("waiting");
2075 if held {
2076 waiting.hold_machine(Some("dependency could not be located".into()));
2077 }
2078 queue.put(&mut waiting).unwrap();
2079 let reply = serde_json::json!({"decisions": [{
2080 "id": waiting.id, "blocked_by": [reference],
2081 "missing_dependencies": [reference],
2082 "question": question.then_some("ca5b is missing"),
2083 "recovery": (!question).then_some("hold"),
2084 "reason": "ca5b is missing"
2085 }]})
2086 .to_string();
2087 let cfg = config(mock_agent(dir.path(), REPLY, env(&reply)));
2088 let (queued, finished) = if held {
2089 (vec![], vec![waiting.clone()])
2090 } else {
2091 (vec![waiting.clone()], vec![])
2092 };
2093 Conductor::new()
2094 .run_once(
2095 &cfg,
2096 dir.path(),
2097 &queue,
2098 &questions,
2099 dir.path(),
2100 &queued,
2101 &[],
2102 &finished,
2103 2,
2104 )
2105 .await
2106 .unwrap();
2107 let after = queue.get(&waiting.id).unwrap();
2108 assert_eq!(after.status, TaskStatus::Blocked);
2109 assert_eq!(after.blocked_by, [reference]);
2110 assert_eq!(after.blocked_from, Some(waiting.status));
2111 assert!(!after.block_reason.unwrap().contains("missing"));
2112 assert_eq!(after.instruction, waiting.instruction);
2113 if unknown {
2114 assert!(questions.root().is_file());
2115 } else {
2116 assert!(questions.list().is_empty());
2117 }
2118 }
2119 }
2120 }
2121 }
2122
2123 #[tokio::test]
2124 async fn dependency_resolution_unverifiable_alias_decisions_are_discarded() {
2125 for held in [false, true] {
2126 for unknown in [false, true] {
2127 for question in [false, true] {
2128 for short_blocker in [false, true] {
2129 let dir = tempdir().unwrap();
2130 let queue = Queue::at(dir.path().join("queue"));
2131 let questions = Questions::at(dir.path().join("questions"));
2132 let mut dep = task("running prerequisite");
2133 dep.id = "20261013-193611-ca5b".into();
2134 dep.start("existing-run".into());
2135 queue.put(&mut dep).unwrap();
2136 if unknown {
2137 std::fs::write(questions.root(), "not a directory").unwrap();
2138 } else {
2139 let mut other = task("another prerequisite");
2140 other.id = "20261014-193611-ca5b".into();
2141 queue.put(&mut other).unwrap();
2142 }
2143 let (blocker, missing) = if short_blocker {
2144 ("ca5b", dep.id.as_str())
2145 } else {
2146 (dep.id.as_str(), "ca5b")
2147 };
2148 let mut waiting = task("waiting");
2149 if held {
2150 waiting.hold_machine(Some("dependency could not be located".into()));
2151 }
2152 queue.put(&mut waiting).unwrap();
2153 let reply = serde_json::json!({"decisions": [{
2154 "id": waiting.id, "blocked_by": [blocker],
2155 "missing_dependencies": [missing],
2156 "question": question.then_some("ca5b is missing"),
2157 "recovery": (!question).then_some("hold"),
2158 "reason": "ca5b is missing"
2159 }]})
2160 .to_string();
2161 let cfg = config(mock_agent(dir.path(), REPLY, env(&reply)));
2162 let (queued, finished) = if held {
2163 (vec![], vec![waiting.clone()])
2164 } else {
2165 (vec![waiting.clone()], vec![])
2166 };
2167 Conductor::new()
2168 .run_once(
2169 &cfg,
2170 dir.path(),
2171 &queue,
2172 &questions,
2173 dir.path(),
2174 &queued,
2175 &[],
2176 &finished,
2177 2,
2178 )
2179 .await
2180 .unwrap();
2181 assert_eq!(
2182 serde_json::to_value(queue.get(&waiting.id).unwrap()).unwrap(),
2183 serde_json::to_value(&waiting).unwrap(),
2184 "unverifiable aliases must leave the entire task unchanged"
2185 );
2186 if unknown {
2187 assert!(questions.root().is_file());
2188 } else {
2189 assert!(questions.list().is_empty());
2190 }
2191 }
2192 }
2193 }
2194 }
2195 }
2196
2197 #[tokio::test]
2198 async fn dependency_resolution_genuine_missing_reference_still_asks() {
2199 let dir = tempdir().unwrap();
2200 let queue = Queue::at(dir.path().join("queue"));
2201 let questions = Questions::at(dir.path().join("questions"));
2202 let mut waiting = task("missing prerequisite");
2203 queue.put(&mut waiting).unwrap();
2204 let reply = serde_json::json!({"decisions": [{
2205 "id": waiting.id, "blocked_by": ["not-present"],
2206 "missing_dependencies": ["not-present"],
2207 "question": "Which prerequisite replaces the missing task?"
2208 }]})
2209 .to_string();
2210 let cfg = config(mock_agent(dir.path(), REPLY, env(&reply)));
2211 Conductor::new()
2212 .run_once(
2213 &cfg,
2214 dir.path(),
2215 &queue,
2216 &questions,
2217 dir.path(),
2218 &[waiting.clone()],
2219 &[],
2220 &[],
2221 2,
2222 )
2223 .await
2224 .unwrap();
2225 let after = queue.get(&waiting.id).unwrap();
2226 assert_eq!(after.status, TaskStatus::Blocked);
2227 assert_eq!(
2228 questions.get(&after.blocked_by[0]).unwrap().summary,
2229 "Which prerequisite replaces the missing task?"
2230 );
2231 }
2232
2233 #[tokio::test]
2234 async fn dependency_resolution_keeps_decisions_during_unrelated_task_progress() {
2235 let dir = tempdir().unwrap();
2236 let queue = Queue::at(dir.path().join("queue"));
2237 let questions = Questions::at(dir.path().join("questions"));
2238 let mut dep = task("prerequisite");
2239 dep.id = "20261013-193611-ca5b".into();
2240 dep.start("existing-run".into());
2241 queue.put(&mut dep).unwrap();
2242 let mut unrelated = task("unrelated work");
2243 unrelated.start("other-run".into());
2244 queue.put(&mut unrelated).unwrap();
2245 std::fs::File::options()
2248 .write(true)
2249 .open(queue.path_of(&unrelated.id))
2250 .unwrap()
2251 .set_times(std::fs::FileTimes::new().set_modified(std::time::UNIX_EPOCH))
2252 .unwrap();
2253 unrelated.succeed();
2254 let mut waiting = task("waiting");
2255 let mut asking = task("needs a product decision");
2256 let mut holding = task("must stay held");
2257 queue.put(&mut waiting).unwrap();
2258 queue.put(&mut asking).unwrap();
2259 queue.put(&mut holding).unwrap();
2260 let reply = serde_json::json!({"decisions": [
2261 {"id": waiting.id, "blocked_by": ["ca5b"], "reason": "wait for implementation"},
2262 {"id": asking.id, "question": "Which behavior do you want?"},
2263 {"id": holding.id, "recovery": "hold", "reason": "already implemented elsewhere"}
2264 ]})
2265 .to_string();
2266 let mut vars = env(&reply);
2267 vars.insert(
2268 "UNRELATED_PATH".into(),
2269 queue.path_of(&unrelated.id).to_string_lossy().into_owned(),
2270 );
2271 vars.insert(
2272 "UNRELATED_RECORD".into(),
2273 serde_json::to_string(&unrelated).unwrap(),
2274 );
2275 let script = r#"#!/bin/sh
2276cat >/dev/null
2277printf '%s' "$UNRELATED_RECORD" > "$UNRELATED_PATH"
2278printf '%s\n' "$MOCK_REPLY"
2279"#;
2280 let cfg = config(mock_agent(dir.path(), script, vars));
2281 Conductor::new()
2282 .run_once(
2283 &cfg,
2284 dir.path(),
2285 &queue,
2286 &questions,
2287 dir.path(),
2288 &[waiting.clone(), asking.clone(), holding.clone()],
2289 &[],
2290 &[],
2291 2,
2292 )
2293 .await
2294 .unwrap();
2295 assert_eq!(queue.get(&unrelated.id).unwrap().status, TaskStatus::Done);
2296 let after = queue.get(&waiting.id).unwrap();
2297 assert_eq!(after.status, TaskStatus::Blocked);
2298 assert_eq!(after.blocked_by, [dep.id]);
2299 let asked = queue.get(&asking.id).unwrap();
2300 assert_eq!(asked.status, TaskStatus::Blocked);
2301 assert_eq!(
2302 questions.get(&asked.blocked_by[0]).unwrap().summary,
2303 "Which behavior do you want?"
2304 );
2305 assert_eq!(queue.get(&holding.id).unwrap().status, TaskStatus::Held);
2306 }
2307
2308 #[test]
2309 fn a_dependency_decision_blocks_the_task_and_leaves_priority_alone() {
2310 let dir = tempdir().unwrap();
2311 let queue = Queue::at(dir.path().join("queue"));
2312 let questions = Questions::at(dir.path().join("questions"));
2313 let mut a = task("a");
2314 a.priority = 9;
2315 queue.put(&mut a).unwrap();
2316
2317 let verdict = Verdict {
2318 decisions: vec![Decision {
2319 id: a.id.clone(),
2320 blocked_by: vec!["20260101-000000-dead".to_owned()],
2321 reason: Some("waits on the other task".to_owned()),
2322 recovery: None,
2323 question: None,
2324 choices: Vec::new(),
2325 actions: BTreeMap::new(),
2326 question_decision: None,
2327 evidence: Vec::new(),
2328 missing_dependencies: Vec::new(),
2329 }],
2330 };
2331 apply(&queue, &questions, &verdict).unwrap();
2332
2333 let back = queue.get(&a.id).unwrap();
2334 assert_eq!(back.status, TaskStatus::Blocked);
2335 assert_eq!(back.blocked_by, ["20260101-000000-dead"]);
2336 assert_eq!(
2337 back.priority, 9,
2338 "the conductor's reply cannot carry priority"
2339 );
2340 }
2341
2342 #[test]
2343 fn a_question_decision_files_one_and_blocks_on_its_id() {
2344 let dir = tempdir().unwrap();
2345 let queue = Queue::at(dir.path().join("queue"));
2346 let questions = Questions::at(dir.path().join("questions"));
2347 let mut t = task("ambiguous");
2348 queue.put(&mut t).unwrap();
2349
2350 let verdict = Verdict {
2351 decisions: vec![Decision {
2352 id: t.id.clone(),
2353 blocked_by: Vec::new(),
2354 reason: Some("which backend?".to_owned()),
2355 recovery: None,
2356 question: Some("Which storage backend?".to_owned()),
2357 choices: vec!["SQLite".to_owned(), "Redis".to_owned()],
2358 actions: BTreeMap::new(),
2359 question_decision: None,
2360 evidence: Vec::new(),
2361 missing_dependencies: Vec::new(),
2362 }],
2363 };
2364 apply(&queue, &questions, &verdict).unwrap();
2365
2366 let back = queue.get(&t.id).unwrap();
2367 assert_eq!(back.status, TaskStatus::Blocked);
2368 assert_eq!(back.blocked_by.len(), 1);
2369 let q = questions.get(&back.blocked_by[0]).unwrap();
2370 assert_eq!(q.summary, "Which storage backend?");
2371 assert_eq!(q.node, NODE);
2372 assert!(q.status.open());
2373 }
2374
2375 #[test]
2376 fn a_task_with_an_open_question_already_reuses_it_rather_than_filing_a_second_one() {
2377 let dir = tempdir().unwrap();
2378 let queue = Queue::at(dir.path().join("queue"));
2379 let questions = Questions::at(dir.path().join("questions"));
2380 let mut t = task("asked once");
2381 queue.put(&mut t).unwrap();
2382
2383 let decision = Decision {
2384 id: t.id.clone(),
2385 reason: Some("still deciding".to_owned()),
2386 question: Some("Which backend?".to_owned()),
2387 ..Decision::default()
2388 };
2389 apply(
2390 &queue,
2391 &questions,
2392 &Verdict {
2393 decisions: vec![decision.clone()],
2394 },
2395 )
2396 .unwrap();
2397 assert_eq!(questions.list().len(), 1);
2398 let first_question_id = queue.get(&t.id).unwrap().blocked_by[0].clone();
2399
2400 let mut released = queue.get(&t.id).unwrap();
2405 released.release();
2406 queue.put(&mut released).unwrap();
2407
2408 apply(
2409 &queue,
2410 &questions,
2411 &Verdict {
2412 decisions: vec![decision],
2413 },
2414 )
2415 .unwrap();
2416 assert_eq!(questions.list().len(), 1, "no duplicate question was filed");
2417 let after = queue.get(&t.id).unwrap();
2418 assert_eq!(
2419 after.blocked_by,
2420 [first_question_id],
2421 "the existing open question is reused, not replaced"
2422 );
2423 }
2424
2425 #[test]
2426 fn a_same_id_question_from_another_node_is_not_reused() {
2427 let dir = tempdir().unwrap();
2428 let queue = Queue::at(dir.path().join("queue"));
2429 let questions = Questions::at(dir.path().join("questions"));
2430 let mut t = task("must ask the conductor");
2431 queue.put(&mut t).unwrap();
2432
2433 let mut unrelated = Question::new(
2434 t.id.clone(),
2435 "review".to_owned(),
2436 "reviewer-1".to_owned(),
2437 "An unrelated review question".to_owned(),
2438 String::new(),
2439 Vec::new(),
2440 );
2441 questions.put(&mut unrelated).unwrap();
2442
2443 apply(
2444 &queue,
2445 &questions,
2446 &Verdict {
2447 decisions: vec![Decision {
2448 id: t.id.clone(),
2449 question: Some("Which backend?".to_owned()),
2450 ..Decision::default()
2451 }],
2452 },
2453 )
2454 .unwrap();
2455
2456 let blocked_by = &queue.get(&t.id).unwrap().blocked_by;
2457 assert_eq!(blocked_by.len(), 1);
2458 assert_ne!(blocked_by[0], unrelated.id);
2459 assert!(questions.get(&unrelated.id).unwrap().status.open());
2460 assert_eq!(questions.get(&blocked_by[0]).unwrap().node, NODE);
2461 }
2462
2463 #[test]
2464 fn answering_the_question_lets_the_resolver_clear_the_block_with_the_answer_kept() {
2465 let dir = tempdir().unwrap();
2466 let queue = Queue::at(dir.path().join("queue"));
2467 let questions = Questions::at(dir.path().join("questions"));
2468 let mut t = task("waits on an answer");
2469 queue.put(&mut t).unwrap();
2470
2471 apply(
2472 &queue,
2473 &questions,
2474 &Verdict {
2475 decisions: vec![Decision {
2476 id: t.id.clone(),
2477 blocked_by: Vec::new(),
2478 reason: None,
2479 recovery: None,
2480 question: Some("Which backend?".to_owned()),
2481 choices: Vec::new(),
2482 actions: BTreeMap::new(),
2483 question_decision: None,
2484 evidence: Vec::new(),
2485 missing_dependencies: Vec::new(),
2486 }],
2487 },
2488 )
2489 .unwrap();
2490 let blocked = queue.get(&t.id).unwrap();
2491 let question_id = blocked.blocked_by[0].clone();
2492
2493 let mut q = questions.get(&question_id).unwrap();
2494 q.answer(Answer::Text("SQLite".to_owned())).unwrap();
2495 questions.put(&mut q).unwrap();
2496 assert_eq!(q.status, QuestionStatus::Answered);
2497
2498 let mut task_after = queue.get(&t.id).unwrap();
2502 task_after.record_answer(q.summary.clone(), "SQLite".to_owned());
2503 task_after.unblock(&question_id);
2504 assert_eq!(task_after.status, TaskStatus::Queued);
2505 assert_eq!(task_after.answers[0].answer, "SQLite");
2506 }
2507
2508 #[test]
2509 fn a_stalled_task_can_be_requeued_or_held() {
2510 let dir = tempdir().unwrap();
2511 let queue = Queue::at(dir.path().join("queue"));
2512 let questions = Questions::at(dir.path().join("questions"));
2513
2514 let mut requeue_me = task("stuck a");
2515 requeue_me.start("run-1".to_owned());
2516 queue.put(&mut requeue_me).unwrap();
2517
2518 let mut hold_me = task("stuck b");
2519 hold_me.start("run-2".to_owned());
2520 queue.put(&mut hold_me).unwrap();
2521
2522 apply(
2523 &queue,
2524 &questions,
2525 &Verdict {
2526 decisions: vec![
2527 Decision {
2528 id: requeue_me.id.clone(),
2529 recovery: Some(Recovery::Requeue),
2530 ..Decision::default()
2531 },
2532 Decision {
2533 id: hold_me.id.clone(),
2534 recovery: Some(Recovery::Hold),
2535 reason: Some("looks broken".to_owned()),
2536 ..Decision::default()
2537 },
2538 ],
2539 },
2540 )
2541 .unwrap();
2542
2543 let requeued = queue.get(&requeue_me.id).unwrap();
2544 assert_eq!(requeued.status, TaskStatus::Queued);
2545 assert_eq!(requeued.attempts, 0);
2546
2547 let held = queue.get(&hold_me.id).unwrap();
2548 assert_eq!(held.status, TaskStatus::Held);
2549 assert_eq!(held.hold_reason.as_deref(), Some("looks broken"));
2550 }
2551
2552 #[test]
2553 fn a_machine_held_task_asked_about_restores_to_held_once_answered() {
2554 let dir = tempdir().unwrap();
2559 let queue = Queue::at(dir.path().join("queue"));
2560 let questions = Questions::at(dir.path().join("questions"));
2561 let mut t = task("held out of attempts");
2562 t.hold_machine(Some("out of attempts".to_owned()));
2563 queue.put(&mut t).unwrap();
2564
2565 apply(
2566 &queue,
2567 &questions,
2568 &Verdict {
2569 decisions: vec![Decision {
2570 id: t.id.clone(),
2571 reason: Some("what should happen to this one?".to_owned()),
2572 question: Some("Hold it, or try again?".to_owned()),
2573 ..Decision::default()
2574 }],
2575 },
2576 )
2577 .unwrap();
2578 let blocked = queue.get(&t.id).unwrap();
2579 assert_eq!(blocked.status, TaskStatus::Blocked);
2580 let question_id = blocked.blocked_by[0].clone();
2581
2582 let mut q = questions.get(&question_id).unwrap();
2583 q.answer(Answer::Text("leave it held".to_owned())).unwrap();
2584 questions.put(&mut q).unwrap();
2585
2586 let mut after = queue.get(&t.id).unwrap();
2588 after.record_answer(q.summary.clone(), "leave it held".to_owned());
2589 after.unblock(&question_id);
2590 assert_eq!(
2591 after.status,
2592 TaskStatus::Held,
2593 "must not fall back to queued"
2594 );
2595 assert_eq!(after.hold_reason.as_deref(), Some("out of attempts"));
2596 }
2597
2598 #[test]
2599 fn a_reaffirmed_hold_with_no_new_reason_is_not_silently_auto_released_by_triage() {
2600 let dir = tempdir().unwrap();
2610 let queue = Queue::at(dir.path().join("queue"));
2611 let questions = Questions::at(dir.path().join("questions"));
2612 let mut t = task("disk pressure, then reconsidered");
2613 t.hold_machine(Some(
2614 "not enough free space to start a run: 10 bytes free, 100 required by \
2615 `[disk] min_free_bytes`"
2616 .to_owned(),
2617 ));
2618 t.record_answer(
2619 "How should this be handled?".to_owned(),
2620 "keep it held, a human will look at it later".to_owned(),
2621 );
2622 queue.put(&mut t).unwrap();
2623
2624 apply(
2625 &queue,
2626 &questions,
2627 &Verdict {
2628 decisions: vec![Decision {
2629 id: t.id.clone(),
2630 recovery: Some(Recovery::Hold),
2631 ..Decision::default()
2632 }],
2633 },
2634 )
2635 .unwrap();
2636
2637 let after = queue.get(&t.id).unwrap();
2638 assert_eq!(after.status, TaskStatus::Held);
2639 assert!(
2640 !after
2641 .hold_reason
2642 .as_deref()
2643 .unwrap_or_default()
2644 .starts_with("not enough free space"),
2645 "the stale disk-pressure text must not survive a reconfirmed hold: {:?}",
2646 after.hold_reason
2647 );
2648
2649 let cfg_dir = tempdir().unwrap();
2652 let config = cfg_dir.path().join("magi.toml");
2653 std::fs::write(&config, "[disk]\nmin_free_bytes = 0\n").unwrap();
2654 let report =
2655 crate::triage::run_once(&queue, &questions, Some(&config), jiff::Timestamp::now());
2656 assert!(report.resumed.is_empty(), "must not be auto-released");
2657 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
2658 }
2659
2660 #[test]
2661 fn explicit_resumption_rehold_requires_new_evidence_and_another_answer() {
2662 crate::run::pin_test_home();
2663 let dir = tempdir().unwrap();
2664 let queue = Queue::at(dir.path().join("queue"));
2665 let questions = Questions::at(dir.path().join("questions"));
2666 let config = dir.path().join("magi.toml");
2667 std::fs::write(&config, "[disk]\nmin_free_bytes = 0\n").unwrap();
2668 let now = jiff::Timestamp::now();
2669 let triage = || crate::triage::run_once(&queue, &questions, Some(&config), now);
2670 let open = || {
2671 questions
2672 .list()
2673 .into_iter()
2674 .filter(|q| q.node == "triage" && q.status.open())
2675 .collect::<Vec<_>>()
2676 };
2677 let hold = Decision {
2678 recovery: Some(Recovery::Hold),
2679 reason: Some("waiting on manual worktree cleanup".to_owned()),
2680 ..Decision::default()
2681 };
2682
2683 let mut t = task("looping hold");
2684 t.hold_machine(Some("waiting on manual worktree cleanup".to_owned()));
2685 queue.put(&mut t).unwrap();
2686 let hold = Decision {
2687 id: t.id.clone(),
2688 ..hold
2689 };
2690
2691 assert_eq!(triage().asked.len(), 1);
2693 let first = open().remove(0);
2694 let mut q = questions.get(&first.id).unwrap();
2695 let resume = q.choices[0].clone();
2696 q.answer(Answer::Choice(resume)).unwrap();
2697 questions.put(&mut q).unwrap();
2698 assert_eq!(triage().answered.len(), 1);
2699 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
2700
2701 apply(
2703 &queue,
2704 &questions,
2705 &Verdict {
2706 decisions: vec![hold.clone()],
2707 },
2708 )
2709 .unwrap();
2710 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
2711 assert!(triage().asked.is_empty());
2712
2713 let mut evidence = Question::new(
2715 t.id.clone(),
2716 "preflight".into(),
2717 "check".into(),
2718 "New permission failure".into(),
2719 String::new(),
2720 Vec::new(),
2721 );
2722 questions.put(&mut evidence).unwrap();
2723 let hold = Decision {
2724 evidence: vec![evidence.id.clone()],
2725 reason: Some("new permission check failed".into()),
2726 ..hold
2727 };
2728 apply(
2729 &queue,
2730 &questions,
2731 &Verdict {
2732 decisions: vec![hold.clone()],
2733 },
2734 )
2735 .unwrap();
2736 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
2737
2738 assert_eq!(triage().asked.len(), 1);
2740 let second = open().remove(0);
2741 assert!(second.detail.contains("new permission check failed"));
2742 assert!(triage().asked.is_empty(), "no duplicate question");
2743 assert_eq!(open().len(), 1);
2744
2745 let mut q = questions.get(&second.id).unwrap();
2747 let force = q.choices[0].clone();
2748 q.answer(Answer::Choice(force)).unwrap();
2749 questions.put(&mut q).unwrap();
2750 assert_eq!(triage().answered.len(), 1);
2751 apply(
2752 &queue,
2753 &questions,
2754 &Verdict {
2755 decisions: vec![hold],
2756 },
2757 )
2758 .unwrap();
2759 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
2760 }
2761
2762 #[test]
2763 fn conductor_resumption_notice_does_not_solicit_unregistered_questions() {
2764 crate::run::pin_test_home();
2765 let dir = tempdir().unwrap();
2766 let queue = Queue::at(dir.path().join("queue"));
2767 let questions = Questions::at(dir.path().join("questions"));
2768
2769 let mut t = task("task with explicit resumption");
2770 t.status = TaskStatus::Queued;
2771 t.resumption = Some(crate::queue::Resumption {
2772 generation: 1,
2773 source: "test".into(),
2774 question_id: Some("q1".into()),
2775 at: jiff::Timestamp::now(),
2776 instruction: "resume".into(),
2777 answers_through: 0,
2778 runs_through: 0,
2779 cleared_reason: None,
2780 blocking_evidence: Vec::new(),
2781 });
2782 queue.put(&mut t).unwrap();
2783
2784 let decision = Decision {
2786 id: t.id.clone(),
2787 question: Some("How should we proceed with this task?".into()),
2788 blocked_by: vec!["dep-x".into()],
2789 reason: Some("needs clarification".into()),
2790 recovery: Some(Recovery::Hold),
2791 ..Decision::default()
2792 };
2793
2794 apply(
2795 &queue,
2796 &questions,
2797 &Verdict {
2798 decisions: vec![decision],
2799 },
2800 )
2801 .unwrap();
2802
2803 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
2805 assert!(questions.list().is_empty());
2807
2808 let notices = crate::notices::Notices::open();
2810 let notice = notices
2811 .get(&crate::notices::id_of(&format!(
2812 "conductor-resumption:{}",
2813 t.id
2814 )))
2815 .expect("conductor-resumption notice filed");
2816
2817 assert_eq!(
2818 notice.link,
2819 Some(crate::notices::Link::Task { id: t.id.clone() })
2820 );
2821 assert!(!notice.message.contains("How should we proceed"));
2823 assert!(
2825 notice
2826 .message
2827 .contains("No reply to this notice is needed.")
2828 );
2829 assert!(!notice.message.contains("Some("));
2831 assert!(!notice.message.contains("None"));
2832 assert!(!notice.message.contains("[]"));
2833 assert!(!notice.message.contains("{:?}"));
2834 assert!(notice.message.contains("Proposed dependencies: dep-x."));
2836 }
2837
2838 #[test]
2839 fn a_runnable_task_can_be_held_directly_without_a_question() {
2840 let dir = tempdir().unwrap();
2841 let queue = Queue::at(dir.path().join("queue"));
2842 let questions = Questions::at(dir.path().join("questions"));
2843 let mut t = task("already answered, should stay put");
2844 queue.put(&mut t).unwrap();
2845
2846 apply(
2847 &queue,
2848 &questions,
2849 &Verdict {
2850 decisions: vec![Decision {
2851 id: t.id.clone(),
2852 recovery: Some(Recovery::Hold),
2853 reason: Some("operator already said keep this held".to_owned()),
2854 ..Decision::default()
2855 }],
2856 },
2857 )
2858 .unwrap();
2859
2860 let after = queue.get(&t.id).unwrap();
2861 assert_eq!(after.status, TaskStatus::Held);
2862 assert_eq!(after.hold_source, Some(crate::queue::HoldSource::Machine));
2863 }
2864
2865 #[test]
2866 fn done_recovery_closes_a_held_task_whose_goal_is_already_met() {
2867 crate::run::pin_test_home();
2868 let dir = tempdir().unwrap();
2874 let queue = Queue::at(dir.path().join("queue"));
2875 let questions = Questions::at(dir.path().join("questions"));
2876 let mut t = task("already merged by hand");
2877 t.hold_machine(Some("branch survived, awaiting a decision".to_owned()));
2878 t.record_answer(
2879 "Handle this one?".to_owned(),
2880 "already merged and cleaned up, close it".to_owned(),
2881 );
2882 queue.put(&mut t).unwrap();
2883
2884 apply(
2885 &queue,
2886 &questions,
2887 &Verdict {
2888 decisions: vec![Decision {
2889 id: t.id.clone(),
2890 recovery: Some(Recovery::Done),
2891 reason: Some("operator confirmed this already landed".to_owned()),
2892 ..Decision::default()
2893 }],
2894 },
2895 )
2896 .unwrap();
2897
2898 let after = queue.get(&t.id).unwrap();
2899 assert_eq!(after.status, TaskStatus::Done);
2900 assert!(after.hold_reason.is_none());
2901 assert_eq!(after.answers.len(), 1, "the record of why is kept");
2902 }
2903
2904 #[test]
2905 fn done_recovery_is_ignored_for_a_runnable_or_running_task() {
2906 let dir = tempdir().unwrap();
2907 let queue = Queue::at(dir.path().join("queue"));
2908 let questions = Questions::at(dir.path().join("questions"));
2909
2910 let mut queued = task("never ran yet");
2911 queue.put(&mut queued).unwrap();
2912
2913 let mut running = task("mid-run");
2914 running.start("run-1".to_owned());
2915 queue.put(&mut running).unwrap();
2916
2917 for id in [queued.id.clone(), running.id.clone()] {
2918 apply(
2919 &queue,
2920 &questions,
2921 &Verdict {
2922 decisions: vec![Decision {
2923 id,
2924 recovery: Some(Recovery::Done),
2925 ..Decision::default()
2926 }],
2927 },
2928 )
2929 .unwrap();
2930 }
2931
2932 assert_eq!(queue.get(&queued.id).unwrap().status, TaskStatus::Queued);
2933 assert_eq!(queue.get(&running.id).unwrap().status, TaskStatus::Running);
2934 }
2935
2936 #[test]
2937 fn a_question_after_two_settled_answers_is_still_filed_and_blocks() {
2938 let dir = tempdir().unwrap();
2941 let queue = Queue::at(dir.path().join("queue"));
2942 let questions = Questions::at(dir.path().join("questions"));
2943 let mut t = task("asked about repeatedly");
2944 t.hold_machine(Some("out of attempts".to_owned()));
2945 t.record_answer("Handle this one? (1)".to_owned(), "not yet".to_owned());
2946 t.record_answer(
2947 "Handle this one? (2)".to_owned(),
2948 "still not yet".to_owned(),
2949 );
2950 queue.put(&mut t).unwrap();
2951 assert_eq!(questions.list().len(), 0);
2952
2953 let verdict = Verdict {
2954 decisions: vec![Decision {
2955 id: t.id.clone(),
2956 question: Some("Branch conflicts with origin/main, how do we proceed?".to_owned()),
2957 ..Decision::default()
2958 }],
2959 };
2960 apply(&queue, &questions, &verdict).unwrap();
2961
2962 let filed = questions.list();
2963 assert_eq!(filed.len(), 1, "the question was filed");
2964 assert_eq!(
2965 filed[0].summary,
2966 "Branch conflicts with origin/main, how do we proceed?"
2967 );
2968 let deputy = filed[0]
2969 .deputy
2970 .as_ref()
2971 .expect("the wait is handed to a deputy");
2972 assert!(deputy.brief.contains(&t.id), "{}", deputy.brief);
2973 assert_eq!(
2974 deputy.starts, 0,
2975 "filing never starts anything: the loop does not wait"
2976 );
2977 assert!(filed[0].status.open());
2978 assert_eq!(filed[0].node, NODE);
2979 let after = queue.get(&t.id).unwrap();
2980 assert_eq!(after.status, TaskStatus::Blocked);
2981 assert_eq!(after.blocked_by, vec![filed[0].id.clone()]);
2982 assert_eq!(after.answers.len(), 2, "the prior answers are untouched");
2983 assert!(
2984 !after
2985 .hold_reason
2986 .clone()
2987 .unwrap_or_default()
2988 .contains("conduct tried to ask"),
2989 "no hold was applied"
2990 );
2991
2992 apply(&queue, &questions, &verdict).unwrap();
2993 let again = questions.list();
2994 assert_eq!(again.len(), 1, "the open question is reused");
2995 assert_eq!(again[0].id, filed[0].id);
2996 }
2997
2998 #[test]
2999 fn question_source_identity_resolves_aliases_and_rejects_invented_targets() {
3000 let dir = tempdir().unwrap();
3001 init_repo_with_branch(dir.path(), "source-a");
3002 let mut t = task("source decision");
3003 t.repo = dir.path().into();
3004 let decision = |reference: &str| QuestionDecision {
3005 operation: QuestionOperation::Recover,
3006 target: QuestionTarget::Source {
3007 reference: reference.into(),
3008 },
3009 };
3010 assert_eq!(
3011 decision("source-a").identity(&t).unwrap(),
3012 decision("refs/heads/source-a").identity(&t).unwrap()
3013 );
3014 assert_ne!(
3015 decision("source-a").identity(&t).unwrap(),
3016 decision("main").identity(&t).unwrap()
3017 );
3018 assert!(decision("invented-source-label").identity(&t).is_err());
3019 let unrelated = QuestionDecision {
3020 operation: QuestionOperation::Resume,
3021 target: QuestionTarget::Run {
3022 id: "unrelated-run".into(),
3023 },
3024 };
3025 assert!(unrelated.identity(&t).is_err());
3026 }
3027
3028 #[test]
3029 fn invalid_question_targets_still_file_and_block_queued_tasks() {
3030 let dir = tempdir().unwrap();
3031 init_repo_with_branch(dir.path(), "source-a");
3032 let queue = Queue::at(dir.path().join("queue"));
3033 let questions = Questions::at(dir.path().join("questions"));
3034 for target in [
3035 QuestionTarget::Source {
3036 reference: "missing-source".into(),
3037 },
3038 QuestionTarget::Run {
3039 id: "unrelated-run".into(),
3040 },
3041 ] {
3042 let mut t = task("decision with invalid metadata");
3043 t.repo = dir.path().into();
3044 queue.put(&mut t).unwrap();
3045 let d = Decision {
3046 id: t.id.clone(),
3047 question: Some("Which recovery should proceed?".into()),
3048 choices: vec!["inspect first".into(), "keep waiting".into()],
3049 question_decision: Some(QuestionDecision {
3050 operation: QuestionOperation::Recover,
3051 target,
3052 }),
3053 ..Decision::default()
3054 };
3055 apply_one(&queue, &questions, &d, None).unwrap();
3056 let q = questions
3057 .list()
3058 .into_iter()
3059 .find(|q| q.run == t.id)
3060 .unwrap();
3061 assert_eq!(q.summary, d.question.as_deref().unwrap());
3062 assert_eq!(q.choices, d.choices);
3063 assert!(q.status.open());
3064 let context: serde_json::Value =
3065 serde_json::from_str(q.decision_context.as_ref().unwrap()).unwrap();
3066 assert!(context[3].is_null(), "invalid metadata was discarded");
3067 let after = queue.get(&t.id).unwrap();
3068 assert_eq!(after.status, TaskStatus::Blocked);
3069 assert_eq!(after.blocked_by, vec![q.id.clone()]);
3070 apply_one(&queue, &questions, &d, None).unwrap();
3071 assert_eq!(questions.list().iter().filter(|q| q.run == t.id).count(), 1);
3072 }
3073 }
3074
3075 #[test]
3076 fn answered_conductor_question_needs_changed_facts_before_reasking() {
3077 let dir = tempdir().unwrap();
3078 let queue = Queue::at(dir.path().join("queue"));
3079 let questions = Questions::at(dir.path().join("questions"));
3080 let mut t = task("recovery decision");
3081 t.hold_machine(Some("out of attempts".into()));
3082 t.runs = vec!["source-run-a".into(), "source-run-b".into()];
3083 queue.put(&mut t).unwrap();
3084 let mut d = Decision {
3085 id: t.id.clone(),
3086 question: Some("Recover from source A?".into()),
3087 choices: vec!["approve source A".into(), "keep held".into()],
3088 question_decision: Some(QuestionDecision {
3089 operation: QuestionOperation::Recover,
3090 target: QuestionTarget::Run {
3091 id: "source-run-a".into(),
3092 },
3093 }),
3094 ..Decision::default()
3095 };
3096 apply_one(&queue, &questions, &d, None).unwrap();
3097 let mut q = questions.list().pop().unwrap();
3098 q.answer(crate::ask::Answer::Choice("keep held".into()))
3099 .unwrap();
3100 questions.put(&mut q).unwrap();
3101 queue
3102 .modify(&t.id, |task| {
3103 task.unblock(&q.id);
3104 task.hold_machine(Some("recovery remains under consideration".into()));
3105 true
3106 })
3107 .unwrap();
3108 d.question = Some("Should we keep waiting on recovery?".into());
3109 d.choices = vec!["recover using source A".into(), "remain on hold".into()];
3110 apply_one(&queue, &questions, &d, None).unwrap();
3111 assert_eq!(questions.list().len(), 1, "no repeated operator turn");
3112 d.question = Some("Recover from source B?".into());
3113 d.question_decision.as_mut().unwrap().target = QuestionTarget::Run {
3115 id: "source-run-b".into(),
3116 };
3117 apply_one(&queue, &questions, &d, None).unwrap();
3118 assert_eq!(
3119 questions.list().len(),
3120 2,
3121 "new decision with unchanged task facts"
3122 );
3123 let after = queue.get(&t.id).unwrap();
3124 assert_eq!(after.instruction, t.instruction);
3125 assert_eq!(after.runs, t.runs);
3126 assert_eq!(after.status, TaskStatus::Blocked);
3127 }
3128
3129 #[test]
3130 fn a_second_conductor_question_is_still_allowed_after_one_settled_answer() {
3131 let dir = tempdir().unwrap();
3132 let queue = Queue::at(dir.path().join("queue"));
3133 let questions = Questions::at(dir.path().join("questions"));
3134 let mut t = task("asked about once already");
3135 t.hold_machine(Some("out of attempts".to_owned()));
3136 t.record_answer("Handle this one?".to_owned(), "not yet".to_owned());
3137 queue.put(&mut t).unwrap();
3138
3139 apply(
3140 &queue,
3141 &questions,
3142 &Verdict {
3143 decisions: vec![Decision {
3144 id: t.id.clone(),
3145 question: Some("Still not sure - now what?".to_owned()),
3146 ..Decision::default()
3147 }],
3148 },
3149 )
3150 .unwrap();
3151
3152 assert_eq!(questions.list().len(), 1, "the second question was filed");
3153 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
3154 }
3155
3156 #[test]
3157 fn a_held_task_with_an_open_triage_question_is_left_to_triage() {
3158 let dir = tempdir().unwrap();
3164 let queue = Queue::at(dir.path().join("queue"));
3165 let questions = Questions::at(dir.path().join("questions"));
3166 let mut t = task("held, triage already asking about it");
3167 t.hold_machine(Some("cause unclear".to_owned()));
3168 queue.put(&mut t).unwrap();
3169
3170 let mut triage_q = Question::new(
3171 t.id.clone(),
3172 crate::triage::NODE.to_owned(),
3173 "triage".to_owned(),
3174 "Still needed?".to_owned(),
3175 String::new(),
3176 vec![
3177 "resume".to_owned(),
3178 "not yet".to_owned(),
3179 "discard".to_owned(),
3180 ],
3181 );
3182 questions.put(&mut triage_q).unwrap();
3183
3184 for decision in [
3185 Decision {
3186 id: t.id.clone(),
3187 question: Some("what now?".to_owned()),
3188 ..Decision::default()
3189 },
3190 Decision {
3191 id: t.id.clone(),
3192 recovery: Some(Recovery::Requeue),
3193 ..Decision::default()
3194 },
3195 ] {
3196 apply(
3197 &queue,
3198 &questions,
3199 &Verdict {
3200 decisions: vec![decision],
3201 },
3202 )
3203 .unwrap();
3204 }
3205
3206 let after = queue.get(&t.id).unwrap();
3207 assert_eq!(
3208 after.status,
3209 TaskStatus::Held,
3210 "triage still owns this hold"
3211 );
3212 assert!(after.blocked_by.is_empty());
3213 assert_eq!(
3214 questions.list().len(),
3215 1,
3216 "no second, conductor-owned question was filed"
3217 );
3218 }
3219
3220 #[test]
3221 fn a_held_task_with_an_answered_but_unapplied_triage_question_is_still_left_alone() {
3222 let dir = tempdir().unwrap();
3230 let queue = Queue::at(dir.path().join("queue"));
3231 let questions = Questions::at(dir.path().join("questions"));
3232 let mut t = task("held, triage question answered but not yet applied");
3233 t.hold_machine(Some("cause unclear".to_owned()));
3234 queue.put(&mut t).unwrap();
3235
3236 let mut triage_q = Question::new(
3237 t.id.clone(),
3238 crate::triage::NODE.to_owned(),
3239 "triage".to_owned(),
3240 "Still needed?".to_owned(),
3241 String::new(),
3242 vec![
3243 "resume".to_owned(),
3244 "not yet".to_owned(),
3245 "discard".to_owned(),
3246 ],
3247 );
3248 questions.put(&mut triage_q).unwrap();
3249 triage_q
3250 .answer(Answer::Choice("not yet".to_owned()))
3251 .unwrap();
3252 questions.put(&mut triage_q).unwrap();
3253 assert!(!triage_q.status.open());
3254
3255 apply(
3256 &queue,
3257 &questions,
3258 &Verdict {
3259 decisions: vec![Decision {
3260 id: t.id.clone(),
3261 question: Some("what now?".to_owned()),
3262 ..Decision::default()
3263 }],
3264 },
3265 )
3266 .unwrap();
3267
3268 let after = queue.get(&t.id).unwrap();
3269 assert_eq!(
3270 after.status,
3271 TaskStatus::Held,
3272 "triage's own answer is not yet applied - conduct must wait"
3273 );
3274 assert_eq!(
3275 questions.list().len(),
3276 1,
3277 "no conductor question was filed over the pending triage answer"
3278 );
3279 }
3280
3281 #[test]
3282 fn manual_hold_rejects_hostile_or_stale_conductor_recovery() {
3283 let dir = tempdir().unwrap();
3284 let queue = Queue::at(dir.path().join("queue"));
3285 let questions = Questions::at(dir.path().join("questions"));
3286 let mut held = task("manual recovery");
3287 held.priority = 300;
3288 held.runs.push("run20260912-224242-daf5".to_owned());
3289 held.hold_manual(Some(
3290 "active manual recovery run20260912-224242-daf5".to_owned(),
3291 ));
3292 queue.put(&mut held).unwrap();
3293
3294 for decision in [
3298 Decision {
3299 id: held.id.clone(),
3300 recovery: Some(Recovery::Requeue),
3301 ..Decision::default()
3302 },
3303 Decision {
3304 id: held.id.clone(),
3305 recovery: Some(Recovery::Hold),
3306 reason: Some("stale replacement reason".to_owned()),
3307 ..Decision::default()
3308 },
3309 Decision {
3310 id: held.id.clone(),
3311 recovery: Some(Recovery::Review),
3312 ..Decision::default()
3313 },
3314 Decision {
3315 id: held.id.clone(),
3316 blocked_by: vec!["other-task".to_owned()],
3317 question: Some("retry now?".to_owned()),
3318 ..Decision::default()
3319 },
3320 ] {
3321 apply(
3322 &queue,
3323 &questions,
3324 &Verdict {
3325 decisions: vec![decision],
3326 },
3327 )
3328 .unwrap();
3329 }
3330
3331 let after = queue.get(&held.id).unwrap();
3332 assert_eq!(after.status, TaskStatus::Held);
3333 assert!(after.operator_held());
3334 assert_eq!(after.priority, 300);
3335 assert_eq!(after.runs, ["run20260912-224242-daf5"]);
3336 assert_eq!(
3337 after.hold_reason.as_deref(),
3338 Some("active manual recovery run20260912-224242-daf5")
3339 );
3340 assert!(after.blocked_by.is_empty());
3341 assert!(questions.list().is_empty());
3342 assert!(
3343 queue.next_runnable().is_none(),
3344 "must not dispatch a duplicate"
3345 );
3346 }
3347
3348 #[test]
3349 fn machine_holds_remain_recoverable_and_manual_release_is_authorization() {
3350 let dir = tempdir().unwrap();
3351 let queue = Queue::at(dir.path().join("queue"));
3352 let questions = Questions::at(dir.path().join("questions"));
3353
3354 let mut automatic = task("disk gate");
3355 automatic.hold_machine(Some("disk full".to_owned()));
3356 queue.put(&mut automatic).unwrap();
3357 let requeue = || Verdict {
3358 decisions: vec![Decision {
3359 id: automatic.id.clone(),
3360 recovery: Some(Recovery::Requeue),
3361 ..Decision::default()
3362 }],
3363 };
3364 apply(&queue, &questions, &requeue()).unwrap();
3365 assert_eq!(queue.get(&automatic.id).unwrap().status, TaskStatus::Queued);
3366
3367 let mut manual = task("operator gate");
3368 manual.hold_manual(Some("wait for operator".to_owned()));
3369 queue.put(&mut manual).unwrap();
3370 apply(
3371 &queue,
3372 &questions,
3373 &Verdict {
3374 decisions: vec![Decision {
3375 id: manual.id.clone(),
3376 recovery: Some(Recovery::Requeue),
3377 ..Decision::default()
3378 }],
3379 },
3380 )
3381 .unwrap();
3382 assert_eq!(queue.get(&manual.id).unwrap().status, TaskStatus::Held);
3383
3384 let mut released = queue.get(&manual.id).unwrap();
3387 released.release();
3388 queue.put(&mut released).unwrap();
3389 assert_eq!(queue.get(&manual.id).unwrap().status, TaskStatus::Queued);
3390 }
3391
3392 #[test]
3393 fn legacy_reasoned_hold_is_protected_without_losing_its_metadata() {
3394 let dir = tempdir().unwrap();
3395 let queue = Queue::at(dir.path().join("queue"));
3396 let questions = Questions::at(dir.path().join("questions"));
3397 let mut legacy = task("old explicit hold");
3398 legacy.status = TaskStatus::Held;
3399 legacy.hold_reason = Some("manual recovery already active".to_owned());
3400 legacy.hold_source = None;
3401 legacy.blocked_by = vec!["dependency".to_owned()];
3402 queue.put(&mut legacy).unwrap();
3403
3404 apply(
3405 &queue,
3406 &questions,
3407 &Verdict {
3408 decisions: vec![Decision {
3409 id: legacy.id.clone(),
3410 recovery: Some(Recovery::Requeue),
3411 ..Decision::default()
3412 }],
3413 },
3414 )
3415 .unwrap();
3416
3417 let after = queue.get(&legacy.id).unwrap();
3418 assert_eq!(after.status, TaskStatus::Held);
3419 assert_eq!(after.hold_source, None);
3420 assert_eq!(after.hold_reason, legacy.hold_reason);
3421 assert_eq!(after.blocked_by, legacy.blocked_by);
3422 }
3423
3424 #[test]
3425 fn review_recovery_is_a_no_op_without_a_survivable_branch() {
3426 crate::run::pin_test_home();
3432 let dir = tempdir().unwrap();
3433 let queue = Queue::at(dir.path().join("queue"));
3434 let questions = Questions::at(dir.path().join("questions"));
3435 let mut t = task("blocked with no readable run");
3436 t.start("20260101-000000-dead".to_owned()); t.fail("blocked", 5);
3438 queue.put(&mut t).unwrap();
3439
3440 apply(
3441 &queue,
3442 &questions,
3443 &Verdict {
3444 decisions: vec![Decision {
3445 id: t.id.clone(),
3446 recovery: Some(Recovery::Review),
3447 ..Decision::default()
3448 }],
3449 },
3450 )
3451 .unwrap();
3452
3453 let after = queue.get(&t.id).unwrap();
3454 assert_eq!(
3455 after.status,
3456 TaskStatus::Failed,
3457 "with nothing to reopen, the decision is dropped rather than guessed at"
3458 );
3459 assert!(after.review_branch.is_none());
3460 }
3461
3462 #[test]
3463 fn requeue_and_review_recovery_are_ignored_for_a_runnable_task() {
3464 let dir = tempdir().unwrap();
3468 let queue = Queue::at(dir.path().join("queue"));
3469 let questions = Questions::at(dir.path().join("questions"));
3470
3471 for recovery in [Recovery::Requeue, Recovery::Review] {
3472 let mut t = task("ordinary");
3473 queue.put(&mut t).unwrap();
3474
3475 apply(
3476 &queue,
3477 &questions,
3478 &Verdict {
3479 decisions: vec![Decision {
3480 id: t.id.clone(),
3481 recovery: Some(recovery),
3482 ..Decision::default()
3483 }],
3484 },
3485 )
3486 .unwrap();
3487
3488 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
3489 }
3490 }
3491
3492 #[tokio::test]
3493 async fn a_broken_agent_leaves_the_queue_untouched_and_does_not_error() {
3494 let dir = tempdir().unwrap();
3495 let cfg = config(mock_agent(dir.path(), BROKEN, BTreeMap::new()));
3496 let queue = Queue::at(dir.path().join("queue"));
3497 let questions = Questions::at(dir.path().join("questions"));
3498 let mut t = task("normal");
3499 queue.put(&mut t).unwrap();
3500
3501 let mut conductor = Conductor::new();
3502 conductor
3503 .maybe_run(
3504 &cfg,
3505 dir.path(),
3506 &queue,
3507 &questions,
3508 dir.path(),
3509 &[t.clone()],
3510 &[],
3511 &[],
3512 2,
3513 )
3514 .await;
3515
3516 assert_eq!(
3517 queue.get(&t.id).unwrap().status,
3518 TaskStatus::Queued,
3519 "a failed invocation must change nothing"
3520 );
3521 assert!(
3522 queue.next_runnable().is_some(),
3523 "the loop must still be able to take the next task"
3524 );
3525 }
3526
3527 #[tokio::test]
3528 async fn a_reply_with_no_json_leaves_the_queue_untouched() {
3529 let dir = tempdir().unwrap();
3530 let cfg = config(mock_agent(dir.path(), GARBAGE, BTreeMap::new()));
3531 let queue = Queue::at(dir.path().join("queue"));
3532 let questions = Questions::at(dir.path().join("questions"));
3533 let mut t = task("normal");
3534 queue.put(&mut t).unwrap();
3535
3536 let mut conductor = Conductor::new();
3537 conductor
3538 .maybe_run(
3539 &cfg,
3540 dir.path(),
3541 &queue,
3542 &questions,
3543 dir.path(),
3544 &[t.clone()],
3545 &[],
3546 &[],
3547 2,
3548 )
3549 .await;
3550
3551 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
3552 }
3553
3554 #[tokio::test]
3555 async fn a_conductor_chain_falls_to_the_next_agent_once_each() {
3556 let dir = tempdir().unwrap();
3557 let mut t = task("chained");
3558 let reply = format!(
3559 "{{\"decisions\":[{{\"id\":\"{}\",\"blocked_by\":[\"x\"],\"reason\":\"why\"}}]}}",
3560 t.id
3561 );
3562 let counted = |id: &str, tail: &str| {
3563 let calls = dir.path().join(format!("{id}.calls"));
3564 let path = dir.path().join(format!("{id}.sh"));
3565 std::fs::write(
3566 &path,
3567 format!(
3568 "#!/bin/sh\ncat >/dev/null\necho x >> '{}'\n{tail}\n",
3569 calls.display()
3570 ),
3571 )
3572 .unwrap();
3573 AgentSpec {
3574 id: id.to_owned(),
3575 kind: AgentKind::Command,
3576 model: None,
3577 command: vec!["sh".to_owned(), path.to_string_lossy().into_owned()],
3578 extra_args: Vec::new(),
3579 env: BTreeMap::new(),
3580 prompt_delivery: None,
3581 }
3582 };
3583 let n_calls = |id: &str| {
3584 std::fs::read_to_string(dir.path().join(format!("{id}.calls")))
3585 .map_or(0, |s| s.lines().count())
3586 };
3587 let mut cfg = config(counted("a", "exit 3"));
3588 cfg.agents = vec![
3589 counted("a", "exit 3"),
3590 counted("b", &format!("printf '%s' '{reply}'")),
3591 ];
3592 cfg.roles.conductor = Some(crate::config::AgentChoice::Chain(vec![
3593 "a".into(),
3594 "b".into(),
3595 "a".into(),
3596 ]));
3597 let queue = Queue::at(dir.path().join("queue"));
3598 let questions = Questions::at(dir.path().join("questions"));
3599 queue.put(&mut t).unwrap();
3600
3601 let mut conductor = Conductor::new();
3602 conductor
3603 .maybe_run(
3604 &cfg,
3605 dir.path(),
3606 &queue,
3607 &questions,
3608 dir.path(),
3609 &[t.clone()],
3610 &[],
3611 &[],
3612 2,
3613 )
3614 .await;
3615
3616 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
3617 assert_eq!(n_calls("a"), 1, "each id is tried once");
3618 assert_eq!(n_calls("b"), 1);
3619 let saved = std::fs::read_to_string(seat_path(dir.path())).unwrap();
3620 assert!(
3621 saved.contains("\"b\""),
3622 "the seat on disk is the one that ran: {saved}"
3623 );
3624 }
3625
3626 #[tokio::test]
3627 async fn json_survives_code_fences_and_a_preamble() {
3628 let dir = tempdir().unwrap();
3629 let mut t = task("fenced");
3630 let reply = format!(
3631 "Sure, here is my decision.\n\n```json\n{{\"decisions\":[{{\"id\":\"{}\",\
3632 \"blocked_by\":[\"x\"],\"reason\":\"why\"}}]}}\n```\n",
3633 t.id
3634 );
3635 let cfg = config(mock_agent(dir.path(), REPLY, env(&reply)));
3636 let queue = Queue::at(dir.path().join("queue"));
3637 let questions = Questions::at(dir.path().join("questions"));
3638 queue.put(&mut t).unwrap();
3639
3640 let mut conductor = Conductor::new();
3641 conductor
3642 .maybe_run(
3643 &cfg,
3644 dir.path(),
3645 &queue,
3646 &questions,
3647 dir.path(),
3648 &[t.clone()],
3649 &[],
3650 &[],
3651 2,
3652 )
3653 .await;
3654
3655 let back = queue.get(&t.id).unwrap();
3656 assert_eq!(back.status, TaskStatus::Blocked);
3657 assert_eq!(back.blocked_by, ["x"]);
3658 }
3659
3660 #[tokio::test]
3661 async fn the_conductor_is_not_called_again_when_nothing_worth_looking_at_has_changed() {
3662 let dir = tempdir().unwrap();
3665 let cfg = config(mock_agent(dir.path(), REPLY, env("{\"decisions\":[]}")));
3666 let queue = Queue::at(dir.path().join("queue"));
3667 let questions = Questions::at(dir.path().join("questions"));
3668 let mut t = task("stable");
3669 queue.put(&mut t).unwrap();
3670 let artifacts = dir.path().join("conduct").join("artifacts");
3671 let turn = |n: usize| artifacts.join(format!("turn-{n}.out"));
3672
3673 let mut conductor = Conductor::new();
3674 conductor
3675 .maybe_run(
3676 &cfg,
3677 dir.path(),
3678 &queue,
3679 &questions,
3680 dir.path(),
3681 &[t.clone()],
3682 &[],
3683 &[],
3684 2,
3685 )
3686 .await;
3687 assert!(turn(1).is_file(), "the first cycle must call the conductor");
3688
3689 conductor
3690 .maybe_run(
3691 &cfg,
3692 dir.path(),
3693 &queue,
3694 &questions,
3695 dir.path(),
3696 &[t.clone()],
3697 &[],
3698 &[],
3699 2,
3700 )
3701 .await;
3702 assert!(
3703 !turn(2).is_file(),
3704 "an unchanged revision and an unchanged stalled/finished set must not call the \
3705 conductor twice"
3706 );
3707
3708 t.priority = 1;
3710 queue.put(&mut t).unwrap();
3711 conductor
3712 .maybe_run(
3713 &cfg,
3714 dir.path(),
3715 &queue,
3716 &questions,
3717 dir.path(),
3718 &[t.clone()],
3719 &[],
3720 &[],
3721 2,
3722 )
3723 .await;
3724 assert!(turn(2).is_file(), "a moved revision calls it again");
3725 }
3726
3727 #[tokio::test]
3728 async fn a_task_turning_stalled_calls_the_conductor_again_despite_an_unchanged_revision() {
3729 let dir = tempdir().unwrap();
3735 let cfg = config(mock_agent(dir.path(), REPLY, env("{\"decisions\":[]}")));
3736 let queue = Queue::at(dir.path().join("queue"));
3737 let questions = Questions::at(dir.path().join("questions"));
3738 let mut t = task("quiet");
3739 queue.put(&mut t).unwrap();
3740 let artifacts = dir.path().join("conduct").join("artifacts");
3741 let turn = |n: usize| artifacts.join(format!("turn-{n}.out"));
3742
3743 let mut conductor = Conductor::new();
3744 conductor
3745 .maybe_run(
3746 &cfg,
3747 dir.path(),
3748 &queue,
3749 &questions,
3750 dir.path(),
3751 &[t.clone()],
3752 &[],
3753 &[],
3754 2,
3755 )
3756 .await;
3757 assert!(turn(1).is_file());
3758
3759 conductor
3760 .maybe_run(
3761 &cfg,
3762 dir.path(),
3763 &queue,
3764 &questions,
3765 dir.path(),
3766 &[],
3767 &[t.clone()],
3768 &[],
3769 2,
3770 )
3771 .await;
3772 assert!(
3773 turn(2).is_file(),
3774 "a task turning stalled must call the conductor again"
3775 );
3776
3777 conductor
3780 .maybe_run(
3781 &cfg,
3782 dir.path(),
3783 &queue,
3784 &questions,
3785 dir.path(),
3786 &[],
3787 &[t.clone()],
3788 &[],
3789 2,
3790 )
3791 .await;
3792 assert!(
3793 !turn(3).is_file(),
3794 "the same stalled task lingering must not call the conductor every cycle"
3795 );
3796 }
3797
3798 fn rehold(queue: &Queue, questions: &Questions, id: &str, note: &str) {
3799 apply(
3800 queue,
3801 questions,
3802 &Verdict {
3803 decisions: vec![Decision {
3804 id: id.to_owned(),
3805 reason: Some(note.to_owned()),
3806 recovery: Some(Recovery::Hold),
3807 ..Decision::default()
3808 }],
3809 },
3810 )
3811 .unwrap();
3812 }
3813
3814 #[test]
3815 fn reholding_with_an_identical_note_changes_nothing() {
3816 let dir = tempdir().unwrap();
3817 let queue = Queue::at(dir.path().join("queue"));
3818 let questions = Questions::at(dir.path().join("questions"));
3819 let mut t = task("held");
3820 t.hold_machine(Some("waiting on a human".to_owned()));
3821 queue.put(&mut t).unwrap();
3822
3823 rehold(&queue, &questions, &t.id, "owner said keep it held");
3824 let first = queue.get(&t.id).unwrap();
3825 let rev = queue.revision();
3826 for _ in 0..5 {
3827 rehold(&queue, &questions, &t.id, "owner said keep it held");
3828 }
3829 let after = queue.get(&t.id).unwrap();
3830 assert_eq!(after.hold_reason, first.hold_reason);
3831 assert_eq!(after.updated_at, first.updated_at);
3832 assert_eq!(queue.revision(), rev, "nothing was written");
3833 }
3834
3835 #[test]
3836 fn reholding_with_different_notes_keeps_one_previously_level() {
3837 let dir = tempdir().unwrap();
3838 let queue = Queue::at(dir.path().join("queue"));
3839 let questions = Questions::at(dir.path().join("questions"));
3840 let mut t = task("held");
3841 t.hold_machine(Some("original".to_owned()));
3842 queue.put(&mut t).unwrap();
3843
3844 for i in 0..20 {
3845 rehold(&queue, &questions, &t.id, &format!("note {}", i % 2));
3846 }
3847 let reason = queue.get(&t.id).unwrap().hold_reason.unwrap();
3848 assert_eq!(reason.matches("(previously:").count(), 1, "{reason}");
3849 assert!(reason.starts_with("note "), "the new note leads: {reason}");
3850 }
3851
3852 #[test]
3853 fn an_already_nested_reason_is_matched_by_its_outermost_note() {
3854 let mut t = task("deep");
3855 let nested = "same\n\n(previously: same\n\n(previously: same))";
3856 t.hold_machine(Some(nested.to_owned()));
3857 let d = Decision {
3858 id: t.id.clone(),
3859 reason: Some("same".to_owned()),
3860 ..Decision::default()
3861 };
3862 assert_eq!(reaffirmed_hold_reason(&t, &d), None);
3863 let d2 = Decision {
3864 reason: Some("other".to_owned()),
3865 ..d
3866 };
3867 assert_eq!(
3868 reaffirmed_hold_reason(&t, &d2).as_deref(),
3869 Some("other\n\n(previously: same)")
3870 );
3871 }
3872
3873 #[tokio::test]
3874 async fn a_repeated_hold_decision_settles_instead_of_looping() {
3875 let dir = tempdir().unwrap();
3876 let queue = Queue::at(dir.path().join("queue"));
3877 let questions = Questions::at(dir.path().join("questions"));
3878 let reply = r#"{"decisions":[{"id":"ID","reason":"keep held","recovery":"hold"}]}"#;
3879 let mut t = task("held");
3880 t.hold_machine(Some("first".to_owned()));
3881 queue.put(&mut t).unwrap();
3882 let cfg = config(mock_agent(
3883 dir.path(),
3884 REPLY,
3885 env(&reply.replace("ID", &t.id)),
3886 ));
3887 let mut conductor = Conductor::new();
3888 for _ in 0..2 {
3890 let held = queue.get(&t.id).unwrap();
3891 conductor
3892 .maybe_run(
3893 &cfg,
3894 dir.path(),
3895 &queue,
3896 &questions,
3897 dir.path(),
3898 &[],
3899 &[],
3900 &[held],
3901 2,
3902 )
3903 .await;
3904 }
3905 let held = queue.get(&t.id).unwrap();
3906 assert!(
3907 held.hold_reason
3908 .as_deref()
3909 .unwrap()
3910 .starts_with("keep held")
3911 );
3912 assert!(
3913 !conductor.worth_a_look(&queue, &[], &[held]),
3914 "an unchanged held task must stop being reconsidered"
3915 );
3916 }
3917
3918 #[tokio::test]
3919 async fn alternating_wording_does_not_keep_a_held_task_in_the_loop() {
3920 let dir = tempdir().unwrap();
3921 let queue = Queue::at(dir.path().join("queue"));
3922 let questions = Questions::at(dir.path().join("questions"));
3923 let mut t = task("held");
3924 t.hold_machine(Some("first".to_owned()));
3925 queue.put(&mut t).unwrap();
3926 let reply = |note: &str| {
3927 format!(
3928 r#"{{"decisions":[{{"id":"{}","reason":"{note}","recovery":"hold"}}]}}"#,
3929 t.id
3930 )
3931 };
3932 let cfg_a = config(mock_agent(dir.path(), REPLY, env(&reply("keep held"))));
3933 let cfg_b = config(mock_agent(dir.path(), REPLY, env(&reply("leave held"))));
3934 let mut conductor = Conductor::new();
3935 let mut writes = 0;
3936 for i in 0..6 {
3937 let held = queue.get(&t.id).unwrap();
3938 let before = queue.revision();
3939 conductor
3940 .maybe_run(
3941 if i % 2 == 0 { &cfg_a } else { &cfg_b },
3942 dir.path(),
3943 &queue,
3944 &questions,
3945 dir.path(),
3946 &[],
3947 &[],
3948 &[held],
3949 2,
3950 )
3951 .await;
3952 if queue.revision() != before {
3953 writes += 1;
3954 }
3955 }
3956 assert!(writes <= 2, "the loop must settle, saw {writes} writes");
3957 let mut held = queue.get(&t.id).unwrap();
3958 held.instruction.push_str(" (edited)");
3959 queue.put(&mut held).unwrap();
3960 let held = queue.get(&t.id).unwrap();
3961 assert!(conductor.worth_a_look(&queue, &[], &[held]));
3962 }
3963
3964 #[test]
3965 fn worth_a_look_is_config_free_and_matches_maybe_runs_own_gate() {
3966 let dir = tempdir().unwrap();
3967 let queue = Queue::at(dir.path().join("queue"));
3968 let mut t = task("t");
3969 queue.put(&mut t).unwrap();
3970
3971 let mut conductor = Conductor::new();
3972 assert!(
3973 conductor.worth_a_look(&queue, &[], &[]),
3974 "a conductor that has never run has something to look at"
3975 );
3976
3977 conductor.last_seen = Some(conductor.snapshot(&queue, &[], &[]));
3978 assert!(
3979 !conductor.worth_a_look(&queue, &[], &[]),
3980 "nothing changed and nothing is stalled or finished"
3981 );
3982 assert!(
3983 conductor.worth_a_look(&queue, &[t.clone()], &[]),
3984 "a stalled task is worth a look even at the same revision"
3985 );
3986 assert!(
3987 conductor.worth_a_look(&queue, &[], &[t.clone()]),
3988 "a finished task is worth a look even at the same revision"
3989 );
3990 }
3991
3992 #[tokio::test]
3993 async fn the_conduct_path_never_calls_ask_and_wait() {
3994 let dir = tempdir().unwrap();
4000 let queue = Queue::at(dir.path().join("queue"));
4001 let questions = Questions::at(dir.path().join("questions"));
4002 let mut t = task("asks without blocking");
4003 queue.put(&mut t).unwrap();
4004
4005 apply(
4006 &queue,
4007 &questions,
4008 &Verdict {
4009 decisions: vec![Decision {
4010 id: t.id.clone(),
4011 question: Some("ok?".to_owned()),
4012 ..Decision::default()
4013 }],
4014 },
4015 )
4016 .unwrap();
4017 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
4019 }
4020
4021 #[test]
4022 fn a_pinned_resume_is_not_held_or_requeued_by_the_conductor() {
4023 let mut t = Task::new("t".into(), "t".into(), PathBuf::new(), Source::Human);
4024 t.resume_override = Some(crate::queue::OperatorResume {
4025 question_id: "q".into(),
4026 at: jiff::Timestamp::now(),
4027 conductor_rehold: None,
4028 forced: false,
4029 pinned_run: Some("run-1".into()),
4030 });
4031 assert!(pinned_resume(&t));
4032 assert!(!may_hold(&mut t, "waiting for magi resume"));
4033 assert!(
4034 t.resume_override
4035 .as_ref()
4036 .unwrap()
4037 .conductor_rehold
4038 .is_none(),
4039 "a refused hold is not recorded as an override"
4040 );
4041 t.resume_override = None;
4042 assert!(!pinned_resume(&t));
4043 assert!(may_hold(&mut t, "no override, so a hold is allowed"));
4044 }
4045
4046 #[test]
4047 fn a_pinned_resume_is_not_blocked_by_a_conductor_question_or_dependency() {
4048 let dir = tempdir().unwrap();
4049 let queue = Queue::at(dir.path().join("queue"));
4050 let questions = Questions::at(dir.path().join("questions"));
4051 let mut t = task("resume me");
4052 t.resume_override = Some(crate::queue::OperatorResume {
4053 question_id: "q".into(),
4054 at: jiff::Timestamp::now(),
4055 conductor_rehold: None,
4056 forced: true,
4057 pinned_run: Some("run-1".into()),
4058 });
4059 queue.put(&mut t).unwrap();
4060
4061 apply(
4062 &queue,
4063 &questions,
4064 &Verdict {
4065 decisions: vec![
4066 Decision {
4067 id: t.id.clone(),
4068 question: Some("really?".to_owned()),
4069 ..Decision::default()
4070 },
4071 Decision {
4072 id: t.id.clone(),
4073 blocked_by: vec!["other".to_owned()],
4074 ..Decision::default()
4075 },
4076 ],
4077 },
4078 )
4079 .unwrap();
4080
4081 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
4082 assert!(questions.list().is_empty());
4083 }
4084}