magi-cli 0.278.0

Blind multi-agent implementation competition: N agents implement, M judges rank blind, deliberate, vote privately, winner survives double review + E2E gate
Documentation
use std::path::Path;
use std::time::{Duration, Instant};

use super::seat_block::PollOutcome;
use magi::daemon;
use magi::queue::{Queue, Task, TaskStatus};
use magi::run::{RunState, RunStatus};

/// A scheduler milestone can span several real runs and Git operations. Bound
/// stalls tightly, but allow more total time under concurrent test load.
pub fn progress_check<'a>(
    home: &'a Path,
    queue: &'a Queue,
    tasks: &'a [&Task],
    stall: Duration,
    outcome: impl Fn(usize, &Task) -> PollOutcome + 'a,
) -> impl FnMut() -> PollOutcome + 'a {
    let mut check = progress_check_at(
        home,
        queue,
        tasks,
        Duration::from_millis(250),
        (stall, stall * 4),
        Instant::now(),
        outcome,
    );
    move || check(Instant::now())
}

pub fn progress_check_at<'a>(
    home: &'a Path,
    queue: &'a Queue,
    tasks: &'a [&Task],
    sample_interval: Duration,
    (stall, absolute_limit): (Duration, Duration),
    start: Instant,
    outcome: impl Fn(usize, &Task) -> PollOutcome + 'a,
) -> impl FnMut(Instant) -> PollOutcome + 'a {
    #[derive(Debug, Default)]
    struct Progress {
        task: Option<(TaskStatus, usize, usize, usize)>,
        run: Option<(String, RunStatus, usize)>,
        control: Option<magi::worker::Control>,
        worker: Option<(String, magi::worker::Status)>,
    }
    let mut observed: Vec<_> = tasks.iter().map(|_| Progress::default()).collect();
    let mut interrupt_state: Option<String> = None;
    let mut last_progress = start;
    let mut next_sample = start;
    move |now| {
        if now < next_sample && now.duration_since(start) < absolute_limit {
            return PollOutcome::Pending;
        }
        next_sample = now + sample_interval;
        // Only track durable state transitions (never wall-clock heartbeats or
        // poll counters like `updated_at` / `daemon.polls`) so a wedged
        // scheduler still triggers the stall bound.
        let current_interrupt = std::fs::read_to_string(home.join("scheduler-interrupt.json")).ok();
        if current_interrupt != interrupt_state {
            interrupt_state = current_interrupt;
            last_progress = now;
        }
        let active_workers = magi::worker::observe_active(home).ok();
        let mut result = PollOutcome::Ready;
        for (i, (task, previous)) in tasks.iter().zip(&mut observed).enumerate() {
            let Ok(task) = queue.get(&task.id) else {
                result = result.and(PollOutcome::Pending);
                continue;
            };
            let current = (
                task.status,
                task.attempts,
                task.runs.len(),
                task.passes.len(),
            );
            if previous.task != Some(current) {
                previous.task = Some(current);
                last_progress = now;
            }
            if let Some(run) = task.runs.last().and_then(|id| RunState::load(id).ok()) {
                let current = (run.id, run.status, run.events.len());
                if previous.run.as_ref().is_none_or(|old| {
                    old.0 != current.0
                        || current.2 > old.2
                        || (current.2 == old.2 && current.1 != old.1)
                }) {
                    previous.run = Some(current);
                    last_progress = now;
                }
            }
            let key = format!("task:{}", task.id);
            if let Ok(control) = magi::worker::control(home, &key)
                && previous.control != control
            {
                previous.control = control;
                last_progress = now;
            }
            if let Some(jobs) = active_workers.as_ref() {
                let worker = jobs
                    .iter()
                    .find(|job| job.key == key)
                    .map(|job| (job.id.clone(), job.status));
                if previous.worker != worker {
                    previous.worker = worker;
                    last_progress = now;
                }
            }
            result = result.and(outcome(i, &task));
        }
        if result == PollOutcome::Pending {
            let reason = if now.duration_since(start) >= absolute_limit {
                format!("scheduler wait exceeded absolute limit of {absolute_limit:?}")
            } else if now.duration_since(last_progress) >= stall {
                format!("no scheduler progress for {stall:?}")
            } else {
                return result;
            };
            return PollOutcome::Failed(format_progress_diagnostic(
                home,
                queue,
                tasks,
                &reason,
                &observed,
                interrupt_state.as_deref(),
            ));
        }
        result
    }
}

fn format_progress_diagnostic(
    home: &Path,
    queue: &Queue,
    tasks: &[&Task],
    reason: &str,
    observed: &[impl std::fmt::Debug],
    interrupt_state: Option<&str>,
) -> String {
    let workers = match magi::worker::observe_active(home) {
        Ok(jobs) => jobs
            .into_iter()
            .map(|job| {
                format!(
                    "{}(kind={}, key={}, status={}, pid={:?})",
                    job.id, job.kind, job.key, job.status, job.pid
                )
            })
            .collect::<Vec<_>>()
            .join(", "),
        Err(err) => format!("<error: {err:#}>"),
    };
    let daemon_status = daemon::read_status(home).map(|r| {
        format!(
            "pid={:?} polls={} idle={} current={:?} skips={:?} wait={:?}",
            r.pid, r.polls, r.idle, r.current, r.dispatch_skips, r.dispatch_wait
        )
    });
    let task_details = tasks
        .iter()
        .map(|spec| {
            let key = format!("task:{}", spec.id);
            let control = magi::worker::control(home, &key)
                .map(|c| format!("{c:?}"))
                .unwrap_or_else(|err| format!("<error: {err:#}>"));
            match queue.get(&spec.id) {
                Ok(task) => {
                    let run_summary = match task.runs.last() {
                        Some(id) => match RunState::load(id) {
                            Ok(run) => format!(
                                "run={} status={:?} parked={} driver_exited={} events={} last_event={:?}",
                                run.id,
                                run.status,
                                run.parked,
                                run.driver_exited,
                                run.events.len(),
                                run.events.last()
                            ),
                            Err(err) => format!("run={id} <load error: {err:#}>"),
                        },
                        None => "run=<none>".to_owned(),
                    };
                    format!(
                        "{}({}) status={:?} attempts={} runs={:?} passes={:?} control={} last_error={:?} park_reason={:?} hold_reason={:?} block_reason={:?} ({run_summary})",
                        task.title,
                        task.id,
                        task.status,
                        task.attempts,
                        task.runs,
                        task.passes,
                        control,
                        task.last_error,
                        task.park_reason,
                        task.hold_reason,
                        task.block_reason
                    )
                }
                Err(err) => format!("{}({}) <queue error: {err:#}> control={control}", spec.title, spec.id),
            }
        })
        .collect::<Vec<_>>()
        .join("; ");
    format!(
        "{reason}: observed={observed:?}; interrupt={}; daemon={daemon_status:?}; active_workers=[{workers}]; tasks=[{task_details}]",
        interrupt_state.unwrap_or("<missing>"),
    )
}