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::{CompletionActor, 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_for_effects(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.execution_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.execution_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.execution_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    if crate::base_sync_recovery::held_task(queue, &task)
784        && (d.recovery == Some(Recovery::Requeue)
785            || d.question_decision
786                .as_ref()
787                .is_some_and(|q| q.operation == QuestionOperation::Resume)
788            || d.actions
789                .values()
790                .any(|a| matches!(a, ChoiceAction::Resume { .. })))
791    {
792        // Additional base rebases require their own explicit authorization.
793        return Ok(());
794    }
795
796    if d.question.is_none()
797        && crate::head_e2e_stop::blocks_automatic_recovery(queue, &task)
798        && (matches!(d.recovery, Some(Recovery::Requeue | Recovery::Review))
799            || (task.status == TaskStatus::Held && d.recovery == Some(Recovery::Hold)))
800    {
801        // Unchanged conclusive head_e2e red stays at its actionable machine hold
802        // until candidate HEAD, remote base, repair evidence, or the owner changes it.
803        return Ok(());
804    }
805
806    // A claimed task may have deferred the pre-scheduling triage sweep.
807    // Leave an open or answered-unapplied question to that sweep rather
808    // than move the task out from under it.
809    if task.status == TaskStatus::Held && crate::triage::pending_for(questions, &task) {
810        return Ok(());
811    }
812
813    // The operator's `resume` action is waiting for its turn: a question or a
814    // dependency would park the task before the daemon can run it.
815    let pinned = pinned_resume(&task);
816    if pinned && (d.question.is_some() || !d.blocked_by.is_empty()) {
817        return Ok(());
818    }
819
820    // A missing-only decision with unverifiable aliases is not evidence for
821    // a question or hold. Do not guess that two ambiguous/unknown references
822    // mean the same record, or treat failure to prove that as proof of absence.
823    if matches!(task.status, TaskStatus::Queued | TaskStatus::Held)
824        && !d.missing_dependencies.is_empty()
825        && (d.question.is_some() || d.recovery == Some(Recovery::Hold))
826        && d.missing_dependencies
827            .iter()
828            .any(|id| !d.blocked_by.contains(id))
829        && d.missing_dependencies
830            .iter()
831            .chain(&d.blocked_by)
832            .any(|id| {
833                matches!(
834                    crate::queue::dependency(queue, questions, id),
835                    crate::queue::Dependency::Ambiguous | crate::queue::Dependency::Unknown
836                )
837            })
838    {
839        return Ok(());
840    }
841
842    // Only an explicit missing-only claim can justify replacing a question
843    // or hold. Existing prerequisites alone say nothing about independent
844    // consent, destructive-operation questions, or other reasons to stay held.
845    // Ambiguous or unreadable inventories cannot confirm absence either: keep
846    // the original reference waiting until it can be resolved authoritatively.
847    if matches!(task.status, TaskStatus::Queued | TaskStatus::Held)
848        && !d.missing_dependencies.is_empty()
849        && d.missing_dependencies.iter().all(|id| {
850            let claim = crate::queue::dependency(queue, questions, id);
851            claim != crate::queue::Dependency::Missing
852                && d.blocked_by.iter().any(|blocker| {
853                    blocker == id
854                        || (matches!(
855                            &claim,
856                            crate::queue::Dependency::Task(_)
857                                | crate::queue::Dependency::Question(_)
858                                | crate::queue::Dependency::Deleted(_)
859                        ) && crate::queue::dependency(queue, questions, blocker) == claim)
860                })
861        })
862        && (d.question.is_some() || d.recovery == Some(Recovery::Hold))
863        && crate::queue::missing_blockers(queue, questions, &d.blocked_by).is_empty()
864    {
865        let mut ids = d.blocked_by.clone();
866        crate::queue::normalize_blockers(queue, questions, &mut ids);
867        let reason = format!("Waiting on dependencies: {}", ids.join(", "));
868        task.block(ids, Some(reason));
869        return queue.put(&mut task);
870    }
871
872    if let Some(text) = &d.question {
873        if task.status == TaskStatus::Done {
874            return Ok(());
875        }
876        let mut held = task.clone();
877        held.status = TaskStatus::Held;
878        let targets: BTreeSet<_> = d
879            .blocked_by
880            .iter()
881            .filter_map(|id| {
882                if let Ok(dep) = queue.get(id) {
883                    Some(format!("task:{id}:{:?}", dep.chat_notice_key()))
884                } else if questions.get_for_effects(id).is_ok() {
885                    Some(format!("question:{id}"))
886                } else {
887                    None
888                }
889            })
890            .collect();
891        let decision = d
892            .question_decision
893            .as_ref()
894            .and_then(|q| match q.identity(&task) {
895                Ok(identity) => Some(identity),
896                Err(error) => {
897                    // Invalid optional metadata must not discard the question
898                    // or leave a runnable task without its decision barrier.
899                    tracing::warn!(task = %task.id, %error, "ignoring invalid question decision target");
900                    None
901                }
902            });
903        let context_value =
904            serde_json::json!([&task.instruction, held.chat_notice_key(), targets, decision]);
905        let context = serde_json::to_string(&context_value)?;
906        // An answer alone does not justify asking the same decision again.
907        // New producer evidence, an instruction edit or a different dependency
908        // target can open another question; rewording cannot.
909        if questions.list_for_effects().iter().any(|q| {
910            q.node == NODE
911                && q.run == task.id
912                && q.status == crate::ask::QuestionStatus::Answered
913                && q.decision_context.as_ref().is_some_and(|stored| {
914                    if stored == &context {
915                        return true;
916                    }
917                    // Missing metadata cannot manufacture a new target. This
918                    // also baselines older contexts whose last item was labels.
919                    decision.is_none()
920                        && serde_json::from_str::<serde_json::Value>(stored)
921                            .ok()
922                            .and_then(|v| {
923                                v.as_array().map(|items| {
924                                    items.len() == 4
925                                        && items[..3]
926                                            == context_value.as_array().expect("context")[..3]
927                                })
928                            })
929                            == Some(true)
930                })
931        }) {
932            return Ok(());
933        }
934        // `Question::run` is a task id for conductor questions, but ordinary
935        // graph questions use it as a run id. A coincidental equality must
936        // not block this task on an answer meant for another node.
937        let question_id = match questions
938            .list_for_effects()
939            .into_iter()
940            .find(|q| q.status.open() && q.node == NODE && q.run == task.id)
941        {
942            Some(existing) => existing.id,
943            None => {
944                let mut q = Question::new(
945                    task.id.clone(),
946                    NODE.to_owned(),
947                    SEAT.to_owned(),
948                    text.clone(),
949                    d.reason.clone().unwrap_or_default(),
950                    d.choices.clone(),
951                );
952                q.actions = d.actions.clone();
953                crate::choice_effect::executable_conductor(&mut q);
954                q.decision_context = Some(context);
955                // The wait is handed to a deputy (`crate::deputy`), so a
956                // free-text reply reaches an agent that knows why this was
957                // asked. The conductor still never blocks: this only records
958                // what the deputy will be told, and `serve` starts it.
959                q.deputy = Some(Deputy::new(crate::deputy::brief(
960                    &task.id,
961                    d.reason.as_deref().unwrap_or_default(),
962                    &q.choices,
963                    &q.actions,
964                )));
965                if task.repo.is_dir() && task.repo != Path::new(".") {
966                    q.cwd = Some(task.repo.to_string_lossy().into_owned());
967                }
968                questions.put_executable(&mut q)?;
969                q.id
970            }
971        };
972        task.block(vec![question_id], d.reason.clone());
973        return queue.put(&mut task);
974    }
975
976    match task.status {
977        // See `Decision::recovery`'s doc: the only lever a runnable task has
978        // besides `blocked_by` is holding it outright, for a task whose
979        // answers already say it should not compete again.
980        TaskStatus::Queued if d.recovery == Some(Recovery::Hold) => {
981            if may_hold(&mut task, &hold_note(d)) {
982                task.hold_machine(d.reason.clone());
983                queue.put(&mut task)?;
984            }
985        }
986        TaskStatus::Queued if !d.blocked_by.is_empty() => {
987            let mut ids = d.blocked_by.clone();
988            crate::queue::normalize_blockers(queue, questions, &mut ids);
989            task.block(ids, d.reason.clone());
990            queue.put(&mut task)?;
991        }
992        TaskStatus::Running => match d.recovery {
993            Some(Recovery::Requeue) if pinned_resume(&task) => {}
994            Some(Recovery::Requeue) => {
995                task.requeue();
996                queue.put(&mut task)?;
997            }
998            Some(Recovery::Hold) if may_hold(&mut task, &hold_note(d)) => {
999                task.hold_machine(d.reason.clone());
1000                queue.put(&mut task)?;
1001            }
1002            // `Review` reopens a branch, which only makes sense once a run
1003            // has actually stopped; a task still `running` has nothing to
1004            // reopen yet.
1005            _ => {}
1006        },
1007        TaskStatus::Failed | TaskStatus::Held => match d.recovery {
1008            // The operator picked a specific run to continue; a fresh
1009            // competition would throw that run away.
1010            Some(Recovery::Requeue) if pinned_resume(&task) => {}
1011            Some(Recovery::Requeue) => {
1012                task.requeue();
1013                queue.put(&mut task)?;
1014            }
1015            Some(Recovery::Hold) => {
1016                // Decided before `may_hold`, which spends the one override: a
1017                // note that adds nothing writes nothing (and so raises no
1018                // notice and moves no queue revision).
1019                if let Some(reason) = reaffirmed_hold_reason(&task, d) {
1020                    if may_hold(&mut task, &hold_note(d)) {
1021                        task.hold_machine(Some(reason));
1022                        queue.put(&mut task)?;
1023                    }
1024                }
1025            }
1026            Some(Recovery::Review) => {
1027                if let Some(branch) = surviving_branch(&task) {
1028                    task.request_review(branch);
1029                    queue.put(&mut task)?;
1030                }
1031                // No survivable branch: a decision naming `review` here is
1032                // simply not actionable, and is dropped rather than guessed
1033                // at - `crate::daemon` applies the same "no branch, no
1034                // review" rule again, from its own read, right before it
1035                // would actually start the run.
1036            }
1037            Some(Recovery::Done) => {
1038                let context = crate::task_completion::prepare_close(
1039                    &task,
1040                    &crate::run::home(),
1041                    CompletionActor::Conductor,
1042                    d.reason.clone(),
1043                    false,
1044                )?;
1045                task.succeed(context);
1046                // Same reason `magi task done` and the web UI's equivalent
1047                // do this: the conductor closing a task by hand is just as
1048                // much a finished story as the loop's own settle path.
1049                crate::daemon::supersede_prior_runs(&task, &crate::run::home());
1050                queue.put(&mut task)?;
1051            }
1052            None => {}
1053        },
1054        // `queued` with nothing to block on, `done`, or already `blocked`:
1055        // nothing for this decision to do.
1056        _ => {}
1057    }
1058    Ok(())
1059}
1060
1061/// Apply every decision in `verdict`. A single bad decision - a task id that
1062/// no longer exists, one already claimed elsewhere - is logged and skipped
1063/// rather than losing every other decision in the same reply.
1064pub fn apply(queue: &Queue, questions: &Questions, verdict: &Verdict) -> Result<()> {
1065    for d in &verdict.decisions {
1066        if let Err(e) = apply_one(queue, questions, d, None) {
1067            tracing::warn!("conductor decision for task {}: {e:#}", d.id);
1068        }
1069    }
1070    Ok(())
1071}
1072
1073/// Where the conductor's seat is kept between turns, so the daemon waiter can
1074/// resume it when the owner answers a question it asked.
1075///
1076/// A graph seat's session lives in its run's `RunState`; the conductor has no
1077/// run, and until this file its seat existed only in memory.
1078pub fn seat_path(home: &Path) -> PathBuf {
1079    home.join("conduct").join("seat.json")
1080}
1081
1082/// The seat the conductor last used, if it has taken a turn.
1083pub fn load_seat(home: &Path) -> Option<SeatState> {
1084    serde_json::from_str(&std::fs::read_to_string(seat_path(home)).ok()?).ok()
1085}
1086
1087fn busy_path(home: &Path) -> PathBuf {
1088    home.join("conduct").join("busy")
1089}
1090
1091/// Is a conductor turn in flight right now?
1092///
1093/// A marker file rather than shared memory because the waiter reads it and the
1094/// conductor is not necessarily in its process. A marker older than one turn's
1095/// timeout (plus slack) was left by a turn that died and counts for nothing.
1096pub fn busy(home: &Path) -> bool {
1097    std::fs::metadata(busy_path(home))
1098        .and_then(|m| m.modified())
1099        .ok()
1100        .and_then(|t| t.elapsed().ok())
1101        .is_some_and(|age| age < TURN_TIMEOUT + Duration::from_secs(30))
1102}
1103
1104/// Removes the busy marker when a turn ends, however it ends.
1105struct Busy(PathBuf);
1106
1107impl Busy {
1108    fn mark(home: &Path) -> Self {
1109        let path = busy_path(home);
1110        if let Some(dir) = path.parent() {
1111            let _ = std::fs::create_dir_all(dir);
1112        }
1113        let _ = std::fs::write(&path, std::process::id().to_string());
1114        Self(path)
1115    }
1116}
1117
1118impl Drop for Busy {
1119    fn drop(&mut self) {
1120        let _ = std::fs::remove_file(&self.0);
1121    }
1122}
1123
1124/// The conductor's state across polling cycles: its own CLI-side conversation
1125/// and the last (revision, stalled ∪ finished ids) pair it actually acted on.
1126#[derive(Debug, Default, Serialize, Deserialize)]
1127pub struct Conductor {
1128    seat: Option<SeatState>,
1129    last_seen: Option<(u64, BTreeSet<String>)>,
1130    /// Content fingerprint of each held task the model was last shown, see
1131    /// [`input_fingerprint`]. A held task whose fingerprint still matches is
1132    /// settled: the conductor's own rewrites of it do not count as news.
1133    considered: BTreeMap<String, String>,
1134}
1135
1136/// What the conductor's decision about a held task is a function of: the task
1137/// without the fields the conductor itself rewrites (`updated_at`,
1138/// `hold_reason`, the recorded re-hold). Independent of how the model words a
1139/// repeated decision.
1140fn decision_input(task: &Task) -> serde_json::Value {
1141    let mut v = serde_json::to_value(task).unwrap_or_default();
1142    if let Some(o) = v.as_object_mut() {
1143        o.remove("chat_notice");
1144        o.remove("chat_notices");
1145        // A delivery write changes only bookkeeping, not the decision input.
1146        o.remove("updated_at");
1147    }
1148    v
1149}
1150
1151fn input_fingerprint(task: &Task) -> String {
1152    let mut v = decision_input(task);
1153    if let Some(o) = v.as_object_mut() {
1154        o.remove("hold_reason");
1155        if let Some(ro) = o.get_mut("resume_override").and_then(|r| r.as_object_mut()) {
1156            ro.remove("conductor_rehold");
1157        }
1158    }
1159    v.to_string()
1160}
1161
1162impl Conductor {
1163    /// A conductor that has never run.
1164    #[must_use]
1165    pub fn new() -> Self {
1166        Self::default()
1167    }
1168
1169    /// Held tasks among `stalled` / `finished` whose input is unchanged since
1170    /// the model last saw them. Their files are left out of the revision, so
1171    /// the conductor re-holding one (however it words it) is not news, while
1172    /// an owner's answer changes the fingerprint and brings the file back in.
1173    fn settled(
1174        considered: &BTreeMap<String, String>,
1175        stalled: &[Task],
1176        finished: &[Task],
1177    ) -> BTreeSet<String> {
1178        stalled
1179            .iter()
1180            .chain(finished)
1181            .filter(|t| t.status == TaskStatus::Held)
1182            .filter(|t| considered.get(&t.id) == Some(&input_fingerprint(t)))
1183            .map(|t| t.id.clone())
1184            .collect()
1185    }
1186
1187    fn snapshot_with(
1188        considered: &BTreeMap<String, String>,
1189        queue: &Queue,
1190        stalled: &[Task],
1191        finished: &[Task],
1192    ) -> (u64, BTreeSet<String>) {
1193        let ids = stalled
1194            .iter()
1195            .chain(finished)
1196            .map(|t| t.id.clone())
1197            .collect();
1198        let skip = Self::settled(considered, stalled, finished);
1199        (queue.revision_excluding(&skip), ids)
1200    }
1201
1202    fn snapshot(
1203        &self,
1204        queue: &Queue,
1205        stalled: &[Task],
1206        finished: &[Task],
1207    ) -> (u64, BTreeSet<String>) {
1208        Self::snapshot_with(&self.considered, queue, stalled, finished)
1209    }
1210
1211    /// Whether calling the conductor could possibly do anything different
1212    /// from last time: [`Queue::revision`] moved, or the set of stalled and
1213    /// finished task ids changed.
1214    ///
1215    /// Deliberately **not** "stalled or finished is non-empty" - a task
1216    /// sitting stalled or finished with nobody changing anything about it
1217    /// must not be re-shown to the model every single poll forever; only a
1218    /// change in *which* tasks are stalled or finished, or a queue write
1219    /// changing something about a runnable one, is worth another look.
1220    ///
1221    /// Cheap and config-free on purpose, so `crate::daemon`'s poll loop can
1222    /// skip `Config::discover`'s synchronous I/O entirely on a cycle where
1223    /// this says no - which [`Conductor::maybe_run`] would otherwise only
1224    /// discover after paying for that load. Both ask the identical question,
1225    /// from the same [`Conductor::last_seen`], so they can never disagree
1226    /// about whether there is anything to look at.
1227    #[must_use]
1228    pub fn worth_a_look(&self, queue: &Queue, stalled: &[Task], finished: &[Task]) -> bool {
1229        self.last_seen.as_ref() != Some(&self.snapshot(queue, stalled, finished))
1230    }
1231
1232    /// Call the conductor once, unless nothing has changed since the last
1233    /// time it was worth calling - see [`Conductor::worth_a_look`], the exact
1234    /// same test. Never fatal - see this module's doc.
1235    #[allow(clippy::too_many_arguments)]
1236    pub async fn maybe_run(
1237        &mut self,
1238        cfg: &Config,
1239        repo: &Path,
1240        queue: &Queue,
1241        questions: &Questions,
1242        home: &Path,
1243        queued: &[Task],
1244        stalled: &[Task],
1245        finished: &[Task],
1246        max_attempts: usize,
1247    ) {
1248        if self.last_seen.as_ref() == Some(&self.snapshot(queue, stalled, finished)) {
1249            return;
1250        }
1251        // What the model is about to be shown becomes "considered" before the
1252        // snapshot is taken, so its own re-hold writes land in the excluded set.
1253        self.considered = stalled
1254            .iter()
1255            .chain(finished)
1256            .filter(|t| t.status == TaskStatus::Held)
1257            .map(|t| (t.id.clone(), input_fingerprint(t)))
1258            .collect();
1259        self.last_seen = Some(self.snapshot(queue, stalled, finished));
1260        if let Err(e) = self
1261            .run_once(
1262                cfg,
1263                repo,
1264                queue,
1265                questions,
1266                home,
1267                queued,
1268                stalled,
1269                finished,
1270                max_attempts,
1271            )
1272            .await
1273        {
1274            // The conductor's own write moves the revision, so one more cycle
1275            // follows; a repeat decision writes nothing (see
1276            // `reaffirmed_hold_reason`), which is what ends the loop. The
1277            // revision is deliberately never re-read here: it cannot tell our
1278            // write from an owner's concurrent update.
1279            tracing::warn!("conductor: {e:#}");
1280        }
1281    }
1282
1283    #[allow(clippy::too_many_arguments)]
1284    async fn run_once(
1285        &mut self,
1286        cfg: &Config,
1287        repo: &Path,
1288        queue: &Queue,
1289        questions: &Questions,
1290        home: &Path,
1291        queued: &[Task],
1292        stalled: &[Task],
1293        finished: &[Task],
1294        max_attempts: usize,
1295    ) -> Result<()> {
1296        if queued.is_empty() && stalled.is_empty() && finished.is_empty() {
1297            return Ok(());
1298        }
1299
1300        let primary = cfg
1301            .resolve_roles()
1302            .context("resolving the conductor seat")?
1303            .conductor;
1304        // A string keeps today's resolution exactly (no CLI preflight here;
1305        // an unavailable CLI fails at invocation). Only a multi-id array
1306        // builds a chain, whose members are each tried at most once.
1307        let chain = match cfg.roles.conductor.as_ref() {
1308            Some(c) if c.ids().len() > 1 => {
1309                agent::pick_chain(&cfg.agents, Some(c), &agent::installed, "conductor")?
1310            }
1311            _ => vec![primary],
1312        };
1313
1314        let runnable_views: Vec<prompt::ConductTask> =
1315            queued.iter().map(|t| view(t, max_attempts)).collect();
1316        let stalled_views: Vec<prompt::ConductTask> =
1317            stalled.iter().map(|t| view(t, max_attempts)).collect();
1318        let mut finished_views = Vec::with_capacity(finished.len());
1319        for t in finished {
1320            finished_views.push(finished_view(t, repo, max_attempts).await);
1321        }
1322
1323        let body = prompt::with_overlay(
1324            prompt::conduct(
1325                &runnable_views,
1326                &stalled_views,
1327                &finished_views,
1328                &cfg.graph.language,
1329            ),
1330            cfg.prompts.overlay(NODE),
1331        );
1332
1333        let body = format!(
1334            "{body}\n\n{}",
1335            crate::queue::dependency_facts(queue, questions)
1336        );
1337        let artifacts = home.join("conduct").join("artifacts");
1338        // Bound to a local: `Invocation` only borrows the cache path, and the
1339        // `Option<PathBuf>` `cache_dir()` returns has to outlive that borrow.
1340        let cache_dir = cfg.cache_dir();
1341
1342        // One marker for the whole chain: a fallback is still this turn.
1343        let busy = Busy::mark(home);
1344        let mut result: Result<Verdict> = Err(anyhow::anyhow!("no conductor agent ran"));
1345        for spec in &chain {
1346            // The prompt carries the whole queue state every cycle, so a
1347            // fallback agent needs no history - but its seat is its own.
1348            let needs_new_seat = !matches!(&self.seat, Some(s) if s.agent == spec.id);
1349            if needs_new_seat {
1350                self.seat = Some(SeatState::new(SEAT, &spec.id, crate::rng::entropy()));
1351            }
1352            let seat = self.seat.as_mut().expect("just ensured a seat exists");
1353            // The first agent keeps the plain stem; a fallback's own artifacts
1354            // must not overwrite it.
1355            let stem = if std::ptr::eq(spec, &chain[0]) {
1356                format!("turn-{}", seat.turns + 1)
1357            } else {
1358                format!("turn-{}-{}", seat.turns + 1, spec.id)
1359            };
1360            let inv = Invocation {
1361                coordination: cfg.coordination.as_ref(),
1362                fetched_base: None,
1363                cwd: repo,
1364                prompt: &body,
1365                timeout: TURN_TIMEOUT,
1366                // The conductor never edits anything - it only decides what
1367                // blocks a task and what to do about one stuck or finished.
1368                allow_write: false,
1369                sessions: cfg.graph.sessions,
1370                artifacts: &artifacts,
1371                stem: &stem,
1372                run: NODE,
1373                node: NODE,
1374                cache_dir: cache_dir.as_deref(),
1375                attachments: &[],
1376                writable: &[],
1377            };
1378            let out = agent::invoke(spec, seat, &inv).await;
1379            // Kept after every turn, failed or not: the CLI-side conversation is
1380            // what a resumed question needs, and it exists once the turn ran.
1381            if let Ok(body) = serde_json::to_string(&*seat) {
1382                let path = seat_path(home);
1383                if let Some(dir) = path.parent() {
1384                    let _ = std::fs::create_dir_all(dir);
1385                }
1386                let _ = std::fs::write(path, body);
1387            }
1388            let advance = agent::chain_advances(&out);
1389            result = match out {
1390                Err(e) => Err(e.context("invoking the conductor")),
1391                Ok(out) if advance => Err(anyhow::anyhow!(
1392                    "no usable reply ({})",
1393                    crate::notices::turn_status(
1394                        out.exit_code,
1395                        out.timed_out,
1396                        out.quota_exhausted()
1397                    )
1398                )),
1399                Ok(out) => verdict::extract_json(&out.text)
1400                    .context("the conductor's reply could not be parsed"),
1401            };
1402            if result.is_ok() {
1403                break;
1404            }
1405            if chain.len() > 1 {
1406                tracing::warn!("conductor: `{}` failed, trying the next agent", spec.id);
1407            }
1408        }
1409        drop(busy);
1410        let mut verdict = result?;
1411        attach_facts(cfg, repo, queue, &mut verdict).await;
1412        for d in &verdict.decisions {
1413            let snapshot = queued
1414                .iter()
1415                .chain(stalled)
1416                .chain(finished)
1417                .find(|t| t.id == d.id);
1418            if let Some(snapshot) = snapshot {
1419                if let Err(e) = apply_one(queue, questions, d, Some(snapshot)) {
1420                    tracing::warn!("conductor decision for task {}: {e:#}", d.id);
1421                }
1422            }
1423        }
1424        Ok(())
1425    }
1426}
1427
1428#[cfg(test)]
1429mod tests {
1430    use std::collections::BTreeMap;
1431
1432    use tempfile::tempdir;
1433
1434    use super::*;
1435    use crate::ask::{Answer, QuestionStatus};
1436    use crate::config::{AgentKind, AgentSpec, Graph};
1437    use crate::queue::{CompletionContext, Source};
1438
1439    fn mock_agent(dir: &Path, script: &str, env: BTreeMap<String, String>) -> AgentSpec {
1440        let path = dir.join("mock-conduct-agent.sh");
1441        std::fs::write(&path, script).expect("write mock");
1442        AgentSpec {
1443            id: "mock".to_owned(),
1444            kind: AgentKind::Command,
1445            model: None,
1446            command: vec!["sh".to_owned(), path.to_string_lossy().into_owned()],
1447            extra_args: Vec::new(),
1448            env,
1449            prompt_delivery: None,
1450            max_turn_secs: None,
1451        }
1452    }
1453
1454    fn config(spec: AgentSpec) -> Config {
1455        Config {
1456            agents: vec![spec],
1457            graph: Graph {
1458                language: "en".to_owned(),
1459                ..Graph::default()
1460            },
1461            ..Config::default()
1462        }
1463    }
1464
1465    fn task(title: &str) -> Task {
1466        Task::new(
1467            title.to_owned(),
1468            format!("do {title}"),
1469            std::path::PathBuf::from("."),
1470            Source::Human,
1471        )
1472    }
1473
1474    #[test]
1475    fn delivery_bookkeeping_does_not_restart_conductor_deliberation() {
1476        let mut t = task("waiting");
1477        t.hold_machine(Some("waiting for recovery".into()));
1478        let before = input_fingerprint(&t);
1479        let snapshot = decision_input(&t);
1480        t.chat_notice = Some(crate::queue::ChatNotice {
1481            key: t.chat_notice_key().unwrap(),
1482            at: jiff::Timestamp::now(),
1483            outcome: crate::queue::ChatNoticeOutcome::Posted,
1484        });
1485        t.chat_notices.push(t.chat_notice_key().unwrap());
1486        t.updated_at = jiff::Timestamp::now();
1487        assert_eq!(before, input_fingerprint(&t));
1488        assert_eq!(snapshot, decision_input(&t));
1489        t.hold_reason = Some("recovery remains under consideration".into());
1490        assert_eq!(before, input_fingerprint(&t));
1491        t.record_answer("a different question".into(), "a new decision".into());
1492        assert_ne!(before, input_fingerprint(&t));
1493    }
1494
1495    const BROKEN: &str = "#!/bin/sh\ncat >/dev/null\nexit 3\n";
1496    const GARBAGE: &str = "#!/bin/sh\ncat >/dev/null\nprintf 'not json at all\\n'\n";
1497
1498    fn env(reply: &str) -> BTreeMap<String, String> {
1499        BTreeMap::from([("MOCK_REPLY".to_owned(), reply.to_owned())])
1500    }
1501
1502    const REPLY: &str = "#!/bin/sh\ncat >/dev/null\nprintf '%s\\n' \"$MOCK_REPLY\"\n";
1503
1504    /// A throwaway repo with one commit on `main` and a second branch ahead
1505    /// of it, so `outcome_for`'s own `git::rev_parse` call has a real head to
1506    /// resolve.
1507    fn init_repo_with_branch(dir: &Path, branch: &str) {
1508        use crate::proc::Quiet as _;
1509        let run = |args: &[&str]| {
1510            let out = std::process::Command::new("git")
1511                .args(args)
1512                .current_dir(dir)
1513                .quiet()
1514                .output()
1515                .expect("spawn git");
1516            assert!(
1517                out.status.success(),
1518                "git {args:?} failed: {}",
1519                String::from_utf8_lossy(&out.stderr)
1520            );
1521        };
1522        run(&["init", "-b", "main"]);
1523        run(&["config", "user.name", "magi test"]);
1524        run(&["config", "user.email", "magi@example.com"]);
1525        std::fs::write(dir.join("README.md"), "# fixture\n").unwrap();
1526        run(&["add", "-A"]);
1527        run(&["commit", "-m", "init"]);
1528        run(&["checkout", "-b", branch]);
1529        std::fs::write(dir.join("change.txt"), "x\n").unwrap();
1530        run(&["add", "-A"]);
1531        run(&["commit", "-m", "candidate work"]);
1532    }
1533
1534    fn review_round_with_finding(
1535        round: usize,
1536        finding_id: &str,
1537        title: &str,
1538        addressed: &[&str],
1539        rejected: &[(&str, &str)],
1540    ) -> crate::run::ReviewRound {
1541        crate::run::ReviewRound {
1542            round,
1543            head: "deadbeef".to_owned(),
1544            verified_head: None,
1545            verified_at: None,
1546            reviews: vec![crate::run::ReviewRecord {
1547                attempts: 0,
1548                reviewer: 1,
1549                agent: "mock".to_owned(),
1550                summary: String::new(),
1551                findings: vec![crate::verdict::Finding {
1552                    id: finding_id.to_owned(),
1553                    severity: crate::verdict::Severity::Major,
1554                    file: None,
1555                    line: None,
1556                    title: title.to_owned(),
1557                    detail: String::new(),
1558                }],
1559                vote: None,
1560                failed: None,
1561                duration_ms: 0,
1562            }],
1563            e2e: Vec::new(),
1564            verify_retried: false,
1565            e2e_deferred: false,
1566            e2e_defer_reason: None,
1567            fix: Some(crate::run::FixRecord {
1568                agent: "mock".to_owned(),
1569                addressed: addressed.iter().map(|s| (*s).to_owned()).collect(),
1570                rejected: rejected
1571                    .iter()
1572                    .map(|(id, why)| crate::verdict::Rejection {
1573                        id: (*id).to_owned(),
1574                        why: (*why).to_owned(),
1575                    })
1576                    .collect(),
1577                notes: String::new(),
1578                committed: false,
1579                failed: None,
1580                duration_ms: 0,
1581                continuation: None,
1582            }),
1583            blocking: 1,
1584            answered: 1,
1585            expected: 1,
1586            clean: false,
1587            progressed: true,
1588            vote_split: false,
1589            reconsideration: Vec::new(),
1590            verdict: None,
1591        }
1592    }
1593
1594    #[test]
1595    fn explicit_resumption_supersedes_history_and_rejects_stale_decisions() {
1596        crate::run::pin_test_home();
1597        let dir = tempdir().unwrap();
1598        let queue = Queue::at(dir.path().join("queue"));
1599        let questions = Questions::at(dir.path().join("questions"));
1600        let mut t = task("recover");
1601        t.answers.push(crate::queue::AnsweredQuestion {
1602            question: "Inspect remote first?".into(),
1603            answer: "Inspect, then await resumption instructions".into(),
1604        });
1605        t.hold_machine(Some("waiting for remote inspection".into()));
1606        queue.put(&mut t).unwrap();
1607        let snapshot = queue.get(&t.id).unwrap();
1608        t.edit(
1609            "recover".into(),
1610            "Reuse the measured PR head; fix Clippy; review".into(),
1611        )
1612        .unwrap();
1613        t.release_operator("cli", None);
1614        queue.put(&mut t).unwrap();
1615        let approval = t.resumption.clone();
1616        let d = Decision {
1617            id: t.id.clone(),
1618            recovery: Some(Recovery::Hold),
1619            reason: Some("remote inspection still required".into()),
1620            ..Decision::default()
1621        };
1622        apply_one(&queue, &questions, &d, Some(&snapshot)).unwrap();
1623        let stale_question = Decision {
1624            question: Some("Inspect remote?".into()),
1625            ..d.clone()
1626        };
1627        apply_one(&queue, &questions, &stale_question, Some(&snapshot)).unwrap();
1628        assert!(questions.list().is_empty());
1629        for reason in [
1630            "waiting for remote inspection",
1631            "inspection has not been confirmed",
1632        ] {
1633            let repeated = Decision {
1634                reason: Some(reason.into()),
1635                question: Some("How should we proceed?".into()),
1636                ..d.clone()
1637            };
1638            apply(
1639                &queue,
1640                &questions,
1641                &Verdict {
1642                    decisions: vec![repeated],
1643                },
1644            )
1645            .unwrap();
1646            assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
1647        }
1648        assert!(
1649            questions.list().is_empty(),
1650            "a rejected proposal registers no question"
1651        );
1652        let notice = crate::notices::Notices::open()
1653            .get(&crate::notices::id_of(&format!(
1654                "conductor-resumption:{}",
1655                t.id
1656            )))
1657            .unwrap();
1658        assert!(!notice.message.contains("How should we proceed?"));
1659        assert!(!notice.message.contains("Some("));
1660        assert!(notice.message.contains("No reply to this notice is needed"));
1661        let reloaded = Queue::at(dir.path().join("queue")).get(&t.id).unwrap();
1662        assert_eq!(reloaded.resumption, approval);
1663        assert_eq!(reloaded.answers, t.answers);
1664        let v = view(&reloaded, 3);
1665        assert!(v.operator_resume.unwrap().contains("superseded"));
1666        let mut dep = task("new prerequisite");
1667        dep.hold_machine(Some("new authentication failure".into()));
1668        queue.put(&mut dep).unwrap();
1669        let new_blocker = Decision {
1670            blocked_by: vec![dep.id.clone()],
1671            evidence: vec![dep.id.clone()],
1672            // Exercise dependency waiting, without inheriting a separate hold.
1673            recovery: None,
1674            reason: Some("new prerequisite failed".into()),
1675            ..d.clone()
1676        };
1677        apply(
1678            &queue,
1679            &questions,
1680            &Verdict {
1681                decisions: vec![new_blocker.clone()],
1682            },
1683        )
1684        .unwrap();
1685        let mut after = queue.get(&t.id).unwrap();
1686        assert_eq!(after.status, TaskStatus::Blocked);
1687        // Automatic release does not grant fresh operator authority or make
1688        // the same unchanged evidence reusable.
1689        after.release();
1690        queue.put(&mut after).unwrap();
1691        apply(
1692            &queue,
1693            &questions,
1694            &Verdict {
1695                decisions: vec![new_blocker],
1696            },
1697        )
1698        .unwrap();
1699        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
1700        after.start("new-run".into());
1701        assert_eq!(after.resumption.as_ref().unwrap().generation, 1);
1702        after.hold_manual(Some("operator says wait".into()));
1703        queue.put(&mut after).unwrap();
1704        apply(&queue, &questions, &Verdict { decisions: vec![d] }).unwrap();
1705        assert!(queue.get(&t.id).unwrap().operator_held());
1706    }
1707
1708    #[test]
1709    fn newly_blocked_dependency_is_material_evidence_after_approval() {
1710        let dir = tempdir().unwrap();
1711        let queue = Queue::at(dir.path().join("queue"));
1712        let questions = Questions::at(dir.path().join("questions"));
1713        let mut dep = task("old queued dependency");
1714        queue.put(&mut dep).unwrap();
1715        let mut t = task("approved task");
1716        t.release_operator("test", None);
1717        queue.put(&mut t).unwrap();
1718        let mut q = Question::new(
1719            dep.id.clone(),
1720            "check".into(),
1721            "check".into(),
1722            "New dependency approval".into(),
1723            String::new(),
1724            Vec::new(),
1725        );
1726        questions.put(&mut q).unwrap();
1727        dep.block(vec![q.id.clone()], Some("new decision needed".into()));
1728        let changed = dep.blocked_at;
1729        queue.put(&mut dep).unwrap();
1730        dep.block(vec![q.id], Some("same decision paraphrased".into()));
1731        assert_eq!(
1732            dep.blocked_at, changed,
1733            "prose is not new blocking evidence"
1734        );
1735        queue.put(&mut dep).unwrap();
1736        let d = Decision {
1737            id: t.id.clone(),
1738            blocked_by: vec![dep.id.clone()],
1739            evidence: vec![dep.id],
1740            ..Decision::default()
1741        };
1742        assert_eq!(new_blocking_evidence(&queue, &questions, &t, &d).len(), 1);
1743        apply_one(&queue, &questions, &d, None).unwrap();
1744        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
1745    }
1746
1747    #[test]
1748    fn resumed_run_evidence_uses_approval_time_not_run_list_offsets() {
1749        crate::run::pin_test_home();
1750        let dir = tempdir().unwrap();
1751        let queue = Queue::at(dir.path().join("queue"));
1752        let questions = Questions::at(dir.path().join("questions"));
1753        let mut t = task("resume evidence");
1754        let mut run = RunState::new(
1755            t.repo.clone(),
1756            "main".into(),
1757            "base".into(),
1758            "work".into(),
1759            crate::config::Config::default(),
1760        );
1761        run.begin_pass();
1762        run.status = crate::run::RunStatus::Failed;
1763        run.save().unwrap();
1764        t.start(run.id.clone());
1765        // Model legacy duplicate history, which the next start will deduplicate.
1766        t.runs.push(run.id.clone());
1767        t.release_operator("cli", None);
1768        let approval = t.resumption.as_ref().unwrap().at;
1769        let decision = Decision {
1770            evidence: vec![run.id.clone()],
1771            ..Decision::default()
1772        };
1773        assert!(new_blocking_evidence(&queue, &questions, &t, &decision).is_empty());
1774        t.start(run.id.clone());
1775        assert_eq!(t.runs.len(), 1);
1776        run.begin_pass();
1777        run.save().unwrap();
1778        assert!(run.passes.last().unwrap().started_at > approval);
1779        let evidence = new_blocking_evidence(&queue, &questions, &t, &decision);
1780        assert_eq!(evidence.len(), 1);
1781        t.resumption.as_mut().unwrap().blocking_evidence = evidence;
1782        assert!(new_blocking_evidence(&queue, &questions, &t, &decision).is_empty());
1783        run.begin_pass();
1784        run.save().unwrap();
1785        assert_eq!(
1786            new_blocking_evidence(&queue, &questions, &t, &decision).len(),
1787            1
1788        );
1789
1790        let mut q = Question::new(
1791            run.id.clone(),
1792            "review".into(),
1793            "check".into(),
1794            "New failure".into(),
1795            String::new(),
1796            Vec::new(),
1797        );
1798        questions.put(&mut q).unwrap();
1799        let decision = Decision {
1800            evidence: vec![q.id.clone()],
1801            ..Decision::default()
1802        };
1803        assert_eq!(
1804            new_blocking_evidence(&queue, &questions, &t, &decision).len(),
1805            1
1806        );
1807        q.asked_at = approval;
1808        questions.put(&mut q).unwrap();
1809        assert!(new_blocking_evidence(&queue, &questions, &t, &decision).is_empty());
1810        q.asked_at = jiff::Timestamp::now();
1811        q.run = "unrelated".into();
1812        questions.put(&mut q).unwrap();
1813        assert!(new_blocking_evidence(&queue, &questions, &t, &decision).is_empty());
1814
1815        let mut fresh = RunState::new(
1816            t.repo.clone(),
1817            "main".into(),
1818            "base".into(),
1819            "fresh work".into(),
1820            crate::config::Config::default(),
1821        );
1822        fresh.status = crate::run::RunStatus::Failed;
1823        fresh.save().unwrap();
1824        t.start(fresh.id.clone());
1825        let decision = Decision {
1826            evidence: vec![fresh.id.clone()],
1827            ..Decision::default()
1828        };
1829        assert_eq!(
1830            new_blocking_evidence(&queue, &questions, &t, &decision).len(),
1831            1
1832        );
1833    }
1834
1835    #[test]
1836    fn outcome_for_carries_every_rounds_findings_and_the_branch_head() {
1837        crate::run::pin_test_home();
1838        let dir = tempdir().unwrap();
1839        let default_repo = dir.path().join("default");
1840        let task_repo = dir.path().join("task");
1841        std::fs::create_dir_all(&default_repo).unwrap();
1842        std::fs::create_dir_all(&task_repo).unwrap();
1843        init_repo_with_branch(&default_repo, "other-branch");
1844        init_repo_with_branch(&task_repo, "magi/f00d/A");
1845
1846        let mut config = Config::default();
1847        config.graph.review_rounds = 6;
1848        let mut state = crate::run::RunState::new(
1849            task_repo.clone(),
1850            "main".to_owned(),
1851            "deadbeef".to_owned(),
1852            "task".to_owned(),
1853            config,
1854        );
1855        state.status = crate::run::RunStatus::Blocked;
1856        state.candidates.push(crate::run::Candidate {
1857            index: 0,
1858            label: 'A',
1859            agent: "mock".to_owned(),
1860            branch: "magi/f00d/A".to_owned(),
1861            worktree: task_repo.clone(),
1862            summary: String::new(),
1863            stat: String::new(),
1864            files: 1,
1865            commits: 1,
1866            empty: false,
1867            failed: None,
1868            verified_noop: None,
1869            duration_ms: 0,
1870            folded: false,
1871        });
1872        state.tally = Some(crate::run::Tally {
1873            first_choice: std::collections::BTreeMap::new(),
1874            borda: std::collections::BTreeMap::new(),
1875            winner: 'A',
1876            rankings: 0,
1877            unanimous_initial: false,
1878            deliberated: false,
1879            changed_votes: 0,
1880            unanimous_final: false,
1881            tie_break: None,
1882            judges: 0,
1883            present: 0,
1884            quorum: 0,
1885            met_quorum: true,
1886            uncontested: Some("solo".to_owned()),
1887        });
1888        state.reviews = vec![
1889            review_round_with_finding(
1890                1,
1891                "R1-1-2",
1892                "answer content is dropped",
1893                &[],
1894                &[("R1-1-2", "the id leaving blocked_by is enough")],
1895            ),
1896            review_round_with_finding(2, "R2-1-3", "answer content is still dropped", &[], &[]),
1897        ];
1898        state.save().unwrap();
1899
1900        let mut t = task("outcome test");
1901        t.repo = task_repo;
1902        t.runs.push(state.id.clone());
1903
1904        let finished = tokio_test_block_on(finished_view(&t, &default_repo, 2));
1905        let outcome = finished.outcome;
1906
1907        assert!(outcome.unreadable.is_none());
1908        assert_eq!(outcome.run_status.as_deref(), Some("blocked"));
1909        assert_eq!(outcome.rounds_used, 2);
1910        assert_eq!(outcome.rounds_max, 6);
1911        assert_eq!(outcome.rounds.len(), 2);
1912        assert_eq!(outcome.rounds[0].findings[0].id, "R1-1-2");
1913        assert_eq!(outcome.rounds[0].rejected[0].id, "R1-1-2");
1914        assert!(outcome.rounds[1].addressed.is_empty());
1915        assert!(outcome.rounds[1].rejected.is_empty());
1916        assert_eq!(outcome.branch.as_deref(), Some("magi/f00d/A"));
1917        assert!(
1918            outcome.branch_head.is_some(),
1919            "a real branch must resolve a head commit: {outcome:?}"
1920        );
1921    }
1922
1923    /// A tiny single-threaded block-on, so an `async fn` can be exercised
1924    /// from a plain `#[test]` without pulling `tokio::test`'s multi-thread
1925    /// runtime into a test that does no other async work.
1926    fn tokio_test_block_on<F: std::future::Future>(f: F) -> F::Output {
1927        tokio::runtime::Builder::new_current_thread()
1928            .enable_all()
1929            .build()
1930            .unwrap()
1931            .block_on(f)
1932    }
1933
1934    #[test]
1935    fn view_resolves_task_attempt_limit_before_daemon_default() {
1936        let mut t = task("budget");
1937        assert_eq!(view(&t, 7).max_attempts, 7);
1938        t.change_attempt_limit(std::num::NonZeroUsize::new(3))
1939            .unwrap();
1940        assert_eq!(view(&t, 7).max_attempts, 3);
1941        t.change_attempt_limit(None).unwrap();
1942        assert_eq!(view(&t, 7).max_attempts, 7);
1943    }
1944
1945    #[test]
1946    fn view_carries_a_tasks_recorded_answers_into_the_conductor_prompt_input() {
1947        let mut t = task("answered");
1948        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
1949        let v = view(&t, 2);
1950        assert_eq!(v.answers.len(), 1);
1951        assert_eq!(v.answers[0].question, "Which backend?");
1952        assert_eq!(v.answers[0].answer, "SQLite");
1953    }
1954
1955    #[tokio::test]
1956    async fn dependency_resolution_rechecks_questions_in_the_production_conductor_path() {
1957        for held in [false, true] {
1958            for reference in ["ca5b", "20261013-193611-ca5b"] {
1959                for question in [false, true] {
1960                    let dir = tempdir().unwrap();
1961                    let queue = Queue::at(dir.path().join("queue"));
1962                    let questions = Questions::at(dir.path().join("questions"));
1963                    let mut dep = task("prerequisite");
1964                    dep.id = "20261013-193611-ca5b".into();
1965                    dep.start("existing-run".into());
1966                    queue.put(&mut dep).unwrap();
1967                    let mut waiting = task("waiting");
1968                    if held {
1969                        waiting.hold_machine(Some("dependency could not be located".into()));
1970                    }
1971                    queue.put(&mut waiting).unwrap();
1972                    let missing_reference = if reference == "ca5b" {
1973                        dep.id.as_str()
1974                    } else {
1975                        "ca5b"
1976                    };
1977                    let reply = serde_json::json!({"decisions": [{
1978                        "id": waiting.id, "blocked_by": [reference],
1979                        "missing_dependencies": [missing_reference],
1980                        "question": question.then_some("ca5b is missing; where is its replacement?"),
1981                        "recovery": (!question).then_some("hold"),
1982                        "reason": "ca5b is missing"
1983                    }]}).to_string();
1984                    let cfg = config(mock_agent(dir.path(), REPLY, env(&reply)));
1985                    let (queued, finished) = if held {
1986                        (vec![], vec![waiting.clone()])
1987                    } else {
1988                        (vec![waiting.clone()], vec![])
1989                    };
1990                    Conductor::new()
1991                        .run_once(
1992                            &cfg,
1993                            dir.path(),
1994                            &queue,
1995                            &questions,
1996                            dir.path(),
1997                            &queued,
1998                            &[],
1999                            &finished,
2000                            2,
2001                        )
2002                        .await
2003                        .unwrap();
2004                    let after = queue.get(&waiting.id).unwrap();
2005                    assert_eq!(after.status, TaskStatus::Blocked);
2006                    assert_eq!(after.blocked_by, [dep.id]);
2007                    assert_eq!(after.blocked_from, Some(waiting.status));
2008                    assert!(!after.block_reason.unwrap().contains("missing"));
2009                    assert!(questions.list().is_empty());
2010                    assert_eq!(after.instruction, waiting.instruction);
2011                }
2012            }
2013        }
2014    }
2015
2016    #[tokio::test]
2017    async fn dependency_resolution_inconclusive_missing_only_decisions_keep_waiting() {
2018        for held in [false, true] {
2019            for unknown in [false, true] {
2020                for question in [false, true] {
2021                    let dir = tempdir().unwrap();
2022                    let queue = Queue::at(dir.path().join("queue"));
2023                    let questions = Questions::at(dir.path().join("questions"));
2024                    let mut dep = task("running prerequisite");
2025                    dep.id = "20261013-193611-ca5b".into();
2026                    dep.start("existing-run".into());
2027                    queue.put(&mut dep).unwrap();
2028                    let reference = if unknown {
2029                        // Even an exact, existing task id is Unknown when
2030                        // the question inventory cannot be scanned.
2031                        std::fs::write(questions.root(), "not a directory").unwrap();
2032                        dep.id.clone()
2033                    } else {
2034                        let mut other = task("another prerequisite");
2035                        other.id = "20261014-193611-ca5b".into();
2036                        queue.put(&mut other).unwrap();
2037                        "ca5b".to_owned()
2038                    };
2039                    assert_eq!(
2040                        crate::queue::dependency(&queue, &questions, &reference),
2041                        if unknown {
2042                            crate::queue::Dependency::Unknown
2043                        } else {
2044                            crate::queue::Dependency::Ambiguous
2045                        }
2046                    );
2047                    let mut waiting = task("waiting");
2048                    if held {
2049                        waiting.hold_machine(Some("dependency could not be located".into()));
2050                    }
2051                    queue.put(&mut waiting).unwrap();
2052                    let reply = serde_json::json!({"decisions": [{
2053                        "id": waiting.id, "blocked_by": [reference],
2054                        "missing_dependencies": [reference],
2055                        "question": question.then_some("ca5b is missing"),
2056                        "recovery": (!question).then_some("hold"),
2057                        "reason": "ca5b is missing"
2058                    }]})
2059                    .to_string();
2060                    let cfg = config(mock_agent(dir.path(), REPLY, env(&reply)));
2061                    let (queued, finished) = if held {
2062                        (vec![], vec![waiting.clone()])
2063                    } else {
2064                        (vec![waiting.clone()], vec![])
2065                    };
2066                    Conductor::new()
2067                        .run_once(
2068                            &cfg,
2069                            dir.path(),
2070                            &queue,
2071                            &questions,
2072                            dir.path(),
2073                            &queued,
2074                            &[],
2075                            &finished,
2076                            2,
2077                        )
2078                        .await
2079                        .unwrap();
2080                    let after = queue.get(&waiting.id).unwrap();
2081                    assert_eq!(after.status, TaskStatus::Blocked);
2082                    assert_eq!(after.blocked_by, [reference]);
2083                    assert_eq!(after.blocked_from, Some(waiting.status));
2084                    assert!(!after.block_reason.unwrap().contains("missing"));
2085                    assert_eq!(after.instruction, waiting.instruction);
2086                    if unknown {
2087                        assert!(questions.root().is_file());
2088                    } else {
2089                        assert!(questions.list().is_empty());
2090                    }
2091                }
2092            }
2093        }
2094    }
2095
2096    #[tokio::test]
2097    async fn dependency_resolution_unverifiable_alias_decisions_are_discarded() {
2098        for held in [false, true] {
2099            for unknown in [false, true] {
2100                for question in [false, true] {
2101                    for short_blocker in [false, true] {
2102                        let dir = tempdir().unwrap();
2103                        let queue = Queue::at(dir.path().join("queue"));
2104                        let questions = Questions::at(dir.path().join("questions"));
2105                        let mut dep = task("running prerequisite");
2106                        dep.id = "20261013-193611-ca5b".into();
2107                        dep.start("existing-run".into());
2108                        queue.put(&mut dep).unwrap();
2109                        if unknown {
2110                            std::fs::write(questions.root(), "not a directory").unwrap();
2111                        } else {
2112                            let mut other = task("another prerequisite");
2113                            other.id = "20261014-193611-ca5b".into();
2114                            queue.put(&mut other).unwrap();
2115                        }
2116                        let (blocker, missing) = if short_blocker {
2117                            ("ca5b", dep.id.as_str())
2118                        } else {
2119                            (dep.id.as_str(), "ca5b")
2120                        };
2121                        let mut waiting = task("waiting");
2122                        if held {
2123                            waiting.hold_machine(Some("dependency could not be located".into()));
2124                        }
2125                        queue.put(&mut waiting).unwrap();
2126                        let reply = serde_json::json!({"decisions": [{
2127                            "id": waiting.id, "blocked_by": [blocker],
2128                            "missing_dependencies": [missing],
2129                            "question": question.then_some("ca5b is missing"),
2130                            "recovery": (!question).then_some("hold"),
2131                            "reason": "ca5b is missing"
2132                        }]})
2133                        .to_string();
2134                        let cfg = config(mock_agent(dir.path(), REPLY, env(&reply)));
2135                        let (queued, finished) = if held {
2136                            (vec![], vec![waiting.clone()])
2137                        } else {
2138                            (vec![waiting.clone()], vec![])
2139                        };
2140                        Conductor::new()
2141                            .run_once(
2142                                &cfg,
2143                                dir.path(),
2144                                &queue,
2145                                &questions,
2146                                dir.path(),
2147                                &queued,
2148                                &[],
2149                                &finished,
2150                                2,
2151                            )
2152                            .await
2153                            .unwrap();
2154                        assert_eq!(
2155                            serde_json::to_value(queue.get(&waiting.id).unwrap()).unwrap(),
2156                            serde_json::to_value(&waiting).unwrap(),
2157                            "unverifiable aliases must leave the entire task unchanged"
2158                        );
2159                        if unknown {
2160                            assert!(questions.root().is_file());
2161                        } else {
2162                            assert!(questions.list().is_empty());
2163                        }
2164                    }
2165                }
2166            }
2167        }
2168    }
2169
2170    #[tokio::test]
2171    async fn dependency_resolution_genuine_missing_reference_still_asks() {
2172        let dir = tempdir().unwrap();
2173        let queue = Queue::at(dir.path().join("queue"));
2174        let questions = Questions::at(dir.path().join("questions"));
2175        let mut waiting = task("missing prerequisite");
2176        queue.put(&mut waiting).unwrap();
2177        let reply = serde_json::json!({"decisions": [{
2178            "id": waiting.id, "blocked_by": ["not-present"],
2179            "missing_dependencies": ["not-present"],
2180            "question": "Which prerequisite replaces the missing task?"
2181        }]})
2182        .to_string();
2183        let cfg = config(mock_agent(dir.path(), REPLY, env(&reply)));
2184        Conductor::new()
2185            .run_once(
2186                &cfg,
2187                dir.path(),
2188                &queue,
2189                &questions,
2190                dir.path(),
2191                &[waiting.clone()],
2192                &[],
2193                &[],
2194                2,
2195            )
2196            .await
2197            .unwrap();
2198        let after = queue.get(&waiting.id).unwrap();
2199        assert_eq!(after.status, TaskStatus::Blocked);
2200        assert_eq!(
2201            questions.get(&after.blocked_by[0]).unwrap().summary,
2202            "Which prerequisite replaces the missing task?"
2203        );
2204    }
2205
2206    #[tokio::test]
2207    async fn dependency_resolution_keeps_decisions_during_unrelated_task_progress() {
2208        let dir = tempdir().unwrap();
2209        let queue = Queue::at(dir.path().join("queue"));
2210        let questions = Questions::at(dir.path().join("questions"));
2211        let mut dep = task("prerequisite");
2212        dep.id = "20261013-193611-ca5b".into();
2213        dep.start("existing-run".into());
2214        queue.put(&mut dep).unwrap();
2215        let mut unrelated = task("unrelated work");
2216        unrelated.start("other-run".into());
2217        queue.put(&mut unrelated).unwrap();
2218        // Make the old and new revision distinguishable without relying on
2219        // the filesystem clock advancing while the mock process starts.
2220        std::fs::File::options()
2221            .write(true)
2222            .open(queue.path_of(&unrelated.id))
2223            .unwrap()
2224            .set_times(std::fs::FileTimes::new().set_modified(std::time::UNIX_EPOCH))
2225            .unwrap();
2226        unrelated.succeed(CompletionContext::new(
2227            CompletionActor::DaemonSettle,
2228            None,
2229            dir.path(),
2230            &unrelated,
2231        ));
2232        let mut waiting = task("waiting");
2233        let mut asking = task("needs a product decision");
2234        let mut holding = task("must stay held");
2235        queue.put(&mut waiting).unwrap();
2236        queue.put(&mut asking).unwrap();
2237        queue.put(&mut holding).unwrap();
2238        let reply = serde_json::json!({"decisions": [
2239            {"id": waiting.id, "blocked_by": ["ca5b"], "reason": "wait for implementation"},
2240            {"id": asking.id, "question": "Which behavior do you want?"},
2241            {"id": holding.id, "recovery": "hold", "reason": "already implemented elsewhere"}
2242        ]})
2243        .to_string();
2244        let mut vars = env(&reply);
2245        vars.insert(
2246            "UNRELATED_PATH".into(),
2247            queue.path_of(&unrelated.id).to_string_lossy().into_owned(),
2248        );
2249        vars.insert(
2250            "UNRELATED_RECORD".into(),
2251            serde_json::to_string(&unrelated).unwrap(),
2252        );
2253        let script = r#"#!/bin/sh
2254cat >/dev/null
2255printf '%s' "$UNRELATED_RECORD" > "$UNRELATED_PATH"
2256printf '%s\n' "$MOCK_REPLY"
2257"#;
2258        let cfg = config(mock_agent(dir.path(), script, vars));
2259        Conductor::new()
2260            .run_once(
2261                &cfg,
2262                dir.path(),
2263                &queue,
2264                &questions,
2265                dir.path(),
2266                &[waiting.clone(), asking.clone(), holding.clone()],
2267                &[],
2268                &[],
2269                2,
2270            )
2271            .await
2272            .unwrap();
2273        assert_eq!(queue.get(&unrelated.id).unwrap().status, TaskStatus::Done);
2274        let after = queue.get(&waiting.id).unwrap();
2275        assert_eq!(after.status, TaskStatus::Blocked);
2276        assert_eq!(after.blocked_by, [dep.id]);
2277        let asked = queue.get(&asking.id).unwrap();
2278        assert_eq!(asked.status, TaskStatus::Blocked);
2279        assert_eq!(
2280            questions.get(&asked.blocked_by[0]).unwrap().summary,
2281            "Which behavior do you want?"
2282        );
2283        assert_eq!(queue.get(&holding.id).unwrap().status, TaskStatus::Held);
2284    }
2285
2286    #[test]
2287    fn a_dependency_decision_blocks_the_task_and_leaves_priority_alone() {
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 a = task("a");
2292        a.priority = 9;
2293        queue.put(&mut a).unwrap();
2294
2295        let verdict = Verdict {
2296            decisions: vec![Decision {
2297                id: a.id.clone(),
2298                blocked_by: vec!["20260101-000000-dead".to_owned()],
2299                reason: Some("waits on the other task".to_owned()),
2300                recovery: None,
2301                question: None,
2302                choices: Vec::new(),
2303                actions: BTreeMap::new(),
2304                question_decision: None,
2305                evidence: Vec::new(),
2306                missing_dependencies: Vec::new(),
2307            }],
2308        };
2309        apply(&queue, &questions, &verdict).unwrap();
2310
2311        let back = queue.get(&a.id).unwrap();
2312        assert_eq!(back.status, TaskStatus::Blocked);
2313        assert_eq!(back.blocked_by, ["20260101-000000-dead"]);
2314        assert_eq!(
2315            back.priority, 9,
2316            "the conductor's reply cannot carry priority"
2317        );
2318    }
2319
2320    #[test]
2321    fn a_question_decision_files_one_and_blocks_on_its_id() {
2322        let dir = tempdir().unwrap();
2323        let queue = Queue::at(dir.path().join("queue"));
2324        let questions = Questions::at(dir.path().join("questions"));
2325        let mut t = task("ambiguous");
2326        queue.put(&mut t).unwrap();
2327
2328        let verdict = Verdict {
2329            decisions: vec![Decision {
2330                id: t.id.clone(),
2331                blocked_by: Vec::new(),
2332                reason: Some("which backend?".to_owned()),
2333                recovery: None,
2334                question: Some("Which storage backend?".to_owned()),
2335                choices: vec!["SQLite".to_owned(), "Redis".to_owned()],
2336                actions: BTreeMap::new(),
2337                question_decision: None,
2338                evidence: Vec::new(),
2339                missing_dependencies: Vec::new(),
2340            }],
2341        };
2342        apply(&queue, &questions, &verdict).unwrap();
2343
2344        let back = queue.get(&t.id).unwrap();
2345        assert_eq!(back.status, TaskStatus::Blocked);
2346        assert_eq!(back.blocked_by.len(), 1);
2347        let q = questions.get(&back.blocked_by[0]).unwrap();
2348        assert_eq!(q.summary, "Which storage backend?");
2349        assert_eq!(q.node, NODE);
2350        assert!(q.status.open());
2351    }
2352
2353    #[test]
2354    fn a_task_with_an_open_question_already_reuses_it_rather_than_filing_a_second_one() {
2355        let dir = tempdir().unwrap();
2356        let queue = Queue::at(dir.path().join("queue"));
2357        let questions = Questions::at(dir.path().join("questions"));
2358        let mut t = task("asked once");
2359        queue.put(&mut t).unwrap();
2360
2361        let decision = Decision {
2362            id: t.id.clone(),
2363            reason: Some("still deciding".to_owned()),
2364            question: Some("Which backend?".to_owned()),
2365            ..Decision::default()
2366        };
2367        apply(
2368            &queue,
2369            &questions,
2370            &Verdict {
2371                decisions: vec![decision.clone()],
2372            },
2373        )
2374        .unwrap();
2375        assert_eq!(questions.list().len(), 1);
2376        let first_question_id = queue.get(&t.id).unwrap().blocked_by[0].clone();
2377
2378        // An operator releasing the blocked task by hand, without answering,
2379        // puts it back at `Queued` while the question stays open - exactly
2380        // the case the guard in `apply_one` exists for: a later cycle
2381        // proposing the very same question must reuse it, not file a second.
2382        let mut released = queue.get(&t.id).unwrap();
2383        released.release();
2384        queue.put(&mut released).unwrap();
2385
2386        apply(
2387            &queue,
2388            &questions,
2389            &Verdict {
2390                decisions: vec![decision],
2391            },
2392        )
2393        .unwrap();
2394        assert_eq!(questions.list().len(), 1, "no duplicate question was filed");
2395        let after = queue.get(&t.id).unwrap();
2396        assert_eq!(
2397            after.blocked_by,
2398            [first_question_id],
2399            "the existing open question is reused, not replaced"
2400        );
2401    }
2402
2403    #[test]
2404    fn a_same_id_question_from_another_node_is_not_reused() {
2405        let dir = tempdir().unwrap();
2406        let queue = Queue::at(dir.path().join("queue"));
2407        let questions = Questions::at(dir.path().join("questions"));
2408        let mut t = task("must ask the conductor");
2409        queue.put(&mut t).unwrap();
2410
2411        let mut unrelated = Question::new(
2412            t.id.clone(),
2413            "review".to_owned(),
2414            "reviewer-1".to_owned(),
2415            "An unrelated review question".to_owned(),
2416            String::new(),
2417            Vec::new(),
2418        );
2419        questions.put(&mut unrelated).unwrap();
2420
2421        apply(
2422            &queue,
2423            &questions,
2424            &Verdict {
2425                decisions: vec![Decision {
2426                    id: t.id.clone(),
2427                    question: Some("Which backend?".to_owned()),
2428                    ..Decision::default()
2429                }],
2430            },
2431        )
2432        .unwrap();
2433
2434        let blocked_by = &queue.get(&t.id).unwrap().blocked_by;
2435        assert_eq!(blocked_by.len(), 1);
2436        assert_ne!(blocked_by[0], unrelated.id);
2437        assert!(questions.get(&unrelated.id).unwrap().status.open());
2438        assert_eq!(questions.get(&blocked_by[0]).unwrap().node, NODE);
2439    }
2440
2441    #[test]
2442    fn answering_the_question_lets_the_resolver_clear_the_block_with_the_answer_kept() {
2443        let dir = tempdir().unwrap();
2444        let queue = Queue::at(dir.path().join("queue"));
2445        let questions = Questions::at(dir.path().join("questions"));
2446        let mut t = task("waits on an answer");
2447        queue.put(&mut t).unwrap();
2448
2449        apply(
2450            &queue,
2451            &questions,
2452            &Verdict {
2453                decisions: vec![Decision {
2454                    id: t.id.clone(),
2455                    blocked_by: Vec::new(),
2456                    reason: None,
2457                    recovery: None,
2458                    question: Some("Which backend?".to_owned()),
2459                    choices: Vec::new(),
2460                    actions: BTreeMap::new(),
2461                    question_decision: None,
2462                    evidence: Vec::new(),
2463                    missing_dependencies: Vec::new(),
2464                }],
2465            },
2466        )
2467        .unwrap();
2468        let blocked = queue.get(&t.id).unwrap();
2469        let question_id = blocked.blocked_by[0].clone();
2470
2471        let mut q = questions.get(&question_id).unwrap();
2472        q.answer(Answer::Text("SQLite".to_owned())).unwrap();
2473        questions.put(&mut q).unwrap();
2474        assert_eq!(q.status, QuestionStatus::Answered);
2475
2476        // `crate::daemon::resolve_blockers` is the deterministic resolver
2477        // that actually does this on the real queue; here it is enough to
2478        // prove the pure steps it is built from behave together.
2479        let mut task_after = queue.get(&t.id).unwrap();
2480        task_after.record_answer(q.summary.clone(), "SQLite".to_owned());
2481        task_after.unblock(&question_id);
2482        assert_eq!(task_after.status, TaskStatus::Queued);
2483        assert_eq!(task_after.answers[0].answer, "SQLite");
2484    }
2485
2486    #[test]
2487    fn a_stalled_task_can_be_requeued_or_held() {
2488        let dir = tempdir().unwrap();
2489        let queue = Queue::at(dir.path().join("queue"));
2490        let questions = Questions::at(dir.path().join("questions"));
2491
2492        let mut requeue_me = task("stuck a");
2493        requeue_me.start("run-1".to_owned());
2494        queue.put(&mut requeue_me).unwrap();
2495
2496        let mut hold_me = task("stuck b");
2497        hold_me.start("run-2".to_owned());
2498        queue.put(&mut hold_me).unwrap();
2499
2500        apply(
2501            &queue,
2502            &questions,
2503            &Verdict {
2504                decisions: vec![
2505                    Decision {
2506                        id: requeue_me.id.clone(),
2507                        recovery: Some(Recovery::Requeue),
2508                        ..Decision::default()
2509                    },
2510                    Decision {
2511                        id: hold_me.id.clone(),
2512                        recovery: Some(Recovery::Hold),
2513                        reason: Some("looks broken".to_owned()),
2514                        ..Decision::default()
2515                    },
2516                ],
2517            },
2518        )
2519        .unwrap();
2520
2521        let requeued = queue.get(&requeue_me.id).unwrap();
2522        assert_eq!(requeued.status, TaskStatus::Queued);
2523        assert_eq!(requeued.attempts, 0);
2524
2525        let held = queue.get(&hold_me.id).unwrap();
2526        assert_eq!(held.status, TaskStatus::Held);
2527        assert_eq!(held.hold_reason.as_deref(), Some("looks broken"));
2528    }
2529
2530    #[test]
2531    fn a_machine_held_task_asked_about_restores_to_held_once_answered() {
2532        // Reproduces the reported bug: a task held after burning its
2533        // attempts, once the conductor asks a follow-up question about it,
2534        // must come back `held` - not `queued` - once the question is
2535        // answered, whatever the answer said.
2536        let dir = tempdir().unwrap();
2537        let queue = Queue::at(dir.path().join("queue"));
2538        let questions = Questions::at(dir.path().join("questions"));
2539        let mut t = task("held out of attempts");
2540        t.hold_machine(Some("out of attempts".to_owned()));
2541        queue.put(&mut t).unwrap();
2542
2543        apply(
2544            &queue,
2545            &questions,
2546            &Verdict {
2547                decisions: vec![Decision {
2548                    id: t.id.clone(),
2549                    reason: Some("what should happen to this one?".to_owned()),
2550                    question: Some("Hold it, or try again?".to_owned()),
2551                    ..Decision::default()
2552                }],
2553            },
2554        )
2555        .unwrap();
2556        let blocked = queue.get(&t.id).unwrap();
2557        assert_eq!(blocked.status, TaskStatus::Blocked);
2558        let question_id = blocked.blocked_by[0].clone();
2559
2560        let mut q = questions.get(&question_id).unwrap();
2561        q.answer(Answer::Text("leave it held".to_owned())).unwrap();
2562        questions.put(&mut q).unwrap();
2563
2564        // What `crate::daemon::resolve_blockers` does on the real queue.
2565        let mut after = queue.get(&t.id).unwrap();
2566        after.record_answer(q.summary.clone(), "leave it held".to_owned());
2567        after.unblock(&question_id);
2568        assert_eq!(
2569            after.status,
2570            TaskStatus::Held,
2571            "must not fall back to queued"
2572        );
2573        assert_eq!(after.hold_reason.as_deref(), Some("out of attempts"));
2574    }
2575
2576    #[test]
2577    fn a_reaffirmed_hold_with_no_new_reason_is_not_silently_auto_released_by_triage() {
2578        // A different path to the same bug round 1 fixed: a task
2579        // machine-held for disk pressure, blocked on a conductor question,
2580        // answered "keep it held", and restored to `held`. If the
2581        // conductor's next decision reconfirms `recovery: hold` with no new
2582        // `reason` - allowed, `Decision::reason` is optional - `hold_machine`
2583        // must not silently leave the stale disk-pressure text in place, or
2584        // `crate::triage::run_once` reads it as an unexamined, auto-resolvable
2585        // hold and releases the task straight through the operator's answer
2586        // the instant disk space looks fine again.
2587        let dir = tempdir().unwrap();
2588        let queue = Queue::at(dir.path().join("queue"));
2589        let questions = Questions::at(dir.path().join("questions"));
2590        let mut t = task("disk pressure, then reconsidered");
2591        t.hold_machine(Some(
2592            "not enough free space to start a run: 10 bytes free, 100 required by \
2593             `[disk] min_free_bytes`"
2594                .to_owned(),
2595        ));
2596        t.record_answer(
2597            "How should this be handled?".to_owned(),
2598            "keep it held, a human will look at it later".to_owned(),
2599        );
2600        queue.put(&mut t).unwrap();
2601
2602        apply(
2603            &queue,
2604            &questions,
2605            &Verdict {
2606                decisions: vec![Decision {
2607                    id: t.id.clone(),
2608                    recovery: Some(Recovery::Hold),
2609                    ..Decision::default()
2610                }],
2611            },
2612        )
2613        .unwrap();
2614
2615        let after = queue.get(&t.id).unwrap();
2616        assert_eq!(after.status, TaskStatus::Held);
2617        assert!(
2618            !after
2619                .hold_reason
2620                .as_deref()
2621                .unwrap_or_default()
2622                .starts_with("not enough free space"),
2623            "the stale disk-pressure text must not survive a reconfirmed hold: {:?}",
2624            after.hold_reason
2625        );
2626
2627        // The disk gate would report space is fine now - `crate::triage`
2628        // must not read the old text and release the task through it.
2629        let cfg_dir = tempdir().unwrap();
2630        let config = cfg_dir.path().join("magi.toml");
2631        std::fs::write(&config, "[disk]\nmin_free_bytes = 0\n").unwrap();
2632        let report =
2633            crate::triage::run_once(&queue, &questions, Some(&config), jiff::Timestamp::now());
2634        assert!(report.resumed.is_empty(), "must not be auto-released");
2635        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
2636    }
2637
2638    #[test]
2639    fn explicit_resumption_rehold_requires_new_evidence_and_another_answer() {
2640        crate::run::pin_test_home();
2641        let dir = tempdir().unwrap();
2642        let queue = Queue::at(dir.path().join("queue"));
2643        let questions = Questions::at(dir.path().join("questions"));
2644        let config = dir.path().join("magi.toml");
2645        std::fs::write(&config, "[disk]\nmin_free_bytes = 0\n").unwrap();
2646        let now = jiff::Timestamp::now();
2647        let triage = || crate::triage::run_once(&queue, &questions, Some(&config), now);
2648        let open = || {
2649            questions
2650                .list()
2651                .into_iter()
2652                .filter(|q| q.node == "triage" && q.status.open())
2653                .collect::<Vec<_>>()
2654        };
2655        let hold = Decision {
2656            recovery: Some(Recovery::Hold),
2657            reason: Some("waiting on manual worktree cleanup".to_owned()),
2658            ..Decision::default()
2659        };
2660
2661        let mut t = task("looping hold");
2662        t.hold_machine(Some("waiting on manual worktree cleanup".to_owned()));
2663        queue.put(&mut t).unwrap();
2664        let hold = Decision {
2665            id: t.id.clone(),
2666            ..hold
2667        };
2668
2669        // 1. triage asks the ordinary machine question; the operator resumes.
2670        assert_eq!(triage().asked.len(), 1);
2671        let first = open().remove(0);
2672        let mut q = questions.get(&first.id).unwrap();
2673        let resume = q.choices[0].clone();
2674        q.answer(Answer::Choice(resume)).unwrap();
2675        questions.put(&mut q).unwrap();
2676        assert_eq!(triage().answered.len(), 1);
2677        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
2678
2679        // Rewording the old cause cannot undo the first explicit answer.
2680        apply(
2681            &queue,
2682            &questions,
2683            &Verdict {
2684                decisions: vec![hold.clone()],
2685            },
2686        )
2687        .unwrap();
2688        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
2689        assert!(triage().asked.is_empty());
2690
2691        // A new independently filed check can justify a later hold.
2692        let mut evidence = Question::new(
2693            t.id.clone(),
2694            "preflight".into(),
2695            "check".into(),
2696            "New permission failure".into(),
2697            String::new(),
2698            Vec::new(),
2699        );
2700        questions.put(&mut evidence).unwrap();
2701        let hold = Decision {
2702            evidence: vec![evidence.id.clone()],
2703            reason: Some("new permission check failed".into()),
2704            ..hold
2705        };
2706        apply(
2707            &queue,
2708            &questions,
2709            &Verdict {
2710                decisions: vec![hold.clone()],
2711            },
2712        )
2713        .unwrap();
2714        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
2715
2716        // The new hold earns one question identifying the new evidence.
2717        assert_eq!(triage().asked.len(), 1);
2718        let second = open().remove(0);
2719        assert!(second.detail.contains("new permission check failed"));
2720        assert!(triage().asked.is_empty(), "no duplicate question");
2721        assert_eq!(open().len(), 1);
2722
2723        // Another explicit answer supersedes this later hold too.
2724        let mut q = questions.get(&second.id).unwrap();
2725        let force = q.choices[0].clone();
2726        q.answer(Answer::Choice(force)).unwrap();
2727        questions.put(&mut q).unwrap();
2728        assert_eq!(triage().answered.len(), 1);
2729        apply(
2730            &queue,
2731            &questions,
2732            &Verdict {
2733                decisions: vec![hold],
2734            },
2735        )
2736        .unwrap();
2737        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
2738    }
2739
2740    #[test]
2741    fn conductor_resumption_notice_does_not_solicit_unregistered_questions() {
2742        crate::run::pin_test_home();
2743        let dir = tempdir().unwrap();
2744        let queue = Queue::at(dir.path().join("queue"));
2745        let questions = Questions::at(dir.path().join("questions"));
2746
2747        let mut t = task("task with explicit resumption");
2748        t.status = TaskStatus::Queued;
2749        t.resumption = Some(crate::queue::Resumption {
2750            generation: 1,
2751            source: "test".into(),
2752            question_id: Some("q1".into()),
2753            at: jiff::Timestamp::now(),
2754            instruction: "resume".into(),
2755            answers_through: 0,
2756            runs_through: 0,
2757            cleared_reason: None,
2758            blocking_evidence: Vec::new(),
2759        });
2760        queue.put(&mut t).unwrap();
2761
2762        // Conductor suggests a question and dependencies without new evidence
2763        let decision = Decision {
2764            id: t.id.clone(),
2765            question: Some("How should we proceed with this task?".into()),
2766            blocked_by: vec!["dep-x".into()],
2767            reason: Some("needs clarification".into()),
2768            recovery: Some(Recovery::Hold),
2769            ..Decision::default()
2770        };
2771
2772        apply(
2773            &queue,
2774            &questions,
2775            &Verdict {
2776                decisions: vec![decision],
2777            },
2778        )
2779        .unwrap();
2780
2781        // Task stays Queued (not re-blocked on old evidence)
2782        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
2783        // No question was filed in the questions store
2784        assert!(questions.list().is_empty());
2785
2786        // A notice was filed with human-readable text and task link
2787        let notices = crate::notices::Notices::open();
2788        let notice = notices
2789            .get(&crate::notices::id_of(&format!(
2790                "conductor-resumption:{}",
2791                t.id
2792            )))
2793            .expect("conductor-resumption notice filed");
2794
2795        assert_eq!(
2796            notice.link,
2797            Some(crate::notices::Link::Task { id: t.id.clone() })
2798        );
2799        // Message does NOT contain the question prose to avoid asking for non-existent answers
2800        assert!(!notice.message.contains("How should we proceed"));
2801        // Message explicitly notes that no reply is required
2802        assert!(
2803            notice
2804                .message
2805                .contains("No reply to this notice is needed.")
2806        );
2807        // No raw Rust debug representations
2808        assert!(!notice.message.contains("Some("));
2809        assert!(!notice.message.contains("None"));
2810        assert!(!notice.message.contains("[]"));
2811        assert!(!notice.message.contains("{:?}"));
2812        // Mention proposed dependencies cleanly
2813        assert!(notice.message.contains("Proposed dependencies: dep-x."));
2814    }
2815
2816    #[test]
2817    fn a_runnable_task_can_be_held_directly_without_a_question() {
2818        let dir = tempdir().unwrap();
2819        let queue = Queue::at(dir.path().join("queue"));
2820        let questions = Questions::at(dir.path().join("questions"));
2821        let mut t = task("already answered, should stay put");
2822        queue.put(&mut t).unwrap();
2823
2824        apply(
2825            &queue,
2826            &questions,
2827            &Verdict {
2828                decisions: vec![Decision {
2829                    id: t.id.clone(),
2830                    recovery: Some(Recovery::Hold),
2831                    reason: Some("operator already said keep this held".to_owned()),
2832                    ..Decision::default()
2833                }],
2834            },
2835        )
2836        .unwrap();
2837
2838        let after = queue.get(&t.id).unwrap();
2839        assert_eq!(after.status, TaskStatus::Held);
2840        assert_eq!(after.hold_source, Some(crate::queue::HoldSource::Machine));
2841    }
2842
2843    #[test]
2844    fn done_recovery_closes_a_held_task_whose_goal_is_already_met() {
2845        crate::run::pin_test_home();
2846        // Reproduces the other half of the reported bug (task 6081): once
2847        // the operator's answer says the work already happened outside the
2848        // loop - PR merged, worktree cleaned up - the conductor needs an
2849        // actual terminal state to put the task in, not just a hold it will
2850        // keep being re-asked about.
2851        let dir = tempdir().unwrap();
2852        let queue = Queue::at(dir.path().join("queue"));
2853        let questions = Questions::at(dir.path().join("questions"));
2854        let mut t = task("already merged by hand");
2855        t.hold_machine(Some("branch survived, awaiting a decision".to_owned()));
2856        t.record_answer(
2857            "Handle this one?".to_owned(),
2858            "already merged and cleaned up, close it".to_owned(),
2859        );
2860        queue.put(&mut t).unwrap();
2861
2862        apply(
2863            &queue,
2864            &questions,
2865            &Verdict {
2866                decisions: vec![Decision {
2867                    id: t.id.clone(),
2868                    recovery: Some(Recovery::Done),
2869                    reason: Some("operator confirmed this already landed".to_owned()),
2870                    ..Decision::default()
2871                }],
2872            },
2873        )
2874        .unwrap();
2875
2876        let after = queue.get(&t.id).unwrap();
2877        assert_eq!(after.status, TaskStatus::Done);
2878        assert!(after.hold_reason.is_none());
2879        assert_eq!(after.answers.len(), 1, "the record of why is kept");
2880        let completion = after.completion_history.last().unwrap();
2881        assert_eq!(completion.actor, CompletionActor::Conductor);
2882        assert_eq!(completion.prior_status, TaskStatus::Held);
2883        assert_eq!(
2884            completion.reason.as_deref(),
2885            Some("operator confirmed this already landed")
2886        );
2887    }
2888
2889    #[test]
2890    fn done_recovery_cannot_discard_unknown_retained_work() {
2891        crate::run::pin_test_home();
2892        let dir = tempdir().unwrap();
2893        let queue = Queue::at(dir.path().join("queue"));
2894        let questions = Questions::at(dir.path().join("questions"));
2895        let mut t = task("unfinished retained work");
2896        t.link_run("unknown-completion-run");
2897        t.hold_machine(Some("verification failed".into()));
2898        queue.put(&mut t).unwrap();
2899        let error = apply_one(
2900            &queue,
2901            &questions,
2902            &Decision {
2903                id: t.id.clone(),
2904                recovery: Some(Recovery::Done),
2905                reason: Some("close it".into()),
2906                ..Decision::default()
2907            },
2908            None,
2909        )
2910        .unwrap_err();
2911        assert!(error.to_string().contains("--discard"), "{error:#}");
2912        let after = queue.get(&t.id).unwrap();
2913        assert_eq!(after.status, TaskStatus::Held);
2914        assert_eq!(after.hold_reason, t.hold_reason);
2915        assert_eq!(after.runs, t.runs);
2916        assert!(after.completion_history.is_empty());
2917    }
2918
2919    #[test]
2920    fn done_recovery_is_ignored_for_a_runnable_or_running_task() {
2921        let dir = tempdir().unwrap();
2922        let queue = Queue::at(dir.path().join("queue"));
2923        let questions = Questions::at(dir.path().join("questions"));
2924
2925        let mut queued = task("never ran yet");
2926        queue.put(&mut queued).unwrap();
2927
2928        let mut running = task("mid-run");
2929        running.start("run-1".to_owned());
2930        queue.put(&mut running).unwrap();
2931
2932        for id in [queued.id.clone(), running.id.clone()] {
2933            apply(
2934                &queue,
2935                &questions,
2936                &Verdict {
2937                    decisions: vec![Decision {
2938                        id,
2939                        recovery: Some(Recovery::Done),
2940                        ..Decision::default()
2941                    }],
2942                },
2943            )
2944            .unwrap();
2945        }
2946
2947        assert_eq!(queue.get(&queued.id).unwrap().status, TaskStatus::Queued);
2948        assert_eq!(queue.get(&running.id).unwrap().status, TaskStatus::Running);
2949    }
2950
2951    #[test]
2952    fn a_question_after_two_settled_answers_is_still_filed_and_blocks() {
2953        // A genuine question must stay answerable however many were settled
2954        // before it: refusing it left `magi answer --list` empty.
2955        let dir = tempdir().unwrap();
2956        let queue = Queue::at(dir.path().join("queue"));
2957        let questions = Questions::at(dir.path().join("questions"));
2958        let mut t = task("asked about repeatedly");
2959        t.hold_machine(Some("out of attempts".to_owned()));
2960        t.record_answer("Handle this one? (1)".to_owned(), "not yet".to_owned());
2961        t.record_answer(
2962            "Handle this one? (2)".to_owned(),
2963            "still not yet".to_owned(),
2964        );
2965        queue.put(&mut t).unwrap();
2966        assert_eq!(questions.list().len(), 0);
2967
2968        let verdict = Verdict {
2969            decisions: vec![Decision {
2970                id: t.id.clone(),
2971                question: Some("Branch conflicts with origin/main, how do we proceed?".to_owned()),
2972                ..Decision::default()
2973            }],
2974        };
2975        apply(&queue, &questions, &verdict).unwrap();
2976
2977        let filed = questions.list();
2978        assert_eq!(filed.len(), 1, "the question was filed");
2979        assert_eq!(
2980            filed[0].summary,
2981            "Branch conflicts with origin/main, how do we proceed?"
2982        );
2983        let deputy = filed[0]
2984            .deputy
2985            .as_ref()
2986            .expect("the wait is handed to a deputy");
2987        assert!(deputy.brief.contains(&t.id), "{}", deputy.brief);
2988        assert_eq!(
2989            deputy.starts, 0,
2990            "filing never starts anything: the loop does not wait"
2991        );
2992        assert!(filed[0].status.open());
2993        assert_eq!(filed[0].node, NODE);
2994        let after = queue.get(&t.id).unwrap();
2995        assert_eq!(after.status, TaskStatus::Blocked);
2996        assert_eq!(after.blocked_by, vec![filed[0].id.clone()]);
2997        assert_eq!(after.answers.len(), 2, "the prior answers are untouched");
2998        assert!(
2999            !after
3000                .hold_reason
3001                .clone()
3002                .unwrap_or_default()
3003                .contains("conduct tried to ask"),
3004            "no hold was applied"
3005        );
3006
3007        apply(&queue, &questions, &verdict).unwrap();
3008        let again = questions.list();
3009        assert_eq!(again.len(), 1, "the open question is reused");
3010        assert_eq!(again[0].id, filed[0].id);
3011    }
3012
3013    #[test]
3014    fn question_source_identity_resolves_aliases_and_rejects_invented_targets() {
3015        let dir = tempdir().unwrap();
3016        init_repo_with_branch(dir.path(), "source-a");
3017        let mut t = task("source decision");
3018        t.repo = dir.path().into();
3019        let decision = |reference: &str| QuestionDecision {
3020            operation: QuestionOperation::Recover,
3021            target: QuestionTarget::Source {
3022                reference: reference.into(),
3023            },
3024        };
3025        assert_eq!(
3026            decision("source-a").identity(&t).unwrap(),
3027            decision("refs/heads/source-a").identity(&t).unwrap()
3028        );
3029        assert_ne!(
3030            decision("source-a").identity(&t).unwrap(),
3031            decision("main").identity(&t).unwrap()
3032        );
3033        assert!(decision("invented-source-label").identity(&t).is_err());
3034        let unrelated = QuestionDecision {
3035            operation: QuestionOperation::Resume,
3036            target: QuestionTarget::Run {
3037                id: "unrelated-run".into(),
3038            },
3039        };
3040        assert!(unrelated.identity(&t).is_err());
3041    }
3042
3043    #[test]
3044    fn base_recovery_conductor_cannot_offer_or_requeue_an_unchanged_stop() {
3045        let dir = tempdir().unwrap();
3046        let queue = Queue::at(dir.path().join("queue"));
3047        let questions = Questions::at(dir.path().join("questions"));
3048        let mut t = task("retained base stop");
3049        let mut state = RunState::new(
3050            dir.path().into(),
3051            "main".into(),
3052            "base".into(),
3053            "retained work".into(),
3054            Config::default(),
3055        );
3056        state.base_sync = Some(crate::run::BaseSync {
3057            tip: "tip".into(),
3058            behind: 3,
3059            attempts: 4,
3060            conflict: Some("exhausted".into()),
3061            already_in: None,
3062        });
3063        state.save_under(dir.path()).unwrap();
3064        t.link_run(&state.id);
3065        t.hold_machine(Some("base stopped".into()));
3066        queue.put(&mut t).unwrap();
3067        let d = Decision {
3068            id: t.id.clone(),
3069            recovery: Some(Recovery::Requeue),
3070            ..Decision::default()
3071        };
3072        apply_one(&queue, &questions, &d, None).unwrap();
3073        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
3074        let d = Decision {
3075            id: t.id.clone(),
3076            question: Some("Resume?".into()),
3077            question_decision: Some(QuestionDecision {
3078                operation: QuestionOperation::Resume,
3079                target: QuestionTarget::Run { id: state.id },
3080            }),
3081            ..Decision::default()
3082        };
3083        apply_one(&queue, &questions, &d, None).unwrap();
3084        assert!(questions.list().is_empty());
3085        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
3086    }
3087
3088    #[test]
3089    fn invalid_question_targets_still_file_and_block_queued_tasks() {
3090        let dir = tempdir().unwrap();
3091        init_repo_with_branch(dir.path(), "source-a");
3092        let queue = Queue::at(dir.path().join("queue"));
3093        let questions = Questions::at(dir.path().join("questions"));
3094        for target in [
3095            QuestionTarget::Source {
3096                reference: "missing-source".into(),
3097            },
3098            QuestionTarget::Run {
3099                id: "unrelated-run".into(),
3100            },
3101        ] {
3102            let mut t = task("decision with invalid metadata");
3103            t.repo = dir.path().into();
3104            queue.put(&mut t).unwrap();
3105            let d = Decision {
3106                id: t.id.clone(),
3107                question: Some("Which recovery should proceed?".into()),
3108                choices: vec!["inspect first".into(), "keep waiting".into()],
3109                question_decision: Some(QuestionDecision {
3110                    operation: QuestionOperation::Recover,
3111                    target,
3112                }),
3113                ..Decision::default()
3114            };
3115            apply_one(&queue, &questions, &d, None).unwrap();
3116            let q = questions
3117                .list()
3118                .into_iter()
3119                .find(|q| q.run == t.id)
3120                .unwrap();
3121            assert_eq!(q.summary, d.question.as_deref().unwrap());
3122            assert!(
3123                q.choices.iter().all(|c| q.actions.contains_key(c)),
3124                "manual-only choices must become an executable hold"
3125            );
3126            assert!(q.status.open());
3127            let context: serde_json::Value =
3128                serde_json::from_str(q.decision_context.as_ref().unwrap()).unwrap();
3129            assert!(context[3].is_null(), "invalid metadata was discarded");
3130            let after = queue.get(&t.id).unwrap();
3131            assert_eq!(after.status, TaskStatus::Blocked);
3132            assert_eq!(after.blocked_by, vec![q.id.clone()]);
3133            apply_one(&queue, &questions, &d, None).unwrap();
3134            assert_eq!(questions.list().iter().filter(|q| q.run == t.id).count(), 1);
3135        }
3136    }
3137
3138    #[test]
3139    fn answered_conductor_question_needs_changed_facts_before_reasking() {
3140        let dir = tempdir().unwrap();
3141        let queue = Queue::at(dir.path().join("queue"));
3142        let questions = Questions::at(dir.path().join("questions"));
3143        let mut t = task("recovery decision");
3144        t.hold_machine(Some("out of attempts".into()));
3145        t.runs = vec!["source-run-a".into(), "source-run-b".into()];
3146        queue.put(&mut t).unwrap();
3147        let mut d = Decision {
3148            id: t.id.clone(),
3149            question: Some("Recover from source A?".into()),
3150            choices: vec!["approve source A".into(), "keep held".into()],
3151            question_decision: Some(QuestionDecision {
3152                operation: QuestionOperation::Recover,
3153                target: QuestionTarget::Run {
3154                    id: "source-run-a".into(),
3155                },
3156            }),
3157            ..Decision::default()
3158        };
3159        apply_one(&queue, &questions, &d, None).unwrap();
3160        let mut q = questions.list().pop().unwrap();
3161        q.answer(crate::ask::Answer::Choice(q.choices[0].clone()))
3162            .unwrap();
3163        questions.put(&mut q).unwrap();
3164        queue
3165            .modify(&t.id, |task| {
3166                task.unblock(&q.id);
3167                task.hold_machine(Some("recovery remains under consideration".into()));
3168                true
3169            })
3170            .unwrap();
3171        d.question = Some("Should we keep waiting on recovery?".into());
3172        d.choices = vec!["recover using source A".into(), "remain on hold".into()];
3173        apply_one(&queue, &questions, &d, None).unwrap();
3174        assert_eq!(questions.list().len(), 1, "no repeated operator turn");
3175        d.question = Some("Recover from source B?".into());
3176        // The labels can remain identical while the approval target changes.
3177        d.question_decision.as_mut().unwrap().target = QuestionTarget::Run {
3178            id: "source-run-b".into(),
3179        };
3180        apply_one(&queue, &questions, &d, None).unwrap();
3181        assert_eq!(
3182            questions.list().len(),
3183            2,
3184            "new decision with unchanged task facts"
3185        );
3186        let after = queue.get(&t.id).unwrap();
3187        assert_eq!(after.instruction, t.instruction);
3188        assert_eq!(after.runs, t.runs);
3189        assert_eq!(after.status, TaskStatus::Blocked);
3190    }
3191
3192    #[test]
3193    fn a_second_conductor_question_is_still_allowed_after_one_settled_answer() {
3194        let dir = tempdir().unwrap();
3195        let queue = Queue::at(dir.path().join("queue"));
3196        let questions = Questions::at(dir.path().join("questions"));
3197        let mut t = task("asked about once already");
3198        t.hold_machine(Some("out of attempts".to_owned()));
3199        t.record_answer("Handle this one?".to_owned(), "not yet".to_owned());
3200        queue.put(&mut t).unwrap();
3201
3202        apply(
3203            &queue,
3204            &questions,
3205            &Verdict {
3206                decisions: vec![Decision {
3207                    id: t.id.clone(),
3208                    question: Some("Still not sure - now what?".to_owned()),
3209                    ..Decision::default()
3210                }],
3211            },
3212        )
3213        .unwrap();
3214
3215        assert_eq!(questions.list().len(), 1, "the second question was filed");
3216        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
3217    }
3218
3219    #[test]
3220    fn a_held_task_with_an_open_triage_question_is_left_to_triage() {
3221        // `crate::triage` never calls `Task::block`, and only ever looks at
3222        // tasks still `held` - so a conductor question that moved this task
3223        // to `blocked` would orphan triage's own open question. The guard in
3224        // `apply_one` must leave the task alone until triage's question
3225        // settles.
3226        let dir = tempdir().unwrap();
3227        let queue = Queue::at(dir.path().join("queue"));
3228        let questions = Questions::at(dir.path().join("questions"));
3229        let mut t = task("held, triage already asking about it");
3230        t.hold_machine(Some("cause unclear".to_owned()));
3231        queue.put(&mut t).unwrap();
3232
3233        let mut triage_q = Question::new(
3234            t.id.clone(),
3235            crate::triage::NODE.to_owned(),
3236            "triage".to_owned(),
3237            "Still needed?".to_owned(),
3238            String::new(),
3239            vec![
3240                "resume".to_owned(),
3241                "not yet".to_owned(),
3242                "discard".to_owned(),
3243            ],
3244        );
3245        questions.put(&mut triage_q).unwrap();
3246
3247        for decision in [
3248            Decision {
3249                id: t.id.clone(),
3250                question: Some("what now?".to_owned()),
3251                ..Decision::default()
3252            },
3253            Decision {
3254                id: t.id.clone(),
3255                recovery: Some(Recovery::Requeue),
3256                ..Decision::default()
3257            },
3258        ] {
3259            apply(
3260                &queue,
3261                &questions,
3262                &Verdict {
3263                    decisions: vec![decision],
3264                },
3265            )
3266            .unwrap();
3267        }
3268
3269        let after = queue.get(&t.id).unwrap();
3270        assert_eq!(
3271            after.status,
3272            TaskStatus::Held,
3273            "triage still owns this hold"
3274        );
3275        assert!(after.blocked_by.is_empty());
3276        assert_eq!(
3277            questions.list().len(),
3278            1,
3279            "no second, conductor-owned question was filed"
3280        );
3281    }
3282
3283    #[test]
3284    fn a_held_task_with_an_answered_but_unapplied_triage_question_is_still_left_alone() {
3285        // The race `crate::triage::pending_for` exists to close: the
3286        // operator has already answered the triage question (it is no
3287        // longer `open`), but `crate::triage::run_once` - which only runs on
3288        // a fully idle daemon tick, far less often than the conductor polls
3289        // - has not had a turn to apply it yet. `apply_one` must not treat
3290        // "not open" as "settled" here, or it would block the task out from
3291        // under an answer triage has not read back yet.
3292        let dir = tempdir().unwrap();
3293        let queue = Queue::at(dir.path().join("queue"));
3294        let questions = Questions::at(dir.path().join("questions"));
3295        let mut t = task("held, triage question answered but not yet applied");
3296        t.hold_machine(Some("cause unclear".to_owned()));
3297        queue.put(&mut t).unwrap();
3298
3299        let mut triage_q = Question::new(
3300            t.id.clone(),
3301            crate::triage::NODE.to_owned(),
3302            "triage".to_owned(),
3303            "Still needed?".to_owned(),
3304            String::new(),
3305            vec![
3306                "resume".to_owned(),
3307                "not yet".to_owned(),
3308                "discard".to_owned(),
3309            ],
3310        );
3311        questions.put(&mut triage_q).unwrap();
3312        triage_q
3313            .answer(Answer::Choice("not yet".to_owned()))
3314            .unwrap();
3315        questions.put(&mut triage_q).unwrap();
3316        assert!(!triage_q.status.open());
3317
3318        apply(
3319            &queue,
3320            &questions,
3321            &Verdict {
3322                decisions: vec![Decision {
3323                    id: t.id.clone(),
3324                    question: Some("what now?".to_owned()),
3325                    ..Decision::default()
3326                }],
3327            },
3328        )
3329        .unwrap();
3330
3331        let after = queue.get(&t.id).unwrap();
3332        assert_eq!(
3333            after.status,
3334            TaskStatus::Held,
3335            "triage's own answer is not yet applied - conduct must wait"
3336        );
3337        assert_eq!(
3338            questions.list().len(),
3339            1,
3340            "no conductor question was filed over the pending triage answer"
3341        );
3342    }
3343
3344    #[test]
3345    fn manual_hold_rejects_hostile_or_stale_conductor_recovery() {
3346        let dir = tempdir().unwrap();
3347        let queue = Queue::at(dir.path().join("queue"));
3348        let questions = Questions::at(dir.path().join("questions"));
3349        let mut held = task("manual recovery");
3350        held.priority = 300;
3351        held.runs.push("run20260912-224242-daf5".to_owned());
3352        held.hold_manual(Some(
3353            "active manual recovery run20260912-224242-daf5".to_owned(),
3354        ));
3355        queue.put(&mut held).unwrap();
3356
3357        // Every field a conductor may use to alter lifecycle state is ignored:
3358        // requeue/review would dispatch duplicate work, hold could overwrite
3359        // evidence, and a question would turn the hold into `blocked`.
3360        for decision in [
3361            Decision {
3362                id: held.id.clone(),
3363                recovery: Some(Recovery::Requeue),
3364                ..Decision::default()
3365            },
3366            Decision {
3367                id: held.id.clone(),
3368                recovery: Some(Recovery::Hold),
3369                reason: Some("stale replacement reason".to_owned()),
3370                ..Decision::default()
3371            },
3372            Decision {
3373                id: held.id.clone(),
3374                recovery: Some(Recovery::Review),
3375                ..Decision::default()
3376            },
3377            Decision {
3378                id: held.id.clone(),
3379                blocked_by: vec!["other-task".to_owned()],
3380                question: Some("retry now?".to_owned()),
3381                ..Decision::default()
3382            },
3383        ] {
3384            apply(
3385                &queue,
3386                &questions,
3387                &Verdict {
3388                    decisions: vec![decision],
3389                },
3390            )
3391            .unwrap();
3392        }
3393
3394        let after = queue.get(&held.id).unwrap();
3395        assert_eq!(after.status, TaskStatus::Held);
3396        assert!(after.operator_held());
3397        assert_eq!(after.priority, 300);
3398        assert_eq!(after.runs, ["run20260912-224242-daf5"]);
3399        assert_eq!(
3400            after.hold_reason.as_deref(),
3401            Some("active manual recovery run20260912-224242-daf5")
3402        );
3403        assert!(after.blocked_by.is_empty());
3404        assert!(questions.list().is_empty());
3405        assert!(
3406            queue.next_runnable().is_none(),
3407            "must not dispatch a duplicate"
3408        );
3409    }
3410
3411    #[test]
3412    fn machine_holds_remain_recoverable_and_manual_release_is_authorization() {
3413        let dir = tempdir().unwrap();
3414        let queue = Queue::at(dir.path().join("queue"));
3415        let questions = Questions::at(dir.path().join("questions"));
3416
3417        let mut automatic = task("disk gate");
3418        automatic.hold_machine(Some("disk full".to_owned()));
3419        queue.put(&mut automatic).unwrap();
3420        let requeue = || Verdict {
3421            decisions: vec![Decision {
3422                id: automatic.id.clone(),
3423                recovery: Some(Recovery::Requeue),
3424                ..Decision::default()
3425            }],
3426        };
3427        apply(&queue, &questions, &requeue()).unwrap();
3428        assert_eq!(queue.get(&automatic.id).unwrap().status, TaskStatus::Queued);
3429
3430        let mut manual = task("operator gate");
3431        manual.hold_manual(Some("wait for operator".to_owned()));
3432        queue.put(&mut manual).unwrap();
3433        apply(
3434            &queue,
3435            &questions,
3436            &Verdict {
3437                decisions: vec![Decision {
3438                    id: manual.id.clone(),
3439                    recovery: Some(Recovery::Requeue),
3440                    ..Decision::default()
3441                }],
3442            },
3443        )
3444        .unwrap();
3445        assert_eq!(queue.get(&manual.id).unwrap().status, TaskStatus::Held);
3446
3447        // This mirrors the CLI and web release routes: only an explicit
3448        // operator action clears the manual boundary.
3449        let mut released = queue.get(&manual.id).unwrap();
3450        released.release();
3451        queue.put(&mut released).unwrap();
3452        assert_eq!(queue.get(&manual.id).unwrap().status, TaskStatus::Queued);
3453    }
3454
3455    #[test]
3456    fn legacy_reasoned_hold_is_protected_without_losing_its_metadata() {
3457        let dir = tempdir().unwrap();
3458        let queue = Queue::at(dir.path().join("queue"));
3459        let questions = Questions::at(dir.path().join("questions"));
3460        let mut legacy = task("old explicit hold");
3461        legacy.status = TaskStatus::Held;
3462        legacy.hold_reason = Some("manual recovery already active".to_owned());
3463        legacy.hold_source = None;
3464        legacy.blocked_by = vec!["dependency".to_owned()];
3465        queue.put(&mut legacy).unwrap();
3466
3467        apply(
3468            &queue,
3469            &questions,
3470            &Verdict {
3471                decisions: vec![Decision {
3472                    id: legacy.id.clone(),
3473                    recovery: Some(Recovery::Requeue),
3474                    ..Decision::default()
3475                }],
3476            },
3477        )
3478        .unwrap();
3479
3480        let after = queue.get(&legacy.id).unwrap();
3481        assert_eq!(after.status, TaskStatus::Held);
3482        assert_eq!(after.hold_source, None);
3483        assert_eq!(after.hold_reason, legacy.hold_reason);
3484        assert_eq!(after.blocked_by, legacy.blocked_by);
3485    }
3486
3487    #[test]
3488    fn review_recovery_is_a_no_op_without_a_survivable_branch() {
3489        // `surviving_branch` reaches `RunState::load`, which reaches the
3490        // process-global `run::home()` - a `OnceLock`, so this only wins the
3491        // race the first time it runs in the binary; every other test still
3492        // reaches the same directory whichever call won, and this test's own
3493        // run id never collides with another test's.
3494        crate::run::pin_test_home();
3495        let dir = tempdir().unwrap();
3496        let queue = Queue::at(dir.path().join("queue"));
3497        let questions = Questions::at(dir.path().join("questions"));
3498        let mut t = task("blocked with no readable run");
3499        t.start("20260101-000000-dead".to_owned()); // no such run on disk
3500        t.fail("blocked", 5);
3501        queue.put(&mut t).unwrap();
3502
3503        apply(
3504            &queue,
3505            &questions,
3506            &Verdict {
3507                decisions: vec![Decision {
3508                    id: t.id.clone(),
3509                    recovery: Some(Recovery::Review),
3510                    ..Decision::default()
3511                }],
3512            },
3513        )
3514        .unwrap();
3515
3516        let after = queue.get(&t.id).unwrap();
3517        assert_eq!(
3518            after.status,
3519            TaskStatus::Failed,
3520            "with nothing to reopen, the decision is dropped rather than guessed at"
3521        );
3522        assert!(after.review_branch.is_none());
3523    }
3524
3525    #[test]
3526    fn requeue_and_review_recovery_are_ignored_for_a_runnable_task() {
3527        // `Hold` is the one exception - see `Decision::recovery`'s doc and
3528        // `a_runnable_task_can_be_held_directly_without_a_question` - but a
3529        // task already in line has nothing for `requeue` or `review` to do.
3530        let dir = tempdir().unwrap();
3531        let queue = Queue::at(dir.path().join("queue"));
3532        let questions = Questions::at(dir.path().join("questions"));
3533
3534        for recovery in [Recovery::Requeue, Recovery::Review] {
3535            let mut t = task("ordinary");
3536            queue.put(&mut t).unwrap();
3537
3538            apply(
3539                &queue,
3540                &questions,
3541                &Verdict {
3542                    decisions: vec![Decision {
3543                        id: t.id.clone(),
3544                        recovery: Some(recovery),
3545                        ..Decision::default()
3546                    }],
3547                },
3548            )
3549            .unwrap();
3550
3551            assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
3552        }
3553    }
3554
3555    #[tokio::test]
3556    async fn a_broken_agent_leaves_the_queue_untouched_and_does_not_error() {
3557        let dir = tempdir().unwrap();
3558        let cfg = config(mock_agent(dir.path(), BROKEN, BTreeMap::new()));
3559        let queue = Queue::at(dir.path().join("queue"));
3560        let questions = Questions::at(dir.path().join("questions"));
3561        let mut t = task("normal");
3562        queue.put(&mut t).unwrap();
3563
3564        let mut conductor = Conductor::new();
3565        conductor
3566            .maybe_run(
3567                &cfg,
3568                dir.path(),
3569                &queue,
3570                &questions,
3571                dir.path(),
3572                &[t.clone()],
3573                &[],
3574                &[],
3575                2,
3576            )
3577            .await;
3578
3579        assert_eq!(
3580            queue.get(&t.id).unwrap().status,
3581            TaskStatus::Queued,
3582            "a failed invocation must change nothing"
3583        );
3584        assert!(
3585            queue.next_runnable().is_some(),
3586            "the loop must still be able to take the next task"
3587        );
3588    }
3589
3590    #[tokio::test]
3591    async fn a_reply_with_no_json_leaves_the_queue_untouched() {
3592        let dir = tempdir().unwrap();
3593        let cfg = config(mock_agent(dir.path(), GARBAGE, BTreeMap::new()));
3594        let queue = Queue::at(dir.path().join("queue"));
3595        let questions = Questions::at(dir.path().join("questions"));
3596        let mut t = task("normal");
3597        queue.put(&mut t).unwrap();
3598
3599        let mut conductor = Conductor::new();
3600        conductor
3601            .maybe_run(
3602                &cfg,
3603                dir.path(),
3604                &queue,
3605                &questions,
3606                dir.path(),
3607                &[t.clone()],
3608                &[],
3609                &[],
3610                2,
3611            )
3612            .await;
3613
3614        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
3615    }
3616
3617    #[tokio::test]
3618    async fn a_conductor_chain_falls_to_the_next_agent_once_each() {
3619        let dir = tempdir().unwrap();
3620        let mut t = task("chained");
3621        let reply = format!(
3622            "{{\"decisions\":[{{\"id\":\"{}\",\"blocked_by\":[\"x\"],\"reason\":\"why\"}}]}}",
3623            t.id
3624        );
3625        let counted = |id: &str, tail: &str| {
3626            let calls = dir.path().join(format!("{id}.calls"));
3627            let path = dir.path().join(format!("{id}.sh"));
3628            std::fs::write(
3629                &path,
3630                format!(
3631                    "#!/bin/sh\ncat >/dev/null\necho x >> '{}'\n{tail}\n",
3632                    calls.display()
3633                ),
3634            )
3635            .unwrap();
3636            AgentSpec {
3637                id: id.to_owned(),
3638                kind: AgentKind::Command,
3639                model: None,
3640                command: vec!["sh".to_owned(), path.to_string_lossy().into_owned()],
3641                extra_args: Vec::new(),
3642                env: BTreeMap::new(),
3643                prompt_delivery: None,
3644                max_turn_secs: None,
3645            }
3646        };
3647        let n_calls = |id: &str| {
3648            std::fs::read_to_string(dir.path().join(format!("{id}.calls")))
3649                .map_or(0, |s| s.lines().count())
3650        };
3651        let mut cfg = config(counted("a", "exit 3"));
3652        cfg.agents = vec![
3653            counted("a", "exit 3"),
3654            counted("b", &format!("printf '%s' '{reply}'")),
3655        ];
3656        cfg.roles.conductor = Some(crate::config::AgentChoice::Chain(vec![
3657            "a".into(),
3658            "b".into(),
3659            "a".into(),
3660        ]));
3661        let queue = Queue::at(dir.path().join("queue"));
3662        let questions = Questions::at(dir.path().join("questions"));
3663        queue.put(&mut t).unwrap();
3664
3665        let mut conductor = Conductor::new();
3666        conductor
3667            .maybe_run(
3668                &cfg,
3669                dir.path(),
3670                &queue,
3671                &questions,
3672                dir.path(),
3673                &[t.clone()],
3674                &[],
3675                &[],
3676                2,
3677            )
3678            .await;
3679
3680        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
3681        assert_eq!(n_calls("a"), 1, "each id is tried once");
3682        assert_eq!(n_calls("b"), 1);
3683        let saved = std::fs::read_to_string(seat_path(dir.path())).unwrap();
3684        assert!(
3685            saved.contains("\"b\""),
3686            "the seat on disk is the one that ran: {saved}"
3687        );
3688    }
3689
3690    #[tokio::test]
3691    async fn json_survives_code_fences_and_a_preamble() {
3692        let dir = tempdir().unwrap();
3693        let mut t = task("fenced");
3694        let reply = format!(
3695            "Sure, here is my decision.\n\n```json\n{{\"decisions\":[{{\"id\":\"{}\",\
3696             \"blocked_by\":[\"x\"],\"reason\":\"why\"}}]}}\n```\n",
3697            t.id
3698        );
3699        let cfg = config(mock_agent(dir.path(), REPLY, env(&reply)));
3700        let queue = Queue::at(dir.path().join("queue"));
3701        let questions = Questions::at(dir.path().join("questions"));
3702        queue.put(&mut t).unwrap();
3703
3704        let mut conductor = Conductor::new();
3705        conductor
3706            .maybe_run(
3707                &cfg,
3708                dir.path(),
3709                &queue,
3710                &questions,
3711                dir.path(),
3712                &[t.clone()],
3713                &[],
3714                &[],
3715                2,
3716            )
3717            .await;
3718
3719        let back = queue.get(&t.id).unwrap();
3720        assert_eq!(back.status, TaskStatus::Blocked);
3721        assert_eq!(back.blocked_by, ["x"]);
3722    }
3723
3724    #[tokio::test]
3725    async fn the_conductor_is_not_called_again_when_nothing_worth_looking_at_has_changed() {
3726        // Each real invocation writes its own artifact stem, `turn-<n>`, so
3727        // whether a second one happened is read off the artifacts directory.
3728        let dir = tempdir().unwrap();
3729        let cfg = config(mock_agent(dir.path(), REPLY, env("{\"decisions\":[]}")));
3730        let queue = Queue::at(dir.path().join("queue"));
3731        let questions = Questions::at(dir.path().join("questions"));
3732        let mut t = task("stable");
3733        queue.put(&mut t).unwrap();
3734        let artifacts = dir.path().join("conduct").join("artifacts");
3735        let turn = |n: usize| artifacts.join(format!("turn-{n}.out"));
3736
3737        let mut conductor = Conductor::new();
3738        conductor
3739            .maybe_run(
3740                &cfg,
3741                dir.path(),
3742                &queue,
3743                &questions,
3744                dir.path(),
3745                &[t.clone()],
3746                &[],
3747                &[],
3748                2,
3749            )
3750            .await;
3751        assert!(turn(1).is_file(), "the first cycle must call the conductor");
3752
3753        conductor
3754            .maybe_run(
3755                &cfg,
3756                dir.path(),
3757                &queue,
3758                &questions,
3759                dir.path(),
3760                &[t.clone()],
3761                &[],
3762                &[],
3763                2,
3764            )
3765            .await;
3766        assert!(
3767            !turn(2).is_file(),
3768            "an unchanged revision and an unchanged stalled/finished set must not call the \
3769             conductor twice"
3770        );
3771
3772        // Once the queue actually changes, the next `maybe_run` calls again.
3773        t.priority = 1;
3774        queue.put(&mut t).unwrap();
3775        conductor
3776            .maybe_run(
3777                &cfg,
3778                dir.path(),
3779                &queue,
3780                &questions,
3781                dir.path(),
3782                &[t.clone()],
3783                &[],
3784                &[],
3785                2,
3786            )
3787            .await;
3788        assert!(turn(2).is_file(), "a moved revision calls it again");
3789    }
3790
3791    #[tokio::test]
3792    async fn a_task_turning_stalled_calls_the_conductor_again_despite_an_unchanged_revision() {
3793        // The queue's own revision has not moved - nothing wrote to it - but
3794        // a task now looks stalled, purely because time passed. Calling
3795        // again here, and never again once this exact set has been shown
3796        // once, is the whole point of keying `worth_a_look` on the id set
3797        // rather than on "is it non-empty".
3798        let dir = tempdir().unwrap();
3799        let cfg = config(mock_agent(dir.path(), REPLY, env("{\"decisions\":[]}")));
3800        let queue = Queue::at(dir.path().join("queue"));
3801        let questions = Questions::at(dir.path().join("questions"));
3802        let mut t = task("quiet");
3803        queue.put(&mut t).unwrap();
3804        let artifacts = dir.path().join("conduct").join("artifacts");
3805        let turn = |n: usize| artifacts.join(format!("turn-{n}.out"));
3806
3807        let mut conductor = Conductor::new();
3808        conductor
3809            .maybe_run(
3810                &cfg,
3811                dir.path(),
3812                &queue,
3813                &questions,
3814                dir.path(),
3815                &[t.clone()],
3816                &[],
3817                &[],
3818                2,
3819            )
3820            .await;
3821        assert!(turn(1).is_file());
3822
3823        conductor
3824            .maybe_run(
3825                &cfg,
3826                dir.path(),
3827                &queue,
3828                &questions,
3829                dir.path(),
3830                &[],
3831                &[t.clone()],
3832                &[],
3833                2,
3834            )
3835            .await;
3836        assert!(
3837            turn(2).is_file(),
3838            "a task turning stalled must call the conductor again"
3839        );
3840
3841        // But once shown at this exact revision, showing the *same* stalled
3842        // set again must not call a third time.
3843        conductor
3844            .maybe_run(
3845                &cfg,
3846                dir.path(),
3847                &queue,
3848                &questions,
3849                dir.path(),
3850                &[],
3851                &[t.clone()],
3852                &[],
3853                2,
3854            )
3855            .await;
3856        assert!(
3857            !turn(3).is_file(),
3858            "the same stalled task lingering must not call the conductor every cycle"
3859        );
3860    }
3861
3862    fn rehold(queue: &Queue, questions: &Questions, id: &str, note: &str) {
3863        apply(
3864            queue,
3865            questions,
3866            &Verdict {
3867                decisions: vec![Decision {
3868                    id: id.to_owned(),
3869                    reason: Some(note.to_owned()),
3870                    recovery: Some(Recovery::Hold),
3871                    ..Decision::default()
3872                }],
3873            },
3874        )
3875        .unwrap();
3876    }
3877
3878    #[test]
3879    fn reholding_with_an_identical_note_changes_nothing() {
3880        let dir = tempdir().unwrap();
3881        let queue = Queue::at(dir.path().join("queue"));
3882        let questions = Questions::at(dir.path().join("questions"));
3883        let mut t = task("held");
3884        t.hold_machine(Some("waiting on a human".to_owned()));
3885        queue.put(&mut t).unwrap();
3886
3887        rehold(&queue, &questions, &t.id, "owner said keep it held");
3888        let first = queue.get(&t.id).unwrap();
3889        let rev = queue.revision();
3890        for _ in 0..5 {
3891            rehold(&queue, &questions, &t.id, "owner said keep it held");
3892        }
3893        let after = queue.get(&t.id).unwrap();
3894        assert_eq!(after.hold_reason, first.hold_reason);
3895        assert_eq!(after.updated_at, first.updated_at);
3896        assert_eq!(queue.revision(), rev, "nothing was written");
3897    }
3898
3899    #[test]
3900    fn reholding_with_different_notes_keeps_one_previously_level() {
3901        let dir = tempdir().unwrap();
3902        let queue = Queue::at(dir.path().join("queue"));
3903        let questions = Questions::at(dir.path().join("questions"));
3904        let mut t = task("held");
3905        t.hold_machine(Some("original".to_owned()));
3906        queue.put(&mut t).unwrap();
3907
3908        for i in 0..20 {
3909            rehold(&queue, &questions, &t.id, &format!("note {}", i % 2));
3910        }
3911        let reason = queue.get(&t.id).unwrap().hold_reason.unwrap();
3912        assert_eq!(reason.matches("(previously:").count(), 1, "{reason}");
3913        assert!(reason.starts_with("note "), "the new note leads: {reason}");
3914    }
3915
3916    #[test]
3917    fn an_already_nested_reason_is_matched_by_its_outermost_note() {
3918        let mut t = task("deep");
3919        let nested = "same\n\n(previously: same\n\n(previously: same))";
3920        t.hold_machine(Some(nested.to_owned()));
3921        let d = Decision {
3922            id: t.id.clone(),
3923            reason: Some("same".to_owned()),
3924            ..Decision::default()
3925        };
3926        assert_eq!(reaffirmed_hold_reason(&t, &d), None);
3927        let d2 = Decision {
3928            reason: Some("other".to_owned()),
3929            ..d
3930        };
3931        assert_eq!(
3932            reaffirmed_hold_reason(&t, &d2).as_deref(),
3933            Some("other\n\n(previously: same)")
3934        );
3935    }
3936
3937    #[tokio::test]
3938    async fn a_repeated_hold_decision_settles_instead_of_looping() {
3939        let dir = tempdir().unwrap();
3940        let queue = Queue::at(dir.path().join("queue"));
3941        let questions = Questions::at(dir.path().join("questions"));
3942        let reply = r#"{"decisions":[{"id":"ID","reason":"keep held","recovery":"hold"}]}"#;
3943        let mut t = task("held");
3944        t.hold_machine(Some("first".to_owned()));
3945        queue.put(&mut t).unwrap();
3946        let cfg = config(mock_agent(
3947            dir.path(),
3948            REPLY,
3949            env(&reply.replace("ID", &t.id)),
3950        ));
3951        let mut conductor = Conductor::new();
3952        // Cycle 1 writes the new note; cycle 2 repeats it and writes nothing.
3953        for _ in 0..2 {
3954            let held = queue.get(&t.id).unwrap();
3955            conductor
3956                .maybe_run(
3957                    &cfg,
3958                    dir.path(),
3959                    &queue,
3960                    &questions,
3961                    dir.path(),
3962                    &[],
3963                    &[],
3964                    &[held],
3965                    2,
3966                )
3967                .await;
3968        }
3969        let held = queue.get(&t.id).unwrap();
3970        assert!(
3971            held.hold_reason
3972                .as_deref()
3973                .unwrap()
3974                .starts_with("keep held")
3975        );
3976        assert!(
3977            !conductor.worth_a_look(&queue, &[], &[held]),
3978            "an unchanged held task must stop being reconsidered"
3979        );
3980    }
3981
3982    #[tokio::test]
3983    async fn alternating_wording_does_not_keep_a_held_task_in_the_loop() {
3984        let dir = tempdir().unwrap();
3985        let queue = Queue::at(dir.path().join("queue"));
3986        let questions = Questions::at(dir.path().join("questions"));
3987        let mut t = task("held");
3988        t.hold_machine(Some("first".to_owned()));
3989        queue.put(&mut t).unwrap();
3990        let reply = |note: &str| {
3991            format!(
3992                r#"{{"decisions":[{{"id":"{}","reason":"{note}","recovery":"hold"}}]}}"#,
3993                t.id
3994            )
3995        };
3996        let cfg_a = config(mock_agent(dir.path(), REPLY, env(&reply("keep held"))));
3997        let cfg_b = config(mock_agent(dir.path(), REPLY, env(&reply("leave held"))));
3998        let mut conductor = Conductor::new();
3999        let mut writes = 0;
4000        for i in 0..6 {
4001            let held = queue.get(&t.id).unwrap();
4002            let before = queue.revision();
4003            conductor
4004                .maybe_run(
4005                    if i % 2 == 0 { &cfg_a } else { &cfg_b },
4006                    dir.path(),
4007                    &queue,
4008                    &questions,
4009                    dir.path(),
4010                    &[],
4011                    &[],
4012                    &[held],
4013                    2,
4014                )
4015                .await;
4016            if queue.revision() != before {
4017                writes += 1;
4018            }
4019        }
4020        assert!(writes <= 2, "the loop must settle, saw {writes} writes");
4021        let mut held = queue.get(&t.id).unwrap();
4022        held.instruction.push_str(" (edited)");
4023        queue.put(&mut held).unwrap();
4024        let held = queue.get(&t.id).unwrap();
4025        assert!(conductor.worth_a_look(&queue, &[], &[held]));
4026    }
4027
4028    #[test]
4029    fn worth_a_look_is_config_free_and_matches_maybe_runs_own_gate() {
4030        let dir = tempdir().unwrap();
4031        let queue = Queue::at(dir.path().join("queue"));
4032        let mut t = task("t");
4033        queue.put(&mut t).unwrap();
4034
4035        let mut conductor = Conductor::new();
4036        assert!(
4037            conductor.worth_a_look(&queue, &[], &[]),
4038            "a conductor that has never run has something to look at"
4039        );
4040
4041        conductor.last_seen = Some(conductor.snapshot(&queue, &[], &[]));
4042        assert!(
4043            !conductor.worth_a_look(&queue, &[], &[]),
4044            "nothing changed and nothing is stalled or finished"
4045        );
4046        assert!(
4047            conductor.worth_a_look(&queue, &[t.clone()], &[]),
4048            "a stalled task is worth a look even at the same revision"
4049        );
4050        assert!(
4051            conductor.worth_a_look(&queue, &[], &[t.clone()]),
4052            "a finished task is worth a look even at the same revision"
4053        );
4054    }
4055
4056    #[tokio::test]
4057    async fn the_conduct_path_never_calls_ask_and_wait() {
4058        // Structural: grepping this module and `daemon.rs` for
4059        // `ask_and_wait` is the actual assertion this module's own doc
4060        // promises; this test exists so the promise has a name in the test
4061        // output too. `apply_one`'s question path uses `Questions::put`
4062        // exclusively.
4063        let dir = tempdir().unwrap();
4064        let queue = Queue::at(dir.path().join("queue"));
4065        let questions = Questions::at(dir.path().join("questions"));
4066        let mut t = task("asks without blocking");
4067        queue.put(&mut t).unwrap();
4068
4069        apply(
4070            &queue,
4071            &questions,
4072            &Verdict {
4073                decisions: vec![Decision {
4074                    id: t.id.clone(),
4075                    question: Some("ok?".to_owned()),
4076                    ..Decision::default()
4077                }],
4078            },
4079        )
4080        .unwrap();
4081        // Reaching here at all (no hang) is the assertion.
4082        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
4083    }
4084
4085    #[test]
4086    fn a_pinned_resume_is_not_held_or_requeued_by_the_conductor() {
4087        let mut t = Task::new("t".into(), "t".into(), PathBuf::new(), Source::Human);
4088        t.resume_override = Some(crate::queue::OperatorResume {
4089            question_id: "q".into(),
4090            at: jiff::Timestamp::now(),
4091            conductor_rehold: None,
4092            forced: false,
4093            pinned_run: Some("run-1".into()),
4094        });
4095        assert!(pinned_resume(&t));
4096        assert!(!may_hold(&mut t, "waiting for magi resume"));
4097        assert!(
4098            t.resume_override
4099                .as_ref()
4100                .unwrap()
4101                .conductor_rehold
4102                .is_none(),
4103            "a refused hold is not recorded as an override"
4104        );
4105        t.resume_override = None;
4106        assert!(!pinned_resume(&t));
4107        assert!(may_hold(&mut t, "no override, so a hold is allowed"));
4108    }
4109
4110    #[test]
4111    fn a_pinned_resume_is_not_blocked_by_a_conductor_question_or_dependency() {
4112        let dir = tempdir().unwrap();
4113        let queue = Queue::at(dir.path().join("queue"));
4114        let questions = Questions::at(dir.path().join("questions"));
4115        let mut t = task("resume me");
4116        t.resume_override = Some(crate::queue::OperatorResume {
4117            question_id: "q".into(),
4118            at: jiff::Timestamp::now(),
4119            conductor_rehold: None,
4120            forced: true,
4121            pinned_run: Some("run-1".into()),
4122        });
4123        queue.put(&mut t).unwrap();
4124
4125        apply(
4126            &queue,
4127            &questions,
4128            &Verdict {
4129                decisions: vec![
4130                    Decision {
4131                        id: t.id.clone(),
4132                        question: Some("really?".to_owned()),
4133                        ..Decision::default()
4134                    },
4135                    Decision {
4136                        id: t.id.clone(),
4137                        blocked_by: vec!["other".to_owned()],
4138                        ..Decision::default()
4139                    },
4140                ],
4141            },
4142        )
4143        .unwrap();
4144
4145        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
4146        assert!(questions.list().is_empty());
4147    }
4148}