Skip to main content

magi/
conduct.rs

1//! The conductor: a single agent seat that arranges the queue.
2//!
3//! [`crate::queue`] orders runnable tasks by `priority` alone; nothing in it
4//! can express that one task should wait for another, or that a task whose
5//! last run stopped short deserves a second look before the loop blindly
6//! retries it. Once per polling cycle, [`Conductor::maybe_run`] shows one
7//! agent seat three things - the runnable tasks, the tasks stuck `running`
8//! with no live daemon behind them, and the `failed`/`held` tasks nobody has
9//! decided about yet - and asks it to decide `blocked_by` for the first and a
10//! recovery for the other two. Everything else about the loop - which
11//! unblocked task runs next, one at a time, in `priority` order - is
12//! unchanged; see `crate::daemon`.
13//!
14//! # What the conductor may not do
15//!
16//! [`Decision`] has no field for `priority`, for deleting a task, or for
17//! touching git, a worktree, or a branch directly. [`Recovery::Review`] only
18//! ever reopens a branch `crate::daemon` itself resolved from the task's own
19//! run record ([`surviving_branch`]) - never a name the model wrote - through
20//! `crate::graph::Runner::review`, which reviews and verifies but never
21//! rewrites history.
22//!
23//! # Non-blocking by construction
24//!
25//! [`crate::ask::ask_and_wait`] is never called from here, and the prompt
26//! tells the model the same: that CLI command blocks until a human answers,
27//! and calling it from inside the conductor's own invocation would park the
28//! whole polling loop behind one task's question. Instead a decision that
29//! wants the operator's judgement carries a `question` field, and [`apply`]
30//! files it with [`Question::new`] and [`Questions::put`] and moves on in the
31//! same call. Something still has to read the owner's reply: the question
32//! carries a [`Deputy`] brief, and `magi serve` starts a short-lived seat of
33//! its own for it ([`crate::deputy`]) - never this loop.
34//!
35//! # Fails soft, always
36//!
37//! [`Conductor::maybe_run`] never returns an error: an unusable roster, a
38//! timed-out invocation, or a reply [`verdict::extract_json`] cannot parse are
39//! all logged and treated as "this cycle changes nothing." `crate::daemon`'s
40//! loop always falls through to its own `Queue::next_runnable` regardless of
41//! what happened here.
42
43use 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
58/// Seat name for the conductor's own CLI-side conversation, scoped away from
59/// every other seat magi ever opens - the same rule every other seat follows.
60const SEAT: &str = "conduct";
61
62/// Node name reported to the invoked agent (`MAGI_NODE`) and recorded on any
63/// question it files, so an operator reading the questions list can tell a
64/// conductor's question from one a run's own agent asked.
65pub const NODE: &str = "conduct";
66
67/// Wall-clock limit for one conductor turn. The conductor reads a queue
68/// listing and replies with json; it does not implement anything or run a
69/// build, so this is short - the same order of magnitude as
70/// `crate::chat`'s own single-turn, no-write invocations.
71const TURN_TIMEOUT: Duration = Duration::from_secs(300);
72
73/// What the conductor may choose for a `running`-but-stalled or a
74/// `failed`/`held` task.
75#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
76#[serde(rename_all = "lowercase")]
77pub enum Recovery {
78    /// Put it back in line, attempts reset - the same effect as
79    /// `magi task release`.
80    Requeue,
81    /// Leave it for a human, unchanged otherwise - the same effect as
82    /// `magi task hold`.
83    Hold,
84    /// Reopen the task's surviving branch as a review-only pass
85    /// (`crate::graph::Runner::review`) instead of competing from scratch.
86    /// Only takes effect when [`surviving_branch`] can actually name one;
87    /// otherwise `crate::daemon` falls back to [`Recovery::Requeue`].
88    Review,
89    /// Close the task outright, as [`Task::succeed`] - the same effect as
90    /// `magi task done`. For a `failed`/`held` task only, never `running`:
91    /// this is for a task whose own goal is already known to be met outside
92    /// the loop entirely (the branch was merged and the worktree cleaned up
93    /// by hand, say) and competing it again would only spend attempts on
94    /// work that has nothing left to do, not for a task that merely stopped
95    /// mid-competition and might still need to run.
96    Done,
97}
98
99/// The conductor's decision for one task. Deliberately has no `priority`
100/// field: see this module's doc.
101#[derive(Debug, Clone, Default, Deserialize)]
102pub struct Decision {
103    /// Task id, expected to be copied verbatim from what it was shown.
104    pub id: String,
105    /// Ids this task should be blocked on. Meaningful only for a runnable
106    /// (`queued`) task; ignored otherwise.
107    #[serde(default)]
108    pub blocked_by: Vec<String>,
109    /// One line explaining the block or the recovery.
110    #[serde(default)]
111    pub reason: Option<String>,
112    /// Recovery for a stalled or finished task. For a runnable (`queued`)
113    /// one, only [`Recovery::Hold`] has any effect - and only when
114    /// `blocked_by` is empty, since a `queued` task with something to wait on
115    /// is handled by that field instead - holding a task the operator has
116    /// already said should not compete again without filing another
117    /// `question` that only restates the same answer. `Requeue`, `Review`,
118    /// and `Done` have no meaning for a task that is already in line.
119    #[serde(default)]
120    pub recovery: Option<Recovery>,
121    /// A question for the operator. When present, [`apply`] files it (unless
122    /// one is already open for this task) and blocks the task on its id
123    /// instead of acting on `blocked_by` or `recovery`.
124    #[serde(default)]
125    pub question: Option<String>,
126    /// Fixed answers for `question`, if it has any. Empty means free text.
127    #[serde(default)]
128    pub choices: Vec<String>,
129}
130
131/// The conductor's whole reply for one cycle.
132///
133/// `decisions` is deliberately **not** `#[serde(default)]`, unlike every
134/// other field in this module. [`verdict::extract_json`] disambiguates
135/// between several balanced `{...}` spans in one reply by trying the type the
136/// caller wants against each of them, last first, and keeping the first that
137/// fits - which only works when a span that is not really the answer can
138/// fail to fit. A `Verdict` with no required field at all would make every
139/// span fit, including a `{}` left by stray trailing prose, and the reply's
140/// real `decisions` - earlier in the text - would never be reached. Requiring
141/// the key costs nothing: the prompt already asks for it on every reply, `[]`
142/// included.
143#[derive(Debug, Clone, Default, Deserialize)]
144pub struct Verdict {
145    /// One entry per task the conductor chose to say something about. A task
146    /// left out of this list is left exactly as it was.
147    pub decisions: Vec<Decision>,
148}
149
150/// A view of a task built for [`prompt::conduct`], shared by the runnable and
151/// stalled sections.
152fn 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
184/// Did the operator answer a `magi ask` choice with a `resume` action that
185/// this task has not yet acted on? Then `Recovery::Requeue` must not turn the
186/// task into a fresh competition either.
187fn pinned_resume(task: &Task) -> bool {
188    task.resume_override
189        .as_ref()
190        .is_some_and(|o| o.pinned_run.is_some())
191}
192
193/// May the conductor's `Recovery::Hold` take effect on `task`, given an
194/// operator's recorded "resume" answer? The conductor is allowed to override
195/// that answer once - and the override is recorded so `crate::triage` can
196/// show the operator the contradiction - but never after the operator
197/// insisted (`forced`), and never a second time.
198///
199/// Returns `false` when the hold must not be applied (nothing to write).
200/// When it returns `true` the override, if any, has been recorded on `task`.
201fn 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
219/// Severity as a lowercase word, matching how `crate::verdict::Severity` is
220/// spelled everywhere else an operator or a model reads it.
221fn 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
230/// The branch a task's last run left behind, if the tally ever ran on it -
231/// what [`Recovery::Review`] reopens. Derived from `crate::run::RunState`
232/// alone, never from anything the conductor wrote, so a hallucinated branch
233/// name can never reach `crate::graph::Runner::review`.
234fn 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
240/// The reason to record when the conductor holds a `failed`/`held` task via
241/// [`Recovery::Hold`]. Always `Some`, never a bare `d.reason.clone()`.
242///
243/// [`Task::hold_machine`] only overwrites [`Task::hold_reason`] when given
244/// one, precisely so a stalled task's existing diagnosis survives a
245/// decision that has nothing new to add. That is the right default when the
246/// task was not already `held` - but a task that *is* already `held`, and
247/// is being held again here, is a different case: its current
248/// `hold_reason` may still read as a cause `crate::triage` knows how to
249/// re-check on its own (a disk-pressure message, say - see
250/// `triage::machine_cause_resolved`), and if the model gives no reason,
251/// leaving that text untouched would make this decision - the conductor
252/// choosing, informed by the operator's own answer, to keep the task held
253/// anyway - indistinguishable from the original, never-reconsidered hold.
254/// `crate::triage` would then read the stale text the next time its one
255/// recognised cause looks resolved and release the task straight through
256/// the decision this call was recording. Prepending (not appending) the new
257/// note keeps the old text as context without leaving the string starting
258/// with whatever pattern `crate::triage` matched before.
259///
260/// Two bounds keep the string from growing, which it once did without limit
261/// (every re-hold nested the whole previous reason one level deeper, and every
262/// change relit the task's notice): a note equal to the current reason - or to
263/// its outermost note - adds nothing, so the result is `None` and the caller
264/// writes nothing; and only ONE `(previously: ...)` level is ever kept, the
265/// prior being cut back to its outermost note before it is embedded.
266fn 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
291/// Separator [`reaffirmed_hold_reason`] puts between a note and the reason it
292/// replaced.
293const PREVIOUSLY: &str = "\n\n(previously: ";
294
295/// A hold reason without any `(previously: ...)` tail: the text before the
296/// first separator, trimmed.
297fn outermost_hold_note(reason: &str) -> &str {
298    reason.split(PREVIOUSLY).next().unwrap_or(reason).trim()
299}
300
301/// The conductor's stated reason for a hold, or a stand-in when it gave none.
302fn hold_note(d: &Decision) -> String {
303    d.reason
304        .clone()
305        .unwrap_or_else(|| "(no reason given)".to_owned())
306}
307
308/// Everything the conductor is shown about a `failed`/`held` task's last run.
309async 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            // The exact failure this feature exists to stop hiding: a schema
329            // mismatch (or any other unreadable state) must never be treated
330            // as "nothing to recover" - it is surfaced here, verbatim, rather
331            // than swallowed into a quiet re-competition.
332            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
417/// Whether the task's latest run's winner branch already has an open pull
418/// request into the run's own base - a fact the repository can answer, so the
419/// operator is never asked it. `None` when there is no run or winner to check.
420async 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
441/// Append what the repository says about the branches and commits a task
442/// names to every question the conductor is about to file, so the operator is
443/// never asked a fact git can answer ("is it already on main?"). Done here,
444/// in code, rather than trusted to the model: a question the model wrote
445/// without checking still reaches the operator with the answer attached.
446/// When it cannot be checked the question says so instead of guessing.
447async 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                // Best effort: a stale tracking ref would report work that
476                // has since landed as still missing from the base.
477                let refreshed = crate::git::fetch(&repo, remote, &base)
478                    .await
479                    .is_ok_and(|o| o.ok());
480                // Only the remote's tip counts: a local branch of the same
481                // name is whatever the checkout happens to hold.
482                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
518/// A `failed`/`held` task together with how its last run ended.
519async 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
526/// The repository containing a task's branch. A task filed without a
527/// repository uses the daemon's repository, exactly as its later attempt does.
528fn 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
536/// Apply one decision to the queue and the question store.
537///
538/// Takes the task's own claim before touching it: a model call spans a whole
539/// agent turn, and the queue can have moved on by the time its answer comes
540/// back. A claim that cannot be taken means something else owns this task
541/// right now - most often a live daemon mid-competition on it - so the
542/// conductor's now-stale view of it is dropped rather than raced against; see
543/// `crate::queue::Queue::claim`'s own doc on why a claim is proof, not a
544/// guess.
545///
546/// A decision is matched against the task's *current* status, re-read under
547/// the claim, not against whichever section of the prompt it came from: a
548/// `blocked_by` only takes effect on a `queued` task, and `recovery` only on
549/// one `running` (stalled) or `failed`/`held`, so a decision that no longer
550/// matches what the task actually is - it moved on between the read that
551/// built the prompt and this write - changes nothing.
552fn 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    // A conductor answer is never operator authorization.  In particular,
559    // do this before questions and blocking too: either would reclassify a
560    // manual hold and let a later deterministic resolver queue it.
561    if task.operator_held() {
562        return Ok(());
563    }
564
565    // `crate::triage` is already running its own question-and-answer cycle
566    // on this hold - see that module's doc on why it never calls
567    // `Task::block`, and `crate::triage::pending_for`'s own doc on why "open"
568    // alone is not enough here: an answered-but-not-yet-applied triage
569    // question is still triage's to finish, since `crate::triage::run_once`
570    // only runs on a fully idle tick and only ever looks at tasks still
571    // `held`. Blocking this task out from under it - even on an unrelated
572    // question - would move it to `Blocked`, and the pending triage answer
573    // would never be read back.
574    if task.status == TaskStatus::Held && crate::triage::pending_for(questions, &task) {
575        return Ok(());
576    }
577
578    // The operator's `resume` action is waiting for its turn: a question or a
579    // dependency would park the task before the daemon can run it.
580    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        // `Question::run` is a task id for conductor questions, but ordinary
590        // graph questions use it as a run id. A coincidental equality must
591        // not block this task on an answer meant for another node.
592        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            // No cap on settled answers: a question the operator can answer
599            // is never refused. The task goes `Blocked` and at most one
600            // conductor question is open at a time (reused above), so each
601            // further question costs one human answer. Run attempts are
602            // bounded by `max_attempts` and the queue's attempt accounting.
603            // A model rewording the same question can still recur once per
604            // answer; that cost falls on the operator, by choice.
605            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                // The wait is handed to a deputy (`crate::deputy`), so a
615                // free-text reply reaches an agent that knows why this was
616                // asked. The conductor still never blocks: this only records
617                // what the deputy will be told, and `serve` starts it.
618                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        // See `Decision::recovery`'s doc: the only lever a runnable task has
641        // besides `blocked_by` is holding it outright, for a task whose
642        // answers already say it should not compete again.
643        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            // `Review` reopens a branch, which only makes sense once a run
660            // has actually stopped; a task still `running` has nothing to
661            // reopen yet.
662            _ => {}
663        },
664        TaskStatus::Failed | TaskStatus::Held => match d.recovery {
665            // The operator picked a specific run to continue; a fresh
666            // competition would throw that run away.
667            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                // Decided before `may_hold`, which spends the one override: a
674                // note that adds nothing writes nothing (and so raises no
675                // notice and moves no queue revision).
676                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                // No survivable branch: a decision naming `review` here is
689                // simply not actionable, and is dropped rather than guessed
690                // at - `crate::daemon` applies the same "no branch, no
691                // review" rule again, from its own read, right before it
692                // would actually start the run.
693            }
694            Some(Recovery::Done) => {
695                task.succeed();
696                // Same reason `magi task done` and the web UI's equivalent
697                // do this: the conductor closing a task by hand is just as
698                // much a finished story as the loop's own settle path.
699                crate::daemon::supersede_prior_runs(&task, &crate::run::home());
700                queue.put(&mut task)?;
701            }
702            None => {}
703        },
704        // `queued` with nothing to block on, `done`, or already `blocked`:
705        // nothing for this decision to do.
706        _ => {}
707    }
708    Ok(())
709}
710
711/// Apply every decision in `verdict`. A single bad decision - a task id that
712/// no longer exists, one already claimed elsewhere - is logged and skipped
713/// rather than losing every other decision in the same reply.
714pub 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
723/// Where the conductor's seat is kept between turns, so the daemon waiter can
724/// resume it when the owner answers a question it asked.
725///
726/// A graph seat's session lives in its run's `RunState`; the conductor has no
727/// run, and until this file its seat existed only in memory.
728pub fn seat_path(home: &Path) -> PathBuf {
729    home.join("conduct").join("seat.json")
730}
731
732/// The seat the conductor last used, if it has taken a turn.
733pub 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
741/// Is a conductor turn in flight right now?
742///
743/// A marker file rather than shared memory because the waiter reads it and the
744/// conductor is not necessarily in its process. A marker older than one turn's
745/// timeout (plus slack) was left by a turn that died and counts for nothing.
746pub 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
754/// Removes the busy marker when a turn ends, however it ends.
755struct 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/// The conductor's state across polling cycles: its own CLI-side conversation
775/// and the last (revision, stalled ∪ finished ids) pair it actually acted on.
776#[derive(Debug, Default)]
777pub struct Conductor {
778    seat: Option<SeatState>,
779    last_seen: Option<(u64, BTreeSet<String>)>,
780    /// Content fingerprint of each held task the model was last shown, see
781    /// [`input_fingerprint`]. A held task whose fingerprint still matches is
782    /// settled: the conductor's own rewrites of it do not count as news.
783    considered: BTreeMap<String, String>,
784}
785
786/// What the conductor's decision about a held task is a function of: the task
787/// without the fields the conductor itself rewrites (`updated_at`,
788/// `hold_reason`, the recorded re-hold). Independent of how the model words a
789/// repeated decision.
790fn 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    /// A conductor that has never run.
804    #[must_use]
805    pub fn new() -> Self {
806        Self::default()
807    }
808
809    /// Held tasks among `stalled` / `finished` whose input is unchanged since
810    /// the model last saw them. Their files are left out of the revision, so
811    /// the conductor re-holding one (however it words it) is not news, while
812    /// an owner's answer changes the fingerprint and brings the file back in.
813    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    /// Whether calling the conductor could possibly do anything different
852    /// from last time: [`Queue::revision`] moved, or the set of stalled and
853    /// finished task ids changed.
854    ///
855    /// Deliberately **not** "stalled or finished is non-empty" - a task
856    /// sitting stalled or finished with nobody changing anything about it
857    /// must not be re-shown to the model every single poll forever; only a
858    /// change in *which* tasks are stalled or finished, or a queue write
859    /// changing something about a runnable one, is worth another look.
860    ///
861    /// Cheap and config-free on purpose, so `crate::daemon`'s poll loop can
862    /// skip `Config::discover`'s synchronous I/O entirely on a cycle where
863    /// this says no - which [`Conductor::maybe_run`] would otherwise only
864    /// discover after paying for that load. Both ask the identical question,
865    /// from the same [`Conductor::last_seen`], so they can never disagree
866    /// about whether there is anything to look at.
867    #[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    /// Call the conductor once, unless nothing has changed since the last
873    /// time it was worth calling - see [`Conductor::worth_a_look`], the exact
874    /// same test. Never fatal - see this module's doc.
875    #[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        // What the model is about to be shown becomes "considered" before the
892        // snapshot is taken, so its own re-hold writes land in the excluded set.
893        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            // The conductor's own write moves the revision, so one more cycle
915            // follows; a repeat decision writes nothing (see
916            // `reaffirmed_hold_reason`), which is what ends the loop. The
917            // revision is deliberately never re-read here: it cannot tell our
918            // write from an owner's concurrent update.
919            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        // A string keeps today's resolution exactly (no CLI preflight here;
945        // an unavailable CLI fails at invocation). Only a multi-id array
946        // builds a chain, whose members are each tried at most once.
947        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        // Bound to a local: `Invocation` only borrows the cache path, and the
975        // `Option<PathBuf>` `cache_dir()` returns has to outlive that borrow.
976        let cache_dir = cfg.cache_dir();
977
978        // One marker for the whole chain: a fallback is still this turn.
979        let busy = Busy::mark(home);
980        let mut result: Result<Verdict> = Err(anyhow::anyhow!("no conductor agent ran"));
981        for spec in &chain {
982            // The prompt carries the whole queue state every cycle, so a
983            // fallback agent needs no history - but its seat is its own.
984            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            // The first agent keeps the plain stem; a fallback's own artifacts
990            // must not overwrite it.
991            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                // The conductor never edits anything - it only decides what
1001                // blocks a task and what to do about one stuck or finished.
1002                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            // Kept after every turn, failed or not: the CLI-side conversation is
1015            // what a resumed question needs, and it exists once the turn ran.
1016            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    /// A throwaway repo with one commit on `main` and a second branch ahead
1103    /// of it, so `outcome_for`'s own `git::rev_parse` call has a real head to
1104    /// resolve.
1105    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    /// A tiny single-threaded block-on, so an `async fn` can be exercised
1281    /// from a plain `#[test]` without pulling `tokio::test`'s multi-thread
1282    /// runtime into a test that does no other async work.
1283    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        // An operator releasing the blocked task by hand, without answering,
1386        // puts it back at `Queued` while the question stays open - exactly
1387        // the case the guard in `apply_one` exists for: a later cycle
1388        // proposing the very same question must reuse it, not file a second.
1389        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        // `crate::daemon::resolve_blockers` is the deterministic resolver
1480        // that actually does this on the real queue; here it is enough to
1481        // prove the pure steps it is built from behave together.
1482        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        // Reproduces the reported bug: a task held after burning its
1536        // attempts, once the conductor asks a follow-up question about it,
1537        // must come back `held` - not `queued` - once the question is
1538        // answered, whatever the answer said.
1539        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        // What `crate::daemon::resolve_blockers` does on the real queue.
1568        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        // A different path to the same bug round 1 fixed: a task
1582        // machine-held for disk pressure, blocked on a conductor question,
1583        // answered "keep it held", and restored to `held`. If the
1584        // conductor's next decision reconfirms `recovery: hold` with no new
1585        // `reason` - allowed, `Decision::reason` is optional - `hold_machine`
1586        // must not silently leave the stale disk-pressure text in place, or
1587        // `crate::triage::run_once` reads it as an unexamined, auto-resolvable
1588        // hold and releases the task straight through the operator's answer
1589        // the instant disk space looks fine again.
1590        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        // The disk gate would report space is fine now - `crate::triage`
1631        // must not read the old text and release the task through it.
1632        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        // 1. triage asks the ordinary machine question; the operator resumes.
1672        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        // 2. the conductor holds it again - allowed once, and recorded.
1682        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        // 3. triage must say something different, once.
1693        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        // 4. forcing a requeue makes the conductor's hold a no-op.
1702        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        // Reproduces the other half of the reported bug (task 6081): once
1748        // the operator's answer says the work already happened outside the
1749        // loop - PR merged, worktree cleaned up - the conductor needs an
1750        // actual terminal state to put the task in, not just a hold it will
1751        // keep being re-asked about.
1752        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        // A genuine question must stay answerable however many were settled
1818        // before it: refusing it left `magi answer --list` empty.
1819        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        // `crate::triage` never calls `Task::block`, and only ever looks at
1907        // tasks still `held` - so a conductor question that moved this task
1908        // to `blocked` would orphan triage's own open question. The guard in
1909        // `apply_one` must leave the task alone until triage's question
1910        // settles.
1911        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        // The race `crate::triage::pending_for` exists to close: the
1971        // operator has already answered the triage question (it is no
1972        // longer `open`), but `crate::triage::run_once` - which only runs on
1973        // a fully idle daemon tick, far less often than the conductor polls
1974        // - has not had a turn to apply it yet. `apply_one` must not treat
1975        // "not open" as "settled" here, or it would block the task out from
1976        // under an answer triage has not read back yet.
1977        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        // Every field a conductor may use to alter lifecycle state is ignored:
2043        // requeue/review would dispatch duplicate work, hold could overwrite
2044        // evidence, and a question would turn the hold into `blocked`.
2045        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        // This mirrors the CLI and web release routes: only an explicit
2133        // operator action clears the manual boundary.
2134        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        // `surviving_branch` reaches `RunState::load`, which reaches the
2175        // process-global `run::home()` - a `OnceLock`, so this only wins the
2176        // race the first time it runs in the binary; every other test still
2177        // reaches the same directory whichever call won, and this test's own
2178        // run id never collides with another test's.
2179        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()); // no such run on disk
2185        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        // `Hold` is the one exception - see `Decision::recovery`'s doc and
2213        // `a_runnable_task_can_be_held_directly_without_a_question` - but a
2214        // task already in line has nothing for `requeue` or `review` to do.
2215        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        // Each real invocation writes its own artifact stem, `turn-<n>`, so
2411        // whether a second one happened is read off the artifacts directory.
2412        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        // Once the queue actually changes, the next `maybe_run` calls again.
2457        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        // The queue's own revision has not moved - nothing wrote to it - but
2478        // a task now looks stalled, purely because time passed. Calling
2479        // again here, and never again once this exact set has been shown
2480        // once, is the whole point of keying `worth_a_look` on the id set
2481        // rather than on "is it non-empty".
2482        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        // But once shown at this exact revision, showing the *same* stalled
2526        // set again must not call a third time.
2527        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        // Cycle 1 writes the new note; cycle 2 repeats it and writes nothing.
2637        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        // Structural: grepping this module and `daemon.rs` for
2743        // `ask_and_wait` is the actual assertion this module's own doc
2744        // promises; this test exists so the promise has a name in the test
2745        // output too. `apply_one`'s question path uses `Questions::put`
2746        // exclusively.
2747        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        // Reaching here at all (no hang) is the assertion.
2766        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}