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