Skip to main content

agentmux_srv_core/backend/cron/
start.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4//! Starting a run once policy lets it (docs/specs/SPEC_JOBS_AND_TEMPLATES_2026_10_24.md
5//! ยง5.1): the job's action (a message to an agent, a task filed, a worker
6//! spawned), and the waiting runs that start when a place frees up.
7
8use std::future::Future;
9use std::pin::Pin;
10use std::sync::Arc;
11
12use super::{CronScheduler, FireOutcome, Fired};
13use crate::backend::jobs;
14use crate::backend::storage::cron::CronJob;
15
16/// What a `task`, `spawn` or `drone` action did.
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub enum ActionOutcome {
19    /// The task was filed: its queue id and card number.
20    Filed { work_id: String, num: i64 },
21    /// The worker is open. Its brief is delivered to it as any message
22    /// is, and the run ends when the worker's first turn does.
23    Spawned { block_id: String, def_id: String, slug: String, brief: String, keep: bool },
24    /// The drone run started. The job's row is running and linked to it
25    /// already, and the drone's end closes it.
26    Drone,
27    Failed(String),
28}
29
30/// Runs a job's `task`, `spawn` or `drone` action (the server installs it: both need
31/// its stores and the spawn path).
32pub type ActionRunner = Arc<dyn Fn(CronJob, String) -> Pin<Box<dyn Future<Output = ActionOutcome> + Send>> + Send + Sync>;
33
34impl CronScheduler {
35    /// Run `task`, `spawn` and `drone` actions through `runner` from now on. Once.
36    pub fn install_actions(&self, runner: ActionRunner) {
37        let _ = self.actions.set(runner);
38    }
39
40    /// Carry out an admitted run: the job's action, then, for an action that
41    /// starts an agent, the delivery of its brief. `scheduled` runs count as
42    /// the job's fires; `late_for` is the slot a late start was due.
43    pub(crate) async fn start_run(&self, job: &CronJob, run_id: Option<String>, scheduled: bool, late_for: Option<i64>) -> Fired {
44        let delivery_started = agentmux_common::time::now_ms();
45        let mut to_deliver = job.clone();
46        let mut worker_started = false;
47        if matches!(job.action_kind.as_str(), "task" | "spawn" | "drone") {
48            let acted = match self.actions.get() {
49                Some(runner) => runner(job.clone(), run_id.clone().unwrap_or_default()).await,
50                None => ActionOutcome::Failed("this build can't run the job's action here".to_string()),
51            };
52            match acted {
53                ActionOutcome::Filed { work_id, num } => {
54                    if let (Some(runs), Some(run_id)) = (self.runs(), &run_id) {
55                        let (runs, run_id, name) = (runs.clone(), run_id.clone(), job.name.clone());
56                        let _ = tokio::task::spawn_blocking(move || runs.task_filed(&run_id, &name, &work_id, num)).await;
57                    }
58                    let outcome = FireOutcome::Delivered { block_id: None };
59                    if scheduled {
60                        self.record_result(&job.id, &outcome);
61                    }
62                    self.publish_changed();
63                    return Fired { run_id, outcome: Some(outcome), waiting: None };
64                }
65                ActionOutcome::Drone => {
66                    let outcome = FireOutcome::Delivered { block_id: None };
67                    if scheduled {
68                        self.record_result(&job.id, &outcome);
69                    }
70                    self.publish_changed();
71                    return Fired { run_id, outcome: Some(outcome), waiting: None };
72                }
73                ActionOutcome::Failed(error) => return self.finish_undelivered(job, run_id, FireOutcome::Failed { error }, scheduled, delivery_started),
74                ActionOutcome::Spawned { block_id, def_id, slug, brief, keep } => {
75                    if let (Some(runs), Some(run_id)) = (self.runs(), &run_id) {
76                        let links = serde_json::json!({ "worker": { "block_id": block_id, "def_id": def_id, "keep": keep } });
77                        let _ = runs.store().job_run_add_links(run_id, &links);
78                    }
79                    (to_deliver.target, to_deliver.target_uid, to_deliver.prompt) = (slug, def_id, brief);
80                    worker_started = true;
81                }
82            }
83        }
84        let Some(mut outcome) = self.deliver(&to_deliver, run_id.as_deref(), late_for).await else {
85            let failed = FireOutcome::Failed { error: "no way to deliver".to_string() };
86            if let (Some(runs), Some(run_id)) = (self.runs(), &run_id) {
87                runs.record_delivery(run_id, &to_deliver, &failed, false, delivery_started);
88            }
89            return Fired { run_id, outcome: None, waiting: None };
90        };
91        if worker_started && !outcome.delivered() {
92            // The worker opened but took no brief: nothing will run, and
93            // waiting for it to come back is no use.
94            outcome = FireOutcome::Failed { error: format!("the spawned worker didn't take its brief ({:?})", outcome.miss_reason()) };
95        }
96        if let (Some(runs), Some(run_id)) = (self.runs(), &run_id) {
97            let (runs, run_id, job, o) = (runs.clone(), run_id.clone(), to_deliver.clone(), outcome.clone());
98            let _ = tokio::task::spawn_blocking(move || runs.record_delivery(&run_id, &job, &o, scheduled, delivery_started)).await;
99        }
100        // Run now (manual) is in the ledger only: it neither counts as a
101        // fire nor as a miss.
102        if scheduled {
103            self.record_result(&job.id, &outcome);
104        }
105        self.publish_changed();
106        Fired { run_id, outcome: Some(outcome), waiting: None }
107    }
108
109    /// An action that failed before anything was delivered.
110    fn finish_undelivered(&self, job: &CronJob, run_id: Option<String>, outcome: FireOutcome, scheduled: bool, started_ms: i64) -> Fired {
111        if let (Some(runs), Some(run_id)) = (self.runs(), &run_id) {
112            runs.record_delivery(run_id, job, &outcome, scheduled, started_ms);
113        }
114        if scheduled {
115            self.record_result(&job.id, &outcome);
116        }
117        self.publish_changed();
118        Fired { run_id, outcome: Some(outcome), waiting: None }
119    }
120
121    /// One pass over the waiting runs and the running ones: stop what ran
122    /// past its timeout, then start the waiting runs policy now lets start.
123    /// Returns how many started.
124    pub(crate) async fn run_policy_pass(&self) -> usize {
125        let Some(runs) = self.runs().cloned() else { return 0 };
126        let started = {
127            let runs = runs.clone();
128            tokio::task::spawn_blocking(move || {
129                runs.enforce_timeouts();
130                runs.start_waiting()
131            })
132            .await
133            .unwrap_or_default()
134        };
135        let n = started.len();
136        for (run, job) in started {
137            let scheduled = run.trigger != jobs::TRIGGER_MANUAL && run.trigger != jobs::TRIGGER_RETRY;
138            let fired = self.start_run(&job, Some(run.id.clone()), scheduled, run.scheduled_for_ms).await;
139            if matches!(fired.outcome, Some(FireOutcome::Delivered { .. })) {
140                self.stop_at_max_fires(&job.id);
141            }
142        }
143        n
144    }
145}