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