1use std::collections::{BTreeMap, BTreeSet};
44use std::path::{Path, PathBuf};
45use std::time::Duration;
46
47use anyhow::{Context as _, Result};
48use serde::Deserialize;
49
50use crate::agent::{self, Invocation, SeatState};
51use crate::ask::{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, Default, Deserialize)]
102pub struct Decision {
103 pub id: String,
105 #[serde(default)]
108 pub blocked_by: Vec<String>,
109 #[serde(default)]
111 pub reason: Option<String>,
112 #[serde(default)]
120 pub recovery: Option<Recovery>,
121 #[serde(default)]
125 pub question: Option<String>,
126 #[serde(default)]
128 pub choices: Vec<String>,
129}
130
131#[derive(Debug, Clone, Default, Deserialize)]
144pub struct Verdict {
145 pub decisions: Vec<Decision>,
148}
149
150fn view(t: &Task, max_attempts: usize) -> prompt::ConductTask {
153 prompt::ConductTask {
154 id: t.id.clone(),
155 title: t.title.clone(),
156 instruction: t.instruction.clone(),
157 repo: t.repo.display().to_string(),
158 priority: t.priority,
159 status: t.status.as_str().to_owned(),
160 attempts: t.attempts,
161 max_attempts,
162 last_error: t.last_error.clone(),
163 hold_reason: t.hold_reason.clone(),
164 hold_source: t.hold_source.map(|source| source.label().to_owned()),
165 blocked_by: t.blocked_by.clone(),
166 answers: t
167 .answers
168 .iter()
169 .map(|a| prompt::ConductAnswer {
170 question: a.question.clone(),
171 answer: a.answer.clone(),
172 })
173 .collect(),
174 operator_resume: t.resume_override.as_ref().map(|o| {
175 format!(
176 "the operator explicitly answered \"resume\" at {}; do not hold this \
177 task again for the same reason unless there is new information",
178 o.at
179 )
180 }),
181 }
182}
183
184fn pinned_resume(task: &Task) -> bool {
188 task.resume_override
189 .as_ref()
190 .is_some_and(|o| o.pinned_run.is_some())
191}
192
193fn may_hold(task: &mut Task, reason: &str) -> bool {
202 let Some(o) = task.resume_override.as_mut() else {
203 return true;
204 };
205 if o.forced || o.pinned_run.is_some() {
206 tracing::warn!(
207 "conductor tried to hold task {} after the operator forced a resume: {reason}",
208 task.id
209 );
210 return false;
211 }
212 if o.conductor_rehold.is_some() {
213 return false;
214 }
215 o.conductor_rehold = Some(reason.to_owned());
216 true
217}
218
219fn severity_str(s: crate::verdict::Severity) -> &'static str {
222 match s {
223 crate::verdict::Severity::Nit => "nit",
224 crate::verdict::Severity::Minor => "minor",
225 crate::verdict::Severity::Major => "major",
226 crate::verdict::Severity::Blocker => "blocker",
227 }
228}
229
230fn surviving_branch(task: &Task) -> Option<String> {
235 let last = task.runs.last()?;
236 let state = RunState::load(last).ok()?;
237 state.winner().map(|c| c.branch.clone())
238}
239
240fn reaffirmed_hold_reason(task: &Task, d: &Decision) -> Option<String> {
267 let note = match &d.reason {
268 Some(reason) => reason.clone(),
269 None => match task.answers.last() {
270 Some(a) => format!(
271 "conduct held this again with no new reason given; last operator \
272 answer on record: {}",
273 a.answer
274 ),
275 None => "conduct held this again with no reason given".to_owned(),
276 },
277 };
278 match task.hold_reason.as_deref() {
279 Some(prior) if !prior.is_empty() => {
280 let outer = outermost_hold_note(prior);
281 if note.trim() == prior.trim() || note.trim() == outer {
282 None
283 } else {
284 Some(format!("{note}\n\n(previously: {outer})"))
285 }
286 }
287 _ => Some(note),
288 }
289}
290
291const PREVIOUSLY: &str = "\n\n(previously: ";
294
295fn outermost_hold_note(reason: &str) -> &str {
298 reason.split(PREVIOUSLY).next().unwrap_or(reason).trim()
299}
300
301fn hold_note(d: &Decision) -> String {
303 d.reason
304 .clone()
305 .unwrap_or_else(|| "(no reason given)".to_owned())
306}
307
308async fn outcome_for(task: &Task, repo: &Path) -> prompt::ConductOutcome {
310 let Some(run_id) = task.runs.last().cloned() else {
311 return prompt::ConductOutcome {
312 run_id: "(none)".to_owned(),
313 unreadable: Some("this task has not produced a run yet".to_owned()),
314 run_status: None,
315 open_findings: Vec::new(),
316 rounds_used: 0,
317 rounds_max: 0,
318 rounds: Vec::new(),
319 branch: None,
320 branch_head: None,
321 references: None,
322 empty_candidate: false,
323 };
324 };
325 let state = match RunState::load(&run_id) {
326 Ok(s) => s,
327 Err(e) => {
328 tracing::warn!(
333 "conductor: could not read run {run_id} for task {}: {e:#}",
334 task.short()
335 );
336 return prompt::ConductOutcome {
337 run_id,
338 unreadable: Some(format!("{e:#}")),
339 run_status: None,
340 open_findings: Vec::new(),
341 rounds_used: 0,
342 rounds_max: 0,
343 rounds: Vec::new(),
344 branch: None,
345 branch_head: None,
346 references: None,
347 empty_candidate: false,
348 };
349 }
350 };
351
352 let finding_view = |f: &crate::verdict::Finding| prompt::ConductFinding {
353 id: f.id.clone(),
354 title: f.title.clone(),
355 severity: severity_str(f.severity).to_owned(),
356 };
357 let open_findings = state
358 .open_findings()
359 .into_iter()
360 .map(finding_view)
361 .collect();
362 let rounds = state
363 .reviews
364 .iter()
365 .map(|r| prompt::ConductRound {
366 round: r.round,
367 findings: r
368 .reviews
369 .iter()
370 .flat_map(|rec| rec.findings.iter())
371 .map(finding_view)
372 .collect(),
373 addressed: r
374 .fix
375 .as_ref()
376 .map(|fx| fx.addressed.clone())
377 .unwrap_or_default(),
378 rejected: r
379 .fix
380 .as_ref()
381 .map(|fx| {
382 fx.rejected
383 .iter()
384 .map(|rej| prompt::ConductRejection {
385 id: rej.id.clone(),
386 why: rej.why.clone(),
387 })
388 .collect()
389 })
390 .unwrap_or_default(),
391 })
392 .collect();
393 let branch = state.winner().map(|c| c.branch.clone());
394 let branch_head = match &branch {
395 Some(b) => crate::git::rev_parse(repo, b)
396 .await
397 .ok()
398 .map(|h| h.chars().take(8).collect()),
399 None => None,
400 };
401
402 prompt::ConductOutcome {
403 run_id,
404 unreadable: None,
405 run_status: Some(state.status.as_str().to_owned()),
406 open_findings,
407 rounds_used: state.reviews.len(),
408 rounds_max: state.config.graph.review_rounds,
409 rounds,
410 branch,
411 branch_head,
412 references: crate::refs::describe(&state.seeds),
413 empty_candidate: state.merge.as_ref().is_some_and(|m| m.empty),
414 }
415}
416
417async fn open_pr_fact(task: &Task, repo: &Path) -> Option<String> {
421 let id = task.runs.last()?;
422 let state = match RunState::load(id) {
423 Ok(s) => s,
424 Err(e) => return Some(format!("could not check open pull requests: {e:#}")),
425 };
426 let branch = state.winner()?.branch.clone();
427 let base = state.base_branch.clone();
428 match crate::land::find_open_pr(repo, &branch, &base).await {
429 Ok(crate::land::OpenPr::None) => None,
430 Ok(crate::land::OpenPr::One { url, .. }) => Some(format!(
431 "pull request {url} is already open for {branch} into {base}"
432 )),
433 Ok(crate::land::OpenPr::Many(urls)) => Some(format!(
434 "several pull requests are already open for {branch} into {base}: {}",
435 urls.join(" ")
436 )),
437 Err(e) => Some(format!("could not check open pull requests: {e:#}")),
438 }
439}
440
441async fn attach_facts(cfg: &Config, repo: &Path, queue: &Queue, verdict: &mut Verdict) {
448 for d in verdict
449 .decisions
450 .iter_mut()
451 .filter(|d| d.question.is_some())
452 {
453 let Ok(task) = queue.get(&d.id) else {
454 continue;
455 };
456 let text = format!("{}\n{}", task.title, task.instruction);
457 let pr_fact = open_pr_fact(&task, repo_for(&task, repo).as_path()).await;
458 if crate::refs::scan(&text).is_empty() {
459 if let (Some(fact), Some(q)) = (pr_fact, d.question.as_mut()) {
460 q.push_str(&format!(
461 "\n\nChecked against the repository (magi did this, not the model):\n{fact}"
462 ));
463 }
464 continue;
465 }
466 let repo = repo_for(&task, repo);
467 let remote = &cfg.merge.remote;
468 let base = crate::git::merge_base_branch(&repo, remote, cfg.merge.base.as_deref())
469 .await
470 .ok();
471 let facts = match base {
472 Some(base) => {
473 let base_name = base.clone();
474 let tracking = format!("{remote}/{base}");
475 let refreshed = crate::git::fetch(&repo, remote, &base)
478 .await
479 .is_ok_and(|o| o.ok());
480 let against = tracking;
483 match crate::git::rev_parse(&repo, &against).await {
484 Ok(tip) => crate::refs::describe(
485 &crate::refs::resolve(&repo, &tip, remote, &text).await,
486 )
487 .map(|facts| {
488 if refreshed {
489 facts
490 } else {
491 format!(
492 "{facts}\n(could not fetch {remote}/{base_name}: this is \
493 against the last fetched `{against}`, which may be behind \
494 the remote)"
495 )
496 }
497 }),
498 Err(_) => Some(format!(
499 "could NOT be checked against the repository: {against} is not \
500 available here, so whether the work is in the base is unknown"
501 )),
502 }
503 }
504 None => Some("could not check the repository: no base branch known".to_owned()),
505 };
506 let facts = match (facts, pr_fact) {
507 (Some(f), Some(p)) => Some(format!("{f}\n{p}")),
508 (f, p) => f.or(p),
509 };
510 if let (Some(facts), Some(q)) = (facts, d.question.as_mut()) {
511 q.push_str(&format!(
512 "\n\nChecked against the repository (magi did this, not the model):\n{facts}"
513 ));
514 }
515 }
516}
517
518async fn finished_view(t: &Task, repo: &Path, max_attempts: usize) -> prompt::ConductFinished {
520 prompt::ConductFinished {
521 task: view(t, max_attempts),
522 outcome: outcome_for(t, &repo_for(t, repo)).await,
523 }
524}
525
526fn repo_for(task: &Task, fallback: &Path) -> PathBuf {
529 if task.repo.as_os_str().is_empty() || task.repo == Path::new(".") {
530 fallback.to_path_buf()
531 } else {
532 task.repo.clone()
533 }
534}
535
536fn apply_one(queue: &Queue, questions: &Questions, d: &Decision) -> Result<()> {
553 let _claim = queue
554 .claim(&d.id)
555 .with_context(|| format!("task {} is claimed elsewhere right now", d.id))?;
556 let mut task = queue.get(&d.id).context("no such task")?;
557
558 if task.operator_held() {
562 return Ok(());
563 }
564
565 if task.status == TaskStatus::Held && crate::triage::pending_for(questions, &task) {
575 return Ok(());
576 }
577
578 let pinned = pinned_resume(&task);
581 if pinned && (d.question.is_some() || !d.blocked_by.is_empty()) {
582 return Ok(());
583 }
584
585 if let Some(text) = &d.question {
586 if task.status == TaskStatus::Done {
587 return Ok(());
588 }
589 let question_id = match questions
593 .list()
594 .into_iter()
595 .find(|q| q.status.open() && q.node == NODE && q.run == task.id)
596 {
597 Some(existing) => existing.id,
598 None => {
606 let mut q = Question::new(
607 task.id.clone(),
608 NODE.to_owned(),
609 SEAT.to_owned(),
610 text.clone(),
611 d.reason.clone().unwrap_or_default(),
612 d.choices.clone(),
613 );
614 q.deputy = Some(Deputy::new(crate::deputy::brief(
619 &task.id,
620 d.reason.as_deref().unwrap_or_default(),
621 &q.choices,
622 &q.actions,
623 )));
624 if task.repo.is_dir() && task.repo != Path::new(".") {
625 q.cwd = Some(task.repo.to_string_lossy().into_owned());
626 }
627 questions.put(&mut q)?;
628 q.id
629 }
630 };
631 task.block(vec![question_id], d.reason.clone());
632 return queue.put(&mut task);
633 }
634
635 match task.status {
636 TaskStatus::Queued if !d.blocked_by.is_empty() => {
637 task.block(d.blocked_by.clone(), d.reason.clone());
638 queue.put(&mut task)?;
639 }
640 TaskStatus::Queued if d.recovery == Some(Recovery::Hold) => {
644 if may_hold(&mut task, &hold_note(d)) {
645 task.hold_machine(d.reason.clone());
646 queue.put(&mut task)?;
647 }
648 }
649 TaskStatus::Running => match d.recovery {
650 Some(Recovery::Requeue) if pinned_resume(&task) => {}
651 Some(Recovery::Requeue) => {
652 task.requeue();
653 queue.put(&mut task)?;
654 }
655 Some(Recovery::Hold) if may_hold(&mut task, &hold_note(d)) => {
656 task.hold_machine(d.reason.clone());
657 queue.put(&mut task)?;
658 }
659 _ => {}
663 },
664 TaskStatus::Failed | TaskStatus::Held => match d.recovery {
665 Some(Recovery::Requeue) if pinned_resume(&task) => {}
668 Some(Recovery::Requeue) => {
669 task.requeue();
670 queue.put(&mut task)?;
671 }
672 Some(Recovery::Hold) => {
673 if let Some(reason) = reaffirmed_hold_reason(&task, d) {
677 if may_hold(&mut task, &hold_note(d)) {
678 task.hold_machine(Some(reason));
679 queue.put(&mut task)?;
680 }
681 }
682 }
683 Some(Recovery::Review) => {
684 if let Some(branch) = surviving_branch(&task) {
685 task.request_review(branch);
686 queue.put(&mut task)?;
687 }
688 }
694 Some(Recovery::Done) => {
695 task.succeed();
696 crate::daemon::supersede_prior_runs(&task, &crate::run::home());
700 queue.put(&mut task)?;
701 }
702 None => {}
703 },
704 _ => {}
707 }
708 Ok(())
709}
710
711pub fn apply(queue: &Queue, questions: &Questions, verdict: &Verdict) -> Result<()> {
715 for d in &verdict.decisions {
716 if let Err(e) = apply_one(queue, questions, d) {
717 tracing::warn!("conductor decision for task {}: {e:#}", d.id);
718 }
719 }
720 Ok(())
721}
722
723pub fn seat_path(home: &Path) -> PathBuf {
729 home.join("conduct").join("seat.json")
730}
731
732pub fn load_seat(home: &Path) -> Option<SeatState> {
734 serde_json::from_str(&std::fs::read_to_string(seat_path(home)).ok()?).ok()
735}
736
737fn busy_path(home: &Path) -> PathBuf {
738 home.join("conduct").join("busy")
739}
740
741pub fn busy(home: &Path) -> bool {
747 std::fs::metadata(busy_path(home))
748 .and_then(|m| m.modified())
749 .ok()
750 .and_then(|t| t.elapsed().ok())
751 .is_some_and(|age| age < TURN_TIMEOUT + Duration::from_secs(30))
752}
753
754struct Busy(PathBuf);
756
757impl Busy {
758 fn mark(home: &Path) -> Self {
759 let path = busy_path(home);
760 if let Some(dir) = path.parent() {
761 let _ = std::fs::create_dir_all(dir);
762 }
763 let _ = std::fs::write(&path, std::process::id().to_string());
764 Self(path)
765 }
766}
767
768impl Drop for Busy {
769 fn drop(&mut self) {
770 let _ = std::fs::remove_file(&self.0);
771 }
772}
773
774#[derive(Debug, Default)]
777pub struct Conductor {
778 seat: Option<SeatState>,
779 last_seen: Option<(u64, BTreeSet<String>)>,
780 considered: BTreeMap<String, String>,
784}
785
786fn input_fingerprint(task: &Task) -> String {
791 let mut v = serde_json::to_value(task).unwrap_or_default();
792 if let Some(o) = v.as_object_mut() {
793 o.remove("updated_at");
794 o.remove("hold_reason");
795 if let Some(ro) = o.get_mut("resume_override").and_then(|r| r.as_object_mut()) {
796 ro.remove("conductor_rehold");
797 }
798 }
799 v.to_string()
800}
801
802impl Conductor {
803 #[must_use]
805 pub fn new() -> Self {
806 Self::default()
807 }
808
809 fn settled(
814 considered: &BTreeMap<String, String>,
815 stalled: &[Task],
816 finished: &[Task],
817 ) -> BTreeSet<String> {
818 stalled
819 .iter()
820 .chain(finished)
821 .filter(|t| t.status == TaskStatus::Held)
822 .filter(|t| considered.get(&t.id) == Some(&input_fingerprint(t)))
823 .map(|t| t.id.clone())
824 .collect()
825 }
826
827 fn snapshot_with(
828 considered: &BTreeMap<String, String>,
829 queue: &Queue,
830 stalled: &[Task],
831 finished: &[Task],
832 ) -> (u64, BTreeSet<String>) {
833 let ids = stalled
834 .iter()
835 .chain(finished)
836 .map(|t| t.id.clone())
837 .collect();
838 let skip = Self::settled(considered, stalled, finished);
839 (queue.revision_excluding(&skip), ids)
840 }
841
842 fn snapshot(
843 &self,
844 queue: &Queue,
845 stalled: &[Task],
846 finished: &[Task],
847 ) -> (u64, BTreeSet<String>) {
848 Self::snapshot_with(&self.considered, queue, stalled, finished)
849 }
850
851 #[must_use]
868 pub fn worth_a_look(&self, queue: &Queue, stalled: &[Task], finished: &[Task]) -> bool {
869 self.last_seen.as_ref() != Some(&self.snapshot(queue, stalled, finished))
870 }
871
872 #[allow(clippy::too_many_arguments)]
876 pub async fn maybe_run(
877 &mut self,
878 cfg: &Config,
879 repo: &Path,
880 queue: &Queue,
881 questions: &Questions,
882 home: &Path,
883 queued: &[Task],
884 stalled: &[Task],
885 finished: &[Task],
886 max_attempts: usize,
887 ) {
888 if self.last_seen.as_ref() == Some(&self.snapshot(queue, stalled, finished)) {
889 return;
890 }
891 self.considered = stalled
894 .iter()
895 .chain(finished)
896 .filter(|t| t.status == TaskStatus::Held)
897 .map(|t| (t.id.clone(), input_fingerprint(t)))
898 .collect();
899 self.last_seen = Some(self.snapshot(queue, stalled, finished));
900 if let Err(e) = self
901 .run_once(
902 cfg,
903 repo,
904 queue,
905 questions,
906 home,
907 queued,
908 stalled,
909 finished,
910 max_attempts,
911 )
912 .await
913 {
914 tracing::warn!("conductor: {e:#}");
920 }
921 }
922
923 #[allow(clippy::too_many_arguments)]
924 async fn run_once(
925 &mut self,
926 cfg: &Config,
927 repo: &Path,
928 queue: &Queue,
929 questions: &Questions,
930 home: &Path,
931 queued: &[Task],
932 stalled: &[Task],
933 finished: &[Task],
934 max_attempts: usize,
935 ) -> Result<()> {
936 if queued.is_empty() && stalled.is_empty() && finished.is_empty() {
937 return Ok(());
938 }
939
940 let primary = cfg
941 .resolve_roles()
942 .context("resolving the conductor seat")?
943 .conductor;
944 let chain = match cfg.roles.conductor.as_ref() {
948 Some(c) if c.ids().len() > 1 => {
949 agent::pick_chain(&cfg.agents, Some(c), &agent::installed, "conductor")?
950 }
951 _ => vec![primary],
952 };
953
954 let runnable_views: Vec<prompt::ConductTask> =
955 queued.iter().map(|t| view(t, max_attempts)).collect();
956 let stalled_views: Vec<prompt::ConductTask> =
957 stalled.iter().map(|t| view(t, max_attempts)).collect();
958 let mut finished_views = Vec::with_capacity(finished.len());
959 for t in finished {
960 finished_views.push(finished_view(t, repo, max_attempts).await);
961 }
962
963 let body = prompt::with_overlay(
964 prompt::conduct(
965 &runnable_views,
966 &stalled_views,
967 &finished_views,
968 &cfg.graph.language,
969 ),
970 cfg.prompts.overlay(NODE),
971 );
972
973 let artifacts = home.join("conduct").join("artifacts");
974 let cache_dir = cfg.cache_dir();
977
978 let busy = Busy::mark(home);
980 let mut result: Result<Verdict> = Err(anyhow::anyhow!("no conductor agent ran"));
981 for spec in &chain {
982 let needs_new_seat = !matches!(&self.seat, Some(s) if s.agent == spec.id);
985 if needs_new_seat {
986 self.seat = Some(SeatState::new(SEAT, &spec.id, crate::rng::entropy()));
987 }
988 let seat = self.seat.as_mut().expect("just ensured a seat exists");
989 let stem = if std::ptr::eq(spec, &chain[0]) {
992 format!("turn-{}", seat.turns + 1)
993 } else {
994 format!("turn-{}-{}", seat.turns + 1, spec.id)
995 };
996 let inv = Invocation {
997 cwd: repo,
998 prompt: &body,
999 timeout: TURN_TIMEOUT,
1000 allow_write: false,
1003 unsandboxed: false,
1004 sessions: cfg.graph.sessions,
1005 artifacts: &artifacts,
1006 stem: &stem,
1007 run: NODE,
1008 node: NODE,
1009 cache_dir: cache_dir.as_deref(),
1010 attachments: &[],
1011 writable: &[],
1012 };
1013 let out = agent::invoke(spec, seat, &inv).await;
1014 if let Ok(body) = serde_json::to_string(&*seat) {
1017 let path = seat_path(home);
1018 if let Some(dir) = path.parent() {
1019 let _ = std::fs::create_dir_all(dir);
1020 }
1021 let _ = std::fs::write(path, body);
1022 }
1023 let advance = agent::chain_advances(&out);
1024 result = match out {
1025 Err(e) => Err(e.context("invoking the conductor")),
1026 Ok(out) if advance => Err(anyhow::anyhow!(
1027 "no usable reply (exit {:?}, timed out {})",
1028 out.exit_code,
1029 out.timed_out
1030 )),
1031 Ok(out) => verdict::extract_json(&out.text)
1032 .context("the conductor's reply could not be parsed"),
1033 };
1034 if result.is_ok() {
1035 break;
1036 }
1037 if chain.len() > 1 {
1038 tracing::warn!("conductor: `{}` failed, trying the next agent", spec.id);
1039 }
1040 }
1041 drop(busy);
1042 let mut verdict = result?;
1043 attach_facts(cfg, repo, queue, &mut verdict).await;
1044 apply(queue, questions, &verdict)
1045 }
1046}
1047
1048#[cfg(test)]
1049mod tests {
1050 use std::collections::BTreeMap;
1051
1052 use tempfile::tempdir;
1053
1054 use super::*;
1055 use crate::ask::{Answer, QuestionStatus};
1056 use crate::config::{AgentKind, AgentSpec, Graph};
1057 use crate::queue::Source;
1058
1059 fn mock_agent(dir: &Path, script: &str, env: BTreeMap<String, String>) -> AgentSpec {
1060 let path = dir.join("mock-conduct-agent.sh");
1061 std::fs::write(&path, script).expect("write mock");
1062 AgentSpec {
1063 id: "mock".to_owned(),
1064 kind: AgentKind::Command,
1065 model: None,
1066 command: vec!["sh".to_owned(), path.to_string_lossy().into_owned()],
1067 extra_args: Vec::new(),
1068 env,
1069 prompt_delivery: None,
1070 }
1071 }
1072
1073 fn config(spec: AgentSpec) -> Config {
1074 Config {
1075 agents: vec![spec],
1076 graph: Graph {
1077 language: "en".to_owned(),
1078 ..Graph::default()
1079 },
1080 ..Config::default()
1081 }
1082 }
1083
1084 fn task(title: &str) -> Task {
1085 Task::new(
1086 title.to_owned(),
1087 format!("do {title}"),
1088 std::path::PathBuf::from("."),
1089 Source::Human,
1090 )
1091 }
1092
1093 const BROKEN: &str = "#!/bin/sh\ncat >/dev/null\nexit 3\n";
1094 const GARBAGE: &str = "#!/bin/sh\ncat >/dev/null\nprintf 'not json at all\\n'\n";
1095
1096 fn env(reply: &str) -> BTreeMap<String, String> {
1097 BTreeMap::from([("MOCK_REPLY".to_owned(), reply.to_owned())])
1098 }
1099
1100 const REPLY: &str = "#!/bin/sh\ncat >/dev/null\nprintf '%s\\n' \"$MOCK_REPLY\"\n";
1101
1102 fn init_repo_with_branch(dir: &Path, branch: &str) {
1106 use crate::proc::Quiet as _;
1107 let run = |args: &[&str]| {
1108 let out = std::process::Command::new("git")
1109 .args(args)
1110 .current_dir(dir)
1111 .quiet()
1112 .output()
1113 .expect("spawn git");
1114 assert!(
1115 out.status.success(),
1116 "git {args:?} failed: {}",
1117 String::from_utf8_lossy(&out.stderr)
1118 );
1119 };
1120 run(&["init", "-b", "main"]);
1121 run(&["config", "user.name", "magi test"]);
1122 run(&["config", "user.email", "magi@example.com"]);
1123 std::fs::write(dir.join("README.md"), "# fixture\n").unwrap();
1124 run(&["add", "-A"]);
1125 run(&["commit", "-m", "init"]);
1126 run(&["checkout", "-b", branch]);
1127 std::fs::write(dir.join("change.txt"), "x\n").unwrap();
1128 run(&["add", "-A"]);
1129 run(&["commit", "-m", "candidate work"]);
1130 }
1131
1132 fn review_round_with_finding(
1133 round: usize,
1134 finding_id: &str,
1135 title: &str,
1136 addressed: &[&str],
1137 rejected: &[(&str, &str)],
1138 ) -> crate::run::ReviewRound {
1139 crate::run::ReviewRound {
1140 round,
1141 head: "deadbeef".to_owned(),
1142 verified_head: None,
1143 verified_at: None,
1144 reviews: vec![crate::run::ReviewRecord {
1145 attempts: 0,
1146 reviewer: 1,
1147 agent: "mock".to_owned(),
1148 summary: String::new(),
1149 findings: vec![crate::verdict::Finding {
1150 id: finding_id.to_owned(),
1151 severity: crate::verdict::Severity::Major,
1152 file: None,
1153 line: None,
1154 title: title.to_owned(),
1155 detail: String::new(),
1156 }],
1157 vote: None,
1158 failed: None,
1159 duration_ms: 0,
1160 }],
1161 e2e: Vec::new(),
1162 verify_retried: false,
1163 e2e_deferred: false,
1164 e2e_defer_reason: None,
1165 fix: Some(crate::run::FixRecord {
1166 agent: "mock".to_owned(),
1167 addressed: addressed.iter().map(|s| (*s).to_owned()).collect(),
1168 rejected: rejected
1169 .iter()
1170 .map(|(id, why)| crate::verdict::Rejection {
1171 id: (*id).to_owned(),
1172 why: (*why).to_owned(),
1173 })
1174 .collect(),
1175 notes: String::new(),
1176 committed: false,
1177 failed: None,
1178 duration_ms: 0,
1179 continuation: None,
1180 }),
1181 blocking: 1,
1182 answered: 1,
1183 expected: 1,
1184 clean: false,
1185 progressed: true,
1186 vote_split: false,
1187 reconsideration: Vec::new(),
1188 verdict: None,
1189 }
1190 }
1191
1192 #[test]
1193 fn outcome_for_carries_every_rounds_findings_and_the_branch_head() {
1194 crate::run::pin_test_home();
1195 let dir = tempdir().unwrap();
1196 let default_repo = dir.path().join("default");
1197 let task_repo = dir.path().join("task");
1198 std::fs::create_dir_all(&default_repo).unwrap();
1199 std::fs::create_dir_all(&task_repo).unwrap();
1200 init_repo_with_branch(&default_repo, "other-branch");
1201 init_repo_with_branch(&task_repo, "magi/f00d/A");
1202
1203 let mut config = Config::default();
1204 config.graph.review_rounds = 6;
1205 let mut state = crate::run::RunState::new(
1206 task_repo.clone(),
1207 "main".to_owned(),
1208 "deadbeef".to_owned(),
1209 "task".to_owned(),
1210 config,
1211 );
1212 state.status = crate::run::RunStatus::Blocked;
1213 state.candidates.push(crate::run::Candidate {
1214 index: 0,
1215 label: 'A',
1216 agent: "mock".to_owned(),
1217 branch: "magi/f00d/A".to_owned(),
1218 worktree: task_repo.clone(),
1219 summary: String::new(),
1220 stat: String::new(),
1221 files: 1,
1222 commits: 1,
1223 empty: false,
1224 failed: None,
1225 verified_noop: None,
1226 duration_ms: 0,
1227 folded: false,
1228 });
1229 state.tally = Some(crate::run::Tally {
1230 first_choice: std::collections::BTreeMap::new(),
1231 borda: std::collections::BTreeMap::new(),
1232 winner: 'A',
1233 rankings: 0,
1234 unanimous_initial: false,
1235 deliberated: false,
1236 changed_votes: 0,
1237 unanimous_final: false,
1238 tie_break: None,
1239 judges: 0,
1240 present: 0,
1241 quorum: 0,
1242 met_quorum: true,
1243 uncontested: Some("solo".to_owned()),
1244 });
1245 state.reviews = vec![
1246 review_round_with_finding(
1247 1,
1248 "R1-1-2",
1249 "answer content is dropped",
1250 &[],
1251 &[("R1-1-2", "the id leaving blocked_by is enough")],
1252 ),
1253 review_round_with_finding(2, "R2-1-3", "answer content is still dropped", &[], &[]),
1254 ];
1255 state.save().unwrap();
1256
1257 let mut t = task("outcome test");
1258 t.repo = task_repo;
1259 t.runs.push(state.id.clone());
1260
1261 let finished = tokio_test_block_on(finished_view(&t, &default_repo, 2));
1262 let outcome = finished.outcome;
1263
1264 assert!(outcome.unreadable.is_none());
1265 assert_eq!(outcome.run_status.as_deref(), Some("blocked"));
1266 assert_eq!(outcome.rounds_used, 2);
1267 assert_eq!(outcome.rounds_max, 6);
1268 assert_eq!(outcome.rounds.len(), 2);
1269 assert_eq!(outcome.rounds[0].findings[0].id, "R1-1-2");
1270 assert_eq!(outcome.rounds[0].rejected[0].id, "R1-1-2");
1271 assert!(outcome.rounds[1].addressed.is_empty());
1272 assert!(outcome.rounds[1].rejected.is_empty());
1273 assert_eq!(outcome.branch.as_deref(), Some("magi/f00d/A"));
1274 assert!(
1275 outcome.branch_head.is_some(),
1276 "a real branch must resolve a head commit: {outcome:?}"
1277 );
1278 }
1279
1280 fn tokio_test_block_on<F: std::future::Future>(f: F) -> F::Output {
1284 tokio::runtime::Builder::new_current_thread()
1285 .enable_all()
1286 .build()
1287 .unwrap()
1288 .block_on(f)
1289 }
1290
1291 #[test]
1292 fn view_carries_a_tasks_recorded_answers_into_the_conductor_prompt_input() {
1293 let mut t = task("answered");
1294 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
1295 let v = view(&t, 2);
1296 assert_eq!(v.answers.len(), 1);
1297 assert_eq!(v.answers[0].question, "Which backend?");
1298 assert_eq!(v.answers[0].answer, "SQLite");
1299 }
1300
1301 #[test]
1302 fn a_dependency_decision_blocks_the_task_and_leaves_priority_alone() {
1303 let dir = tempdir().unwrap();
1304 let queue = Queue::at(dir.path().join("queue"));
1305 let questions = Questions::at(dir.path().join("questions"));
1306 let mut a = task("a");
1307 a.priority = 9;
1308 queue.put(&mut a).unwrap();
1309
1310 let verdict = Verdict {
1311 decisions: vec![Decision {
1312 id: a.id.clone(),
1313 blocked_by: vec!["20260101-000000-dead".to_owned()],
1314 reason: Some("waits on the other task".to_owned()),
1315 recovery: None,
1316 question: None,
1317 choices: Vec::new(),
1318 }],
1319 };
1320 apply(&queue, &questions, &verdict).unwrap();
1321
1322 let back = queue.get(&a.id).unwrap();
1323 assert_eq!(back.status, TaskStatus::Blocked);
1324 assert_eq!(back.blocked_by, ["20260101-000000-dead"]);
1325 assert_eq!(
1326 back.priority, 9,
1327 "the conductor's reply cannot carry priority"
1328 );
1329 }
1330
1331 #[test]
1332 fn a_question_decision_files_one_and_blocks_on_its_id() {
1333 let dir = tempdir().unwrap();
1334 let queue = Queue::at(dir.path().join("queue"));
1335 let questions = Questions::at(dir.path().join("questions"));
1336 let mut t = task("ambiguous");
1337 queue.put(&mut t).unwrap();
1338
1339 let verdict = Verdict {
1340 decisions: vec![Decision {
1341 id: t.id.clone(),
1342 blocked_by: Vec::new(),
1343 reason: Some("which backend?".to_owned()),
1344 recovery: None,
1345 question: Some("Which storage backend?".to_owned()),
1346 choices: vec!["SQLite".to_owned(), "Redis".to_owned()],
1347 }],
1348 };
1349 apply(&queue, &questions, &verdict).unwrap();
1350
1351 let back = queue.get(&t.id).unwrap();
1352 assert_eq!(back.status, TaskStatus::Blocked);
1353 assert_eq!(back.blocked_by.len(), 1);
1354 let q = questions.get(&back.blocked_by[0]).unwrap();
1355 assert_eq!(q.summary, "Which storage backend?");
1356 assert_eq!(q.node, NODE);
1357 assert!(q.status.open());
1358 }
1359
1360 #[test]
1361 fn a_task_with_an_open_question_already_reuses_it_rather_than_filing_a_second_one() {
1362 let dir = tempdir().unwrap();
1363 let queue = Queue::at(dir.path().join("queue"));
1364 let questions = Questions::at(dir.path().join("questions"));
1365 let mut t = task("asked once");
1366 queue.put(&mut t).unwrap();
1367
1368 let decision = Decision {
1369 id: t.id.clone(),
1370 reason: Some("still deciding".to_owned()),
1371 question: Some("Which backend?".to_owned()),
1372 ..Decision::default()
1373 };
1374 apply(
1375 &queue,
1376 &questions,
1377 &Verdict {
1378 decisions: vec![decision.clone()],
1379 },
1380 )
1381 .unwrap();
1382 assert_eq!(questions.list().len(), 1);
1383 let first_question_id = queue.get(&t.id).unwrap().blocked_by[0].clone();
1384
1385 let mut released = queue.get(&t.id).unwrap();
1390 released.release();
1391 queue.put(&mut released).unwrap();
1392
1393 apply(
1394 &queue,
1395 &questions,
1396 &Verdict {
1397 decisions: vec![decision],
1398 },
1399 )
1400 .unwrap();
1401 assert_eq!(questions.list().len(), 1, "no duplicate question was filed");
1402 let after = queue.get(&t.id).unwrap();
1403 assert_eq!(
1404 after.blocked_by,
1405 [first_question_id],
1406 "the existing open question is reused, not replaced"
1407 );
1408 }
1409
1410 #[test]
1411 fn a_same_id_question_from_another_node_is_not_reused() {
1412 let dir = tempdir().unwrap();
1413 let queue = Queue::at(dir.path().join("queue"));
1414 let questions = Questions::at(dir.path().join("questions"));
1415 let mut t = task("must ask the conductor");
1416 queue.put(&mut t).unwrap();
1417
1418 let mut unrelated = Question::new(
1419 t.id.clone(),
1420 "review".to_owned(),
1421 "reviewer-1".to_owned(),
1422 "An unrelated review question".to_owned(),
1423 String::new(),
1424 Vec::new(),
1425 );
1426 questions.put(&mut unrelated).unwrap();
1427
1428 apply(
1429 &queue,
1430 &questions,
1431 &Verdict {
1432 decisions: vec![Decision {
1433 id: t.id.clone(),
1434 question: Some("Which backend?".to_owned()),
1435 ..Decision::default()
1436 }],
1437 },
1438 )
1439 .unwrap();
1440
1441 let blocked_by = &queue.get(&t.id).unwrap().blocked_by;
1442 assert_eq!(blocked_by.len(), 1);
1443 assert_ne!(blocked_by[0], unrelated.id);
1444 assert!(questions.get(&unrelated.id).unwrap().status.open());
1445 assert_eq!(questions.get(&blocked_by[0]).unwrap().node, NODE);
1446 }
1447
1448 #[test]
1449 fn answering_the_question_lets_the_resolver_clear_the_block_with_the_answer_kept() {
1450 let dir = tempdir().unwrap();
1451 let queue = Queue::at(dir.path().join("queue"));
1452 let questions = Questions::at(dir.path().join("questions"));
1453 let mut t = task("waits on an answer");
1454 queue.put(&mut t).unwrap();
1455
1456 apply(
1457 &queue,
1458 &questions,
1459 &Verdict {
1460 decisions: vec![Decision {
1461 id: t.id.clone(),
1462 blocked_by: Vec::new(),
1463 reason: None,
1464 recovery: None,
1465 question: Some("Which backend?".to_owned()),
1466 choices: Vec::new(),
1467 }],
1468 },
1469 )
1470 .unwrap();
1471 let blocked = queue.get(&t.id).unwrap();
1472 let question_id = blocked.blocked_by[0].clone();
1473
1474 let mut q = questions.get(&question_id).unwrap();
1475 q.answer(Answer::Text("SQLite".to_owned())).unwrap();
1476 questions.put(&mut q).unwrap();
1477 assert_eq!(q.status, QuestionStatus::Answered);
1478
1479 let mut task_after = queue.get(&t.id).unwrap();
1483 task_after.record_answer(q.summary.clone(), "SQLite".to_owned());
1484 task_after.unblock(&question_id);
1485 assert_eq!(task_after.status, TaskStatus::Queued);
1486 assert_eq!(task_after.answers[0].answer, "SQLite");
1487 }
1488
1489 #[test]
1490 fn a_stalled_task_can_be_requeued_or_held() {
1491 let dir = tempdir().unwrap();
1492 let queue = Queue::at(dir.path().join("queue"));
1493 let questions = Questions::at(dir.path().join("questions"));
1494
1495 let mut requeue_me = task("stuck a");
1496 requeue_me.start("run-1".to_owned());
1497 queue.put(&mut requeue_me).unwrap();
1498
1499 let mut hold_me = task("stuck b");
1500 hold_me.start("run-2".to_owned());
1501 queue.put(&mut hold_me).unwrap();
1502
1503 apply(
1504 &queue,
1505 &questions,
1506 &Verdict {
1507 decisions: vec![
1508 Decision {
1509 id: requeue_me.id.clone(),
1510 recovery: Some(Recovery::Requeue),
1511 ..Decision::default()
1512 },
1513 Decision {
1514 id: hold_me.id.clone(),
1515 recovery: Some(Recovery::Hold),
1516 reason: Some("looks broken".to_owned()),
1517 ..Decision::default()
1518 },
1519 ],
1520 },
1521 )
1522 .unwrap();
1523
1524 let requeued = queue.get(&requeue_me.id).unwrap();
1525 assert_eq!(requeued.status, TaskStatus::Queued);
1526 assert_eq!(requeued.attempts, 0);
1527
1528 let held = queue.get(&hold_me.id).unwrap();
1529 assert_eq!(held.status, TaskStatus::Held);
1530 assert_eq!(held.hold_reason.as_deref(), Some("looks broken"));
1531 }
1532
1533 #[test]
1534 fn a_machine_held_task_asked_about_restores_to_held_once_answered() {
1535 let dir = tempdir().unwrap();
1540 let queue = Queue::at(dir.path().join("queue"));
1541 let questions = Questions::at(dir.path().join("questions"));
1542 let mut t = task("held out of attempts");
1543 t.hold_machine(Some("out of attempts".to_owned()));
1544 queue.put(&mut t).unwrap();
1545
1546 apply(
1547 &queue,
1548 &questions,
1549 &Verdict {
1550 decisions: vec![Decision {
1551 id: t.id.clone(),
1552 reason: Some("what should happen to this one?".to_owned()),
1553 question: Some("Hold it, or try again?".to_owned()),
1554 ..Decision::default()
1555 }],
1556 },
1557 )
1558 .unwrap();
1559 let blocked = queue.get(&t.id).unwrap();
1560 assert_eq!(blocked.status, TaskStatus::Blocked);
1561 let question_id = blocked.blocked_by[0].clone();
1562
1563 let mut q = questions.get(&question_id).unwrap();
1564 q.answer(Answer::Text("leave it held".to_owned())).unwrap();
1565 questions.put(&mut q).unwrap();
1566
1567 let mut after = queue.get(&t.id).unwrap();
1569 after.record_answer(q.summary.clone(), "leave it held".to_owned());
1570 after.unblock(&question_id);
1571 assert_eq!(
1572 after.status,
1573 TaskStatus::Held,
1574 "must not fall back to queued"
1575 );
1576 assert_eq!(after.hold_reason.as_deref(), Some("out of attempts"));
1577 }
1578
1579 #[test]
1580 fn a_reaffirmed_hold_with_no_new_reason_is_not_silently_auto_released_by_triage() {
1581 let dir = tempdir().unwrap();
1591 let queue = Queue::at(dir.path().join("queue"));
1592 let questions = Questions::at(dir.path().join("questions"));
1593 let mut t = task("disk pressure, then reconsidered");
1594 t.hold_machine(Some(
1595 "not enough free space to start a run: 10 bytes free, 100 required by \
1596 `[disk] min_free_bytes`"
1597 .to_owned(),
1598 ));
1599 t.record_answer(
1600 "How should this be handled?".to_owned(),
1601 "keep it held, a human will look at it later".to_owned(),
1602 );
1603 queue.put(&mut t).unwrap();
1604
1605 apply(
1606 &queue,
1607 &questions,
1608 &Verdict {
1609 decisions: vec![Decision {
1610 id: t.id.clone(),
1611 recovery: Some(Recovery::Hold),
1612 ..Decision::default()
1613 }],
1614 },
1615 )
1616 .unwrap();
1617
1618 let after = queue.get(&t.id).unwrap();
1619 assert_eq!(after.status, TaskStatus::Held);
1620 assert!(
1621 !after
1622 .hold_reason
1623 .as_deref()
1624 .unwrap_or_default()
1625 .starts_with("not enough free space"),
1626 "the stale disk-pressure text must not survive a reconfirmed hold: {:?}",
1627 after.hold_reason
1628 );
1629
1630 let cfg_dir = tempdir().unwrap();
1633 let config = cfg_dir.path().join("magi.toml");
1634 std::fs::write(&config, "[disk]\nmin_free_bytes = 0\n").unwrap();
1635 let report =
1636 crate::triage::run_once(&queue, &questions, Some(&config), jiff::Timestamp::now());
1637 assert!(report.resumed.is_empty(), "must not be auto-released");
1638 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
1639 }
1640
1641 #[test]
1642 fn a_conductor_rehold_after_a_resume_answer_is_not_asked_again_identically() {
1643 let dir = tempdir().unwrap();
1644 let queue = Queue::at(dir.path().join("queue"));
1645 let questions = Questions::at(dir.path().join("questions"));
1646 let config = dir.path().join("magi.toml");
1647 std::fs::write(&config, "[disk]\nmin_free_bytes = 0\n").unwrap();
1648 let now = jiff::Timestamp::now();
1649 let triage = || crate::triage::run_once(&queue, &questions, Some(&config), now);
1650 let open = || {
1651 questions
1652 .list()
1653 .into_iter()
1654 .filter(|q| q.node == "triage" && q.status.open())
1655 .collect::<Vec<_>>()
1656 };
1657 let hold = Decision {
1658 recovery: Some(Recovery::Hold),
1659 reason: Some("waiting on manual worktree cleanup".to_owned()),
1660 ..Decision::default()
1661 };
1662
1663 let mut t = task("looping hold");
1664 t.hold_machine(Some("waiting on manual worktree cleanup".to_owned()));
1665 queue.put(&mut t).unwrap();
1666 let hold = Decision {
1667 id: t.id.clone(),
1668 ..hold
1669 };
1670
1671 assert_eq!(triage().asked.len(), 1);
1673 let first = open().remove(0);
1674 let mut q = questions.get(&first.id).unwrap();
1675 let resume = q.choices[0].clone();
1676 q.answer(Answer::Choice(resume)).unwrap();
1677 questions.put(&mut q).unwrap();
1678 assert_eq!(triage().answered.len(), 1);
1679 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
1680
1681 apply(
1683 &queue,
1684 &questions,
1685 &Verdict {
1686 decisions: vec![hold.clone()],
1687 },
1688 )
1689 .unwrap();
1690 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
1691
1692 assert_eq!(triage().asked.len(), 1);
1694 let second = open().remove(0);
1695 assert_ne!(second.summary, first.summary);
1696 assert_ne!(second.choices, first.choices);
1697 assert!(second.detail.contains("waiting on manual worktree cleanup"));
1698 assert!(triage().asked.is_empty(), "no duplicate question");
1699 assert_eq!(open().len(), 1);
1700
1701 let mut q = questions.get(&second.id).unwrap();
1703 let force = q.choices[0].clone();
1704 q.answer(Answer::Choice(force)).unwrap();
1705 questions.put(&mut q).unwrap();
1706 assert_eq!(triage().answered.len(), 1);
1707 apply(
1708 &queue,
1709 &questions,
1710 &Verdict {
1711 decisions: vec![hold],
1712 },
1713 )
1714 .unwrap();
1715 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
1716 }
1717
1718 #[test]
1719 fn a_runnable_task_can_be_held_directly_without_a_question() {
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("already answered, should stay put");
1724 queue.put(&mut t).unwrap();
1725
1726 apply(
1727 &queue,
1728 &questions,
1729 &Verdict {
1730 decisions: vec![Decision {
1731 id: t.id.clone(),
1732 recovery: Some(Recovery::Hold),
1733 reason: Some("operator already said keep this held".to_owned()),
1734 ..Decision::default()
1735 }],
1736 },
1737 )
1738 .unwrap();
1739
1740 let after = queue.get(&t.id).unwrap();
1741 assert_eq!(after.status, TaskStatus::Held);
1742 assert_eq!(after.hold_source, Some(crate::queue::HoldSource::Machine));
1743 }
1744
1745 #[test]
1746 fn done_recovery_closes_a_held_task_whose_goal_is_already_met() {
1747 let dir = tempdir().unwrap();
1753 let queue = Queue::at(dir.path().join("queue"));
1754 let questions = Questions::at(dir.path().join("questions"));
1755 let mut t = task("already merged by hand");
1756 t.hold_machine(Some("branch survived, awaiting a decision".to_owned()));
1757 t.record_answer(
1758 "Handle this one?".to_owned(),
1759 "already merged and cleaned up, close it".to_owned(),
1760 );
1761 queue.put(&mut t).unwrap();
1762
1763 apply(
1764 &queue,
1765 &questions,
1766 &Verdict {
1767 decisions: vec![Decision {
1768 id: t.id.clone(),
1769 recovery: Some(Recovery::Done),
1770 reason: Some("operator confirmed this already landed".to_owned()),
1771 ..Decision::default()
1772 }],
1773 },
1774 )
1775 .unwrap();
1776
1777 let after = queue.get(&t.id).unwrap();
1778 assert_eq!(after.status, TaskStatus::Done);
1779 assert!(after.hold_reason.is_none());
1780 assert_eq!(after.answers.len(), 1, "the record of why is kept");
1781 }
1782
1783 #[test]
1784 fn done_recovery_is_ignored_for_a_runnable_or_running_task() {
1785 let dir = tempdir().unwrap();
1786 let queue = Queue::at(dir.path().join("queue"));
1787 let questions = Questions::at(dir.path().join("questions"));
1788
1789 let mut queued = task("never ran yet");
1790 queue.put(&mut queued).unwrap();
1791
1792 let mut running = task("mid-run");
1793 running.start("run-1".to_owned());
1794 queue.put(&mut running).unwrap();
1795
1796 for id in [queued.id.clone(), running.id.clone()] {
1797 apply(
1798 &queue,
1799 &questions,
1800 &Verdict {
1801 decisions: vec![Decision {
1802 id,
1803 recovery: Some(Recovery::Done),
1804 ..Decision::default()
1805 }],
1806 },
1807 )
1808 .unwrap();
1809 }
1810
1811 assert_eq!(queue.get(&queued.id).unwrap().status, TaskStatus::Queued);
1812 assert_eq!(queue.get(&running.id).unwrap().status, TaskStatus::Running);
1813 }
1814
1815 #[test]
1816 fn a_question_after_two_settled_answers_is_still_filed_and_blocks() {
1817 let dir = tempdir().unwrap();
1820 let queue = Queue::at(dir.path().join("queue"));
1821 let questions = Questions::at(dir.path().join("questions"));
1822 let mut t = task("asked about repeatedly");
1823 t.hold_machine(Some("out of attempts".to_owned()));
1824 t.record_answer("Handle this one? (1)".to_owned(), "not yet".to_owned());
1825 t.record_answer(
1826 "Handle this one? (2)".to_owned(),
1827 "still not yet".to_owned(),
1828 );
1829 queue.put(&mut t).unwrap();
1830 assert_eq!(questions.list().len(), 0);
1831
1832 let verdict = Verdict {
1833 decisions: vec![Decision {
1834 id: t.id.clone(),
1835 question: Some("Branch conflicts with origin/main, how do we proceed?".to_owned()),
1836 ..Decision::default()
1837 }],
1838 };
1839 apply(&queue, &questions, &verdict).unwrap();
1840
1841 let filed = questions.list();
1842 assert_eq!(filed.len(), 1, "the question was filed");
1843 assert_eq!(
1844 filed[0].summary,
1845 "Branch conflicts with origin/main, how do we proceed?"
1846 );
1847 let deputy = filed[0]
1848 .deputy
1849 .as_ref()
1850 .expect("the wait is handed to a deputy");
1851 assert!(deputy.brief.contains(&t.id), "{}", deputy.brief);
1852 assert_eq!(
1853 deputy.starts, 0,
1854 "filing never starts anything: the loop does not wait"
1855 );
1856 assert!(filed[0].status.open());
1857 assert_eq!(filed[0].node, NODE);
1858 let after = queue.get(&t.id).unwrap();
1859 assert_eq!(after.status, TaskStatus::Blocked);
1860 assert_eq!(after.blocked_by, vec![filed[0].id.clone()]);
1861 assert_eq!(after.answers.len(), 2, "the prior answers are untouched");
1862 assert!(
1863 !after
1864 .hold_reason
1865 .clone()
1866 .unwrap_or_default()
1867 .contains("conduct tried to ask"),
1868 "no hold was applied"
1869 );
1870
1871 apply(&queue, &questions, &verdict).unwrap();
1872 let again = questions.list();
1873 assert_eq!(again.len(), 1, "the open question is reused");
1874 assert_eq!(again[0].id, filed[0].id);
1875 }
1876
1877 #[test]
1878 fn a_second_conductor_question_is_still_allowed_after_one_settled_answer() {
1879 let dir = tempdir().unwrap();
1880 let queue = Queue::at(dir.path().join("queue"));
1881 let questions = Questions::at(dir.path().join("questions"));
1882 let mut t = task("asked about once already");
1883 t.hold_machine(Some("out of attempts".to_owned()));
1884 t.record_answer("Handle this one?".to_owned(), "not yet".to_owned());
1885 queue.put(&mut t).unwrap();
1886
1887 apply(
1888 &queue,
1889 &questions,
1890 &Verdict {
1891 decisions: vec![Decision {
1892 id: t.id.clone(),
1893 question: Some("Still not sure - now what?".to_owned()),
1894 ..Decision::default()
1895 }],
1896 },
1897 )
1898 .unwrap();
1899
1900 assert_eq!(questions.list().len(), 1, "the second question was filed");
1901 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
1902 }
1903
1904 #[test]
1905 fn a_held_task_with_an_open_triage_question_is_left_to_triage() {
1906 let dir = tempdir().unwrap();
1912 let queue = Queue::at(dir.path().join("queue"));
1913 let questions = Questions::at(dir.path().join("questions"));
1914 let mut t = task("held, triage already asking about it");
1915 t.hold_machine(Some("cause unclear".to_owned()));
1916 queue.put(&mut t).unwrap();
1917
1918 let mut triage_q = Question::new(
1919 t.id.clone(),
1920 crate::triage::NODE.to_owned(),
1921 "triage".to_owned(),
1922 "Still needed?".to_owned(),
1923 String::new(),
1924 vec![
1925 "resume".to_owned(),
1926 "not yet".to_owned(),
1927 "discard".to_owned(),
1928 ],
1929 );
1930 questions.put(&mut triage_q).unwrap();
1931
1932 for decision in [
1933 Decision {
1934 id: t.id.clone(),
1935 question: Some("what now?".to_owned()),
1936 ..Decision::default()
1937 },
1938 Decision {
1939 id: t.id.clone(),
1940 recovery: Some(Recovery::Requeue),
1941 ..Decision::default()
1942 },
1943 ] {
1944 apply(
1945 &queue,
1946 &questions,
1947 &Verdict {
1948 decisions: vec![decision],
1949 },
1950 )
1951 .unwrap();
1952 }
1953
1954 let after = queue.get(&t.id).unwrap();
1955 assert_eq!(
1956 after.status,
1957 TaskStatus::Held,
1958 "triage still owns this hold"
1959 );
1960 assert!(after.blocked_by.is_empty());
1961 assert_eq!(
1962 questions.list().len(),
1963 1,
1964 "no second, conductor-owned question was filed"
1965 );
1966 }
1967
1968 #[test]
1969 fn a_held_task_with_an_answered_but_unapplied_triage_question_is_still_left_alone() {
1970 let dir = tempdir().unwrap();
1978 let queue = Queue::at(dir.path().join("queue"));
1979 let questions = Questions::at(dir.path().join("questions"));
1980 let mut t = task("held, triage question answered but not yet applied");
1981 t.hold_machine(Some("cause unclear".to_owned()));
1982 queue.put(&mut t).unwrap();
1983
1984 let mut triage_q = Question::new(
1985 t.id.clone(),
1986 crate::triage::NODE.to_owned(),
1987 "triage".to_owned(),
1988 "Still needed?".to_owned(),
1989 String::new(),
1990 vec![
1991 "resume".to_owned(),
1992 "not yet".to_owned(),
1993 "discard".to_owned(),
1994 ],
1995 );
1996 questions.put(&mut triage_q).unwrap();
1997 triage_q
1998 .answer(Answer::Choice("not yet".to_owned()))
1999 .unwrap();
2000 questions.put(&mut triage_q).unwrap();
2001 assert!(!triage_q.status.open());
2002
2003 apply(
2004 &queue,
2005 &questions,
2006 &Verdict {
2007 decisions: vec![Decision {
2008 id: t.id.clone(),
2009 question: Some("what now?".to_owned()),
2010 ..Decision::default()
2011 }],
2012 },
2013 )
2014 .unwrap();
2015
2016 let after = queue.get(&t.id).unwrap();
2017 assert_eq!(
2018 after.status,
2019 TaskStatus::Held,
2020 "triage's own answer is not yet applied - conduct must wait"
2021 );
2022 assert_eq!(
2023 questions.list().len(),
2024 1,
2025 "no conductor question was filed over the pending triage answer"
2026 );
2027 }
2028
2029 #[test]
2030 fn manual_hold_rejects_hostile_or_stale_conductor_recovery() {
2031 let dir = tempdir().unwrap();
2032 let queue = Queue::at(dir.path().join("queue"));
2033 let questions = Questions::at(dir.path().join("questions"));
2034 let mut held = task("manual recovery");
2035 held.priority = 300;
2036 held.runs.push("run20260912-224242-daf5".to_owned());
2037 held.hold_manual(Some(
2038 "active manual recovery run20260912-224242-daf5".to_owned(),
2039 ));
2040 queue.put(&mut held).unwrap();
2041
2042 for decision in [
2046 Decision {
2047 id: held.id.clone(),
2048 recovery: Some(Recovery::Requeue),
2049 ..Decision::default()
2050 },
2051 Decision {
2052 id: held.id.clone(),
2053 recovery: Some(Recovery::Hold),
2054 reason: Some("stale replacement reason".to_owned()),
2055 ..Decision::default()
2056 },
2057 Decision {
2058 id: held.id.clone(),
2059 recovery: Some(Recovery::Review),
2060 ..Decision::default()
2061 },
2062 Decision {
2063 id: held.id.clone(),
2064 blocked_by: vec!["other-task".to_owned()],
2065 question: Some("retry now?".to_owned()),
2066 ..Decision::default()
2067 },
2068 ] {
2069 apply(
2070 &queue,
2071 &questions,
2072 &Verdict {
2073 decisions: vec![decision],
2074 },
2075 )
2076 .unwrap();
2077 }
2078
2079 let after = queue.get(&held.id).unwrap();
2080 assert_eq!(after.status, TaskStatus::Held);
2081 assert!(after.operator_held());
2082 assert_eq!(after.priority, 300);
2083 assert_eq!(after.runs, ["run20260912-224242-daf5"]);
2084 assert_eq!(
2085 after.hold_reason.as_deref(),
2086 Some("active manual recovery run20260912-224242-daf5")
2087 );
2088 assert!(after.blocked_by.is_empty());
2089 assert!(questions.list().is_empty());
2090 assert!(
2091 queue.next_runnable().is_none(),
2092 "must not dispatch a duplicate"
2093 );
2094 }
2095
2096 #[test]
2097 fn machine_holds_remain_recoverable_and_manual_release_is_authorization() {
2098 let dir = tempdir().unwrap();
2099 let queue = Queue::at(dir.path().join("queue"));
2100 let questions = Questions::at(dir.path().join("questions"));
2101
2102 let mut automatic = task("disk gate");
2103 automatic.hold_machine(Some("disk full".to_owned()));
2104 queue.put(&mut automatic).unwrap();
2105 let requeue = || Verdict {
2106 decisions: vec![Decision {
2107 id: automatic.id.clone(),
2108 recovery: Some(Recovery::Requeue),
2109 ..Decision::default()
2110 }],
2111 };
2112 apply(&queue, &questions, &requeue()).unwrap();
2113 assert_eq!(queue.get(&automatic.id).unwrap().status, TaskStatus::Queued);
2114
2115 let mut manual = task("operator gate");
2116 manual.hold_manual(Some("wait for operator".to_owned()));
2117 queue.put(&mut manual).unwrap();
2118 apply(
2119 &queue,
2120 &questions,
2121 &Verdict {
2122 decisions: vec![Decision {
2123 id: manual.id.clone(),
2124 recovery: Some(Recovery::Requeue),
2125 ..Decision::default()
2126 }],
2127 },
2128 )
2129 .unwrap();
2130 assert_eq!(queue.get(&manual.id).unwrap().status, TaskStatus::Held);
2131
2132 let mut released = queue.get(&manual.id).unwrap();
2135 released.release();
2136 queue.put(&mut released).unwrap();
2137 assert_eq!(queue.get(&manual.id).unwrap().status, TaskStatus::Queued);
2138 }
2139
2140 #[test]
2141 fn legacy_reasoned_hold_is_protected_without_losing_its_metadata() {
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 legacy = task("old explicit hold");
2146 legacy.status = TaskStatus::Held;
2147 legacy.hold_reason = Some("manual recovery already active".to_owned());
2148 legacy.hold_source = None;
2149 legacy.blocked_by = vec!["dependency".to_owned()];
2150 queue.put(&mut legacy).unwrap();
2151
2152 apply(
2153 &queue,
2154 &questions,
2155 &Verdict {
2156 decisions: vec![Decision {
2157 id: legacy.id.clone(),
2158 recovery: Some(Recovery::Requeue),
2159 ..Decision::default()
2160 }],
2161 },
2162 )
2163 .unwrap();
2164
2165 let after = queue.get(&legacy.id).unwrap();
2166 assert_eq!(after.status, TaskStatus::Held);
2167 assert_eq!(after.hold_source, None);
2168 assert_eq!(after.hold_reason, legacy.hold_reason);
2169 assert_eq!(after.blocked_by, legacy.blocked_by);
2170 }
2171
2172 #[test]
2173 fn review_recovery_is_a_no_op_without_a_survivable_branch() {
2174 crate::run::pin_test_home();
2180 let dir = tempdir().unwrap();
2181 let queue = Queue::at(dir.path().join("queue"));
2182 let questions = Questions::at(dir.path().join("questions"));
2183 let mut t = task("blocked with no readable run");
2184 t.start("20260101-000000-dead".to_owned()); t.fail("blocked", 5);
2186 queue.put(&mut t).unwrap();
2187
2188 apply(
2189 &queue,
2190 &questions,
2191 &Verdict {
2192 decisions: vec![Decision {
2193 id: t.id.clone(),
2194 recovery: Some(Recovery::Review),
2195 ..Decision::default()
2196 }],
2197 },
2198 )
2199 .unwrap();
2200
2201 let after = queue.get(&t.id).unwrap();
2202 assert_eq!(
2203 after.status,
2204 TaskStatus::Failed,
2205 "with nothing to reopen, the decision is dropped rather than guessed at"
2206 );
2207 assert!(after.review_branch.is_none());
2208 }
2209
2210 #[test]
2211 fn requeue_and_review_recovery_are_ignored_for_a_runnable_task() {
2212 let dir = tempdir().unwrap();
2216 let queue = Queue::at(dir.path().join("queue"));
2217 let questions = Questions::at(dir.path().join("questions"));
2218
2219 for recovery in [Recovery::Requeue, Recovery::Review] {
2220 let mut t = task("ordinary");
2221 queue.put(&mut t).unwrap();
2222
2223 apply(
2224 &queue,
2225 &questions,
2226 &Verdict {
2227 decisions: vec![Decision {
2228 id: t.id.clone(),
2229 recovery: Some(recovery),
2230 ..Decision::default()
2231 }],
2232 },
2233 )
2234 .unwrap();
2235
2236 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
2237 }
2238 }
2239
2240 #[tokio::test]
2241 async fn a_broken_agent_leaves_the_queue_untouched_and_does_not_error() {
2242 let dir = tempdir().unwrap();
2243 let cfg = config(mock_agent(dir.path(), BROKEN, BTreeMap::new()));
2244 let queue = Queue::at(dir.path().join("queue"));
2245 let questions = Questions::at(dir.path().join("questions"));
2246 let mut t = task("normal");
2247 queue.put(&mut t).unwrap();
2248
2249 let mut conductor = Conductor::new();
2250 conductor
2251 .maybe_run(
2252 &cfg,
2253 dir.path(),
2254 &queue,
2255 &questions,
2256 dir.path(),
2257 &[t.clone()],
2258 &[],
2259 &[],
2260 2,
2261 )
2262 .await;
2263
2264 assert_eq!(
2265 queue.get(&t.id).unwrap().status,
2266 TaskStatus::Queued,
2267 "a failed invocation must change nothing"
2268 );
2269 assert!(
2270 queue.next_runnable().is_some(),
2271 "the loop must still be able to take the next task"
2272 );
2273 }
2274
2275 #[tokio::test]
2276 async fn a_reply_with_no_json_leaves_the_queue_untouched() {
2277 let dir = tempdir().unwrap();
2278 let cfg = config(mock_agent(dir.path(), GARBAGE, BTreeMap::new()));
2279 let queue = Queue::at(dir.path().join("queue"));
2280 let questions = Questions::at(dir.path().join("questions"));
2281 let mut t = task("normal");
2282 queue.put(&mut t).unwrap();
2283
2284 let mut conductor = Conductor::new();
2285 conductor
2286 .maybe_run(
2287 &cfg,
2288 dir.path(),
2289 &queue,
2290 &questions,
2291 dir.path(),
2292 &[t.clone()],
2293 &[],
2294 &[],
2295 2,
2296 )
2297 .await;
2298
2299 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
2300 }
2301
2302 #[tokio::test]
2303 async fn a_conductor_chain_falls_to_the_next_agent_once_each() {
2304 let dir = tempdir().unwrap();
2305 let mut t = task("chained");
2306 let reply = format!(
2307 "{{\"decisions\":[{{\"id\":\"{}\",\"blocked_by\":[\"x\"],\"reason\":\"why\"}}]}}",
2308 t.id
2309 );
2310 let counted = |id: &str, tail: &str| {
2311 let calls = dir.path().join(format!("{id}.calls"));
2312 let path = dir.path().join(format!("{id}.sh"));
2313 std::fs::write(
2314 &path,
2315 format!(
2316 "#!/bin/sh\ncat >/dev/null\necho x >> '{}'\n{tail}\n",
2317 calls.display()
2318 ),
2319 )
2320 .unwrap();
2321 AgentSpec {
2322 id: id.to_owned(),
2323 kind: AgentKind::Command,
2324 model: None,
2325 command: vec!["sh".to_owned(), path.to_string_lossy().into_owned()],
2326 extra_args: Vec::new(),
2327 env: BTreeMap::new(),
2328 prompt_delivery: None,
2329 }
2330 };
2331 let n_calls = |id: &str| {
2332 std::fs::read_to_string(dir.path().join(format!("{id}.calls")))
2333 .map_or(0, |s| s.lines().count())
2334 };
2335 let mut cfg = config(counted("a", "exit 3"));
2336 cfg.agents = vec![
2337 counted("a", "exit 3"),
2338 counted("b", &format!("printf '%s' '{reply}'")),
2339 ];
2340 cfg.roles.conductor = Some(crate::config::AgentChoice::Chain(vec![
2341 "a".into(),
2342 "b".into(),
2343 "a".into(),
2344 ]));
2345 let queue = Queue::at(dir.path().join("queue"));
2346 let questions = Questions::at(dir.path().join("questions"));
2347 queue.put(&mut t).unwrap();
2348
2349 let mut conductor = Conductor::new();
2350 conductor
2351 .maybe_run(
2352 &cfg,
2353 dir.path(),
2354 &queue,
2355 &questions,
2356 dir.path(),
2357 &[t.clone()],
2358 &[],
2359 &[],
2360 2,
2361 )
2362 .await;
2363
2364 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
2365 assert_eq!(n_calls("a"), 1, "each id is tried once");
2366 assert_eq!(n_calls("b"), 1);
2367 let saved = std::fs::read_to_string(seat_path(dir.path())).unwrap();
2368 assert!(
2369 saved.contains("\"b\""),
2370 "the seat on disk is the one that ran: {saved}"
2371 );
2372 }
2373
2374 #[tokio::test]
2375 async fn json_survives_code_fences_and_a_preamble() {
2376 let dir = tempdir().unwrap();
2377 let mut t = task("fenced");
2378 let reply = format!(
2379 "Sure, here is my decision.\n\n```json\n{{\"decisions\":[{{\"id\":\"{}\",\
2380 \"blocked_by\":[\"x\"],\"reason\":\"why\"}}]}}\n```\n",
2381 t.id
2382 );
2383 let cfg = config(mock_agent(dir.path(), REPLY, env(&reply)));
2384 let queue = Queue::at(dir.path().join("queue"));
2385 let questions = Questions::at(dir.path().join("questions"));
2386 queue.put(&mut t).unwrap();
2387
2388 let mut conductor = Conductor::new();
2389 conductor
2390 .maybe_run(
2391 &cfg,
2392 dir.path(),
2393 &queue,
2394 &questions,
2395 dir.path(),
2396 &[t.clone()],
2397 &[],
2398 &[],
2399 2,
2400 )
2401 .await;
2402
2403 let back = queue.get(&t.id).unwrap();
2404 assert_eq!(back.status, TaskStatus::Blocked);
2405 assert_eq!(back.blocked_by, ["x"]);
2406 }
2407
2408 #[tokio::test]
2409 async fn the_conductor_is_not_called_again_when_nothing_worth_looking_at_has_changed() {
2410 let dir = tempdir().unwrap();
2413 let cfg = config(mock_agent(dir.path(), REPLY, env("{\"decisions\":[]}")));
2414 let queue = Queue::at(dir.path().join("queue"));
2415 let questions = Questions::at(dir.path().join("questions"));
2416 let mut t = task("stable");
2417 queue.put(&mut t).unwrap();
2418 let artifacts = dir.path().join("conduct").join("artifacts");
2419 let turn = |n: usize| artifacts.join(format!("turn-{n}.out"));
2420
2421 let mut conductor = Conductor::new();
2422 conductor
2423 .maybe_run(
2424 &cfg,
2425 dir.path(),
2426 &queue,
2427 &questions,
2428 dir.path(),
2429 &[t.clone()],
2430 &[],
2431 &[],
2432 2,
2433 )
2434 .await;
2435 assert!(turn(1).is_file(), "the first cycle must call the conductor");
2436
2437 conductor
2438 .maybe_run(
2439 &cfg,
2440 dir.path(),
2441 &queue,
2442 &questions,
2443 dir.path(),
2444 &[t.clone()],
2445 &[],
2446 &[],
2447 2,
2448 )
2449 .await;
2450 assert!(
2451 !turn(2).is_file(),
2452 "an unchanged revision and an unchanged stalled/finished set must not call the \
2453 conductor twice"
2454 );
2455
2456 t.priority = 1;
2458 queue.put(&mut t).unwrap();
2459 conductor
2460 .maybe_run(
2461 &cfg,
2462 dir.path(),
2463 &queue,
2464 &questions,
2465 dir.path(),
2466 &[t.clone()],
2467 &[],
2468 &[],
2469 2,
2470 )
2471 .await;
2472 assert!(turn(2).is_file(), "a moved revision calls it again");
2473 }
2474
2475 #[tokio::test]
2476 async fn a_task_turning_stalled_calls_the_conductor_again_despite_an_unchanged_revision() {
2477 let dir = tempdir().unwrap();
2483 let cfg = config(mock_agent(dir.path(), REPLY, env("{\"decisions\":[]}")));
2484 let queue = Queue::at(dir.path().join("queue"));
2485 let questions = Questions::at(dir.path().join("questions"));
2486 let mut t = task("quiet");
2487 queue.put(&mut t).unwrap();
2488 let artifacts = dir.path().join("conduct").join("artifacts");
2489 let turn = |n: usize| artifacts.join(format!("turn-{n}.out"));
2490
2491 let mut conductor = Conductor::new();
2492 conductor
2493 .maybe_run(
2494 &cfg,
2495 dir.path(),
2496 &queue,
2497 &questions,
2498 dir.path(),
2499 &[t.clone()],
2500 &[],
2501 &[],
2502 2,
2503 )
2504 .await;
2505 assert!(turn(1).is_file());
2506
2507 conductor
2508 .maybe_run(
2509 &cfg,
2510 dir.path(),
2511 &queue,
2512 &questions,
2513 dir.path(),
2514 &[],
2515 &[t.clone()],
2516 &[],
2517 2,
2518 )
2519 .await;
2520 assert!(
2521 turn(2).is_file(),
2522 "a task turning stalled must call the conductor again"
2523 );
2524
2525 conductor
2528 .maybe_run(
2529 &cfg,
2530 dir.path(),
2531 &queue,
2532 &questions,
2533 dir.path(),
2534 &[],
2535 &[t.clone()],
2536 &[],
2537 2,
2538 )
2539 .await;
2540 assert!(
2541 !turn(3).is_file(),
2542 "the same stalled task lingering must not call the conductor every cycle"
2543 );
2544 }
2545
2546 fn rehold(queue: &Queue, questions: &Questions, id: &str, note: &str) {
2547 apply(
2548 queue,
2549 questions,
2550 &Verdict {
2551 decisions: vec![Decision {
2552 id: id.to_owned(),
2553 reason: Some(note.to_owned()),
2554 recovery: Some(Recovery::Hold),
2555 ..Decision::default()
2556 }],
2557 },
2558 )
2559 .unwrap();
2560 }
2561
2562 #[test]
2563 fn reholding_with_an_identical_note_changes_nothing() {
2564 let dir = tempdir().unwrap();
2565 let queue = Queue::at(dir.path().join("queue"));
2566 let questions = Questions::at(dir.path().join("questions"));
2567 let mut t = task("held");
2568 t.hold_machine(Some("waiting on a human".to_owned()));
2569 queue.put(&mut t).unwrap();
2570
2571 rehold(&queue, &questions, &t.id, "owner said keep it held");
2572 let first = queue.get(&t.id).unwrap();
2573 let rev = queue.revision();
2574 for _ in 0..5 {
2575 rehold(&queue, &questions, &t.id, "owner said keep it held");
2576 }
2577 let after = queue.get(&t.id).unwrap();
2578 assert_eq!(after.hold_reason, first.hold_reason);
2579 assert_eq!(after.updated_at, first.updated_at);
2580 assert_eq!(queue.revision(), rev, "nothing was written");
2581 }
2582
2583 #[test]
2584 fn reholding_with_different_notes_keeps_one_previously_level() {
2585 let dir = tempdir().unwrap();
2586 let queue = Queue::at(dir.path().join("queue"));
2587 let questions = Questions::at(dir.path().join("questions"));
2588 let mut t = task("held");
2589 t.hold_machine(Some("original".to_owned()));
2590 queue.put(&mut t).unwrap();
2591
2592 for i in 0..20 {
2593 rehold(&queue, &questions, &t.id, &format!("note {}", i % 2));
2594 }
2595 let reason = queue.get(&t.id).unwrap().hold_reason.unwrap();
2596 assert_eq!(reason.matches("(previously:").count(), 1, "{reason}");
2597 assert!(reason.starts_with("note "), "the new note leads: {reason}");
2598 }
2599
2600 #[test]
2601 fn an_already_nested_reason_is_matched_by_its_outermost_note() {
2602 let mut t = task("deep");
2603 let nested = "same\n\n(previously: same\n\n(previously: same))";
2604 t.hold_machine(Some(nested.to_owned()));
2605 let d = Decision {
2606 id: t.id.clone(),
2607 reason: Some("same".to_owned()),
2608 ..Decision::default()
2609 };
2610 assert_eq!(reaffirmed_hold_reason(&t, &d), None);
2611 let d2 = Decision {
2612 reason: Some("other".to_owned()),
2613 ..d
2614 };
2615 assert_eq!(
2616 reaffirmed_hold_reason(&t, &d2).as_deref(),
2617 Some("other\n\n(previously: same)")
2618 );
2619 }
2620
2621 #[tokio::test]
2622 async fn a_repeated_hold_decision_settles_instead_of_looping() {
2623 let dir = tempdir().unwrap();
2624 let queue = Queue::at(dir.path().join("queue"));
2625 let questions = Questions::at(dir.path().join("questions"));
2626 let reply = r#"{"decisions":[{"id":"ID","reason":"keep held","recovery":"hold"}]}"#;
2627 let mut t = task("held");
2628 t.hold_machine(Some("first".to_owned()));
2629 queue.put(&mut t).unwrap();
2630 let cfg = config(mock_agent(
2631 dir.path(),
2632 REPLY,
2633 env(&reply.replace("ID", &t.id)),
2634 ));
2635 let mut conductor = Conductor::new();
2636 for _ in 0..2 {
2638 let held = queue.get(&t.id).unwrap();
2639 conductor
2640 .maybe_run(
2641 &cfg,
2642 dir.path(),
2643 &queue,
2644 &questions,
2645 dir.path(),
2646 &[],
2647 &[],
2648 &[held],
2649 2,
2650 )
2651 .await;
2652 }
2653 let held = queue.get(&t.id).unwrap();
2654 assert!(
2655 held.hold_reason
2656 .as_deref()
2657 .unwrap()
2658 .starts_with("keep held")
2659 );
2660 assert!(
2661 !conductor.worth_a_look(&queue, &[], &[held]),
2662 "an unchanged held task must stop being reconsidered"
2663 );
2664 }
2665
2666 #[tokio::test]
2667 async fn alternating_wording_does_not_keep_a_held_task_in_the_loop() {
2668 let dir = tempdir().unwrap();
2669 let queue = Queue::at(dir.path().join("queue"));
2670 let questions = Questions::at(dir.path().join("questions"));
2671 let mut t = task("held");
2672 t.hold_machine(Some("first".to_owned()));
2673 queue.put(&mut t).unwrap();
2674 let reply = |note: &str| {
2675 format!(
2676 r#"{{"decisions":[{{"id":"{}","reason":"{note}","recovery":"hold"}}]}}"#,
2677 t.id
2678 )
2679 };
2680 let cfg_a = config(mock_agent(dir.path(), REPLY, env(&reply("keep held"))));
2681 let cfg_b = config(mock_agent(dir.path(), REPLY, env(&reply("leave held"))));
2682 let mut conductor = Conductor::new();
2683 let mut writes = 0;
2684 for i in 0..6 {
2685 let held = queue.get(&t.id).unwrap();
2686 let before = queue.revision();
2687 conductor
2688 .maybe_run(
2689 if i % 2 == 0 { &cfg_a } else { &cfg_b },
2690 dir.path(),
2691 &queue,
2692 &questions,
2693 dir.path(),
2694 &[],
2695 &[],
2696 &[held],
2697 2,
2698 )
2699 .await;
2700 if queue.revision() != before {
2701 writes += 1;
2702 }
2703 }
2704 assert!(writes <= 2, "the loop must settle, saw {writes} writes");
2705 let mut held = queue.get(&t.id).unwrap();
2706 held.instruction.push_str(" (edited)");
2707 queue.put(&mut held).unwrap();
2708 let held = queue.get(&t.id).unwrap();
2709 assert!(conductor.worth_a_look(&queue, &[], &[held]));
2710 }
2711
2712 #[test]
2713 fn worth_a_look_is_config_free_and_matches_maybe_runs_own_gate() {
2714 let dir = tempdir().unwrap();
2715 let queue = Queue::at(dir.path().join("queue"));
2716 let mut t = task("t");
2717 queue.put(&mut t).unwrap();
2718
2719 let mut conductor = Conductor::new();
2720 assert!(
2721 conductor.worth_a_look(&queue, &[], &[]),
2722 "a conductor that has never run has something to look at"
2723 );
2724
2725 conductor.last_seen = Some(conductor.snapshot(&queue, &[], &[]));
2726 assert!(
2727 !conductor.worth_a_look(&queue, &[], &[]),
2728 "nothing changed and nothing is stalled or finished"
2729 );
2730 assert!(
2731 conductor.worth_a_look(&queue, &[t.clone()], &[]),
2732 "a stalled task is worth a look even at the same revision"
2733 );
2734 assert!(
2735 conductor.worth_a_look(&queue, &[], &[t.clone()]),
2736 "a finished task is worth a look even at the same revision"
2737 );
2738 }
2739
2740 #[tokio::test]
2741 async fn the_conduct_path_never_calls_ask_and_wait() {
2742 let dir = tempdir().unwrap();
2748 let queue = Queue::at(dir.path().join("queue"));
2749 let questions = Questions::at(dir.path().join("questions"));
2750 let mut t = task("asks without blocking");
2751 queue.put(&mut t).unwrap();
2752
2753 apply(
2754 &queue,
2755 &questions,
2756 &Verdict {
2757 decisions: vec![Decision {
2758 id: t.id.clone(),
2759 question: Some("ok?".to_owned()),
2760 ..Decision::default()
2761 }],
2762 },
2763 )
2764 .unwrap();
2765 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
2767 }
2768
2769 #[test]
2770 fn a_pinned_resume_is_not_held_or_requeued_by_the_conductor() {
2771 let mut t = Task::new("t".into(), "t".into(), PathBuf::new(), Source::Human);
2772 t.resume_override = Some(crate::queue::OperatorResume {
2773 question_id: "q".into(),
2774 at: jiff::Timestamp::now(),
2775 conductor_rehold: None,
2776 forced: false,
2777 pinned_run: Some("run-1".into()),
2778 });
2779 assert!(pinned_resume(&t));
2780 assert!(!may_hold(&mut t, "waiting for magi resume"));
2781 assert!(
2782 t.resume_override
2783 .as_ref()
2784 .unwrap()
2785 .conductor_rehold
2786 .is_none(),
2787 "a refused hold is not recorded as an override"
2788 );
2789 t.resume_override = None;
2790 assert!(!pinned_resume(&t));
2791 assert!(may_hold(&mut t, "no override, so a hold is allowed"));
2792 }
2793
2794 #[test]
2795 fn a_pinned_resume_is_not_blocked_by_a_conductor_question_or_dependency() {
2796 let dir = tempdir().unwrap();
2797 let queue = Queue::at(dir.path().join("queue"));
2798 let questions = Questions::at(dir.path().join("questions"));
2799 let mut t = task("resume me");
2800 t.resume_override = Some(crate::queue::OperatorResume {
2801 question_id: "q".into(),
2802 at: jiff::Timestamp::now(),
2803 conductor_rehold: None,
2804 forced: true,
2805 pinned_run: Some("run-1".into()),
2806 });
2807 queue.put(&mut t).unwrap();
2808
2809 apply(
2810 &queue,
2811 &questions,
2812 &Verdict {
2813 decisions: vec![
2814 Decision {
2815 id: t.id.clone(),
2816 question: Some("really?".to_owned()),
2817 ..Decision::default()
2818 },
2819 Decision {
2820 id: t.id.clone(),
2821 blocked_by: vec!["other".to_owned()],
2822 ..Decision::default()
2823 },
2824 ],
2825 },
2826 )
2827 .unwrap();
2828
2829 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
2830 assert!(questions.list().is_empty());
2831 }
2832}