Skip to main content

agentmux_srv/drone/executor/
engine.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A run's handle, its event stream and the way to stop it. The scheduler that
5//! runs the graph is `scheduler.rs`.
6
7use std::collections::HashMap;
8use std::sync::Arc;
9
10use serde_json::Value;
11use tokio::sync::mpsc;
12
13use crate::drone::checkpoint::Checkpoint;
14use crate::drone::recorder::Persist;
15use crate::drone::replay::Replay;
16use crate::drone::types::{BlockState, DroneGraph};
17
18pub use crate::backend::drone_run_event::RunEvent;
19pub use crate::backend::drone_cancel::{cancel_run, Cancel};
20
21/// How the scheduler ended a run that did not finish.
22pub(super) enum RunEnd {
23    Failed(String),
24    Cancelled(String),
25}
26
27pub struct RunHandle {
28    pub run_id: String,
29    pub events: mpsc::UnboundedReceiver<RunEvent>,
30    pub final_states: Arc<tokio::sync::Mutex<HashMap<String, BlockState>>>,
31}
32
33/// Run the drone end-to-end. Returns a handle whose `events` channel
34/// surfaces per-block lifecycle, and a `final_states` mutex callers can
35/// snapshot for the run-history record. `trigger` is what started the run
36/// (`{{trigger.*}}`); `Null` when nothing did. `run_cap_usd` ends the run
37/// before its next block once its Agent blocks have spent that much (a job's
38/// per-run cap); `None` is no cap, as for a run started by hand. `persist` says
39/// where to keep the run's checkpoints; `None` keeps none.
40pub async fn run_drone(
41    drone_id: String,
42    graph: DroneGraph,
43    trigger: Value,
44    (run_cap_usd, persist): (Option<f64>, Option<Persist>),
45) -> Result<RunHandle, String> {
46    let run_id = uuid::Uuid::new_v4().to_string();
47    let (tx, rx) = mpsc::unbounded_channel();
48    let final_states: Arc<tokio::sync::Mutex<HashMap<String, BlockState>>> =
49        Arc::new(tokio::sync::Mutex::new(HashMap::new()));
50
51    let cancel = Cancel::default();
52    crate::backend::drone_cancel::register_run(&run_id, &cancel);
53    let states_for_task = final_states.clone();
54    let drone_id_for_evt = drone_id.clone();
55    let run_id_for_task = run_id.clone();
56    let tx_for_task = tx.clone();
57    tokio::spawn(async move {
58        let _ = tx_for_task.send(RunEvent::RunStarted {
59            run_id: run_id_for_task.clone(),
60            drone_id: drone_id_for_evt,
61        });
62        let limits = super::scheduler::Limits { run_cap_usd, cancel, persist, chain: Vec::new(), lookup: crate::drone::host::lookup(), replay: None };
63        let ended = super::scheduler::execute(&run_id_for_task, (&graph, trigger, limits, &drone_id), &tx_for_task, &states_for_task).await;
64        crate::backend::drone_cancel::forget_run(&run_id_for_task);
65        let _ = tx_for_task.send(end_event(run_id_for_task, ended));
66    });
67
68    Ok(RunHandle {
69        run_id,
70        events: rx,
71        final_states,
72    })
73}
74
75/// The event that closes a run's stream, from how it ended.
76fn end_event(run_id: String, ended: Result<Value, RunEnd>) -> RunEvent {
77    match ended {
78        Ok(output) => RunEvent::RunDone { run_id, output },
79        Err(RunEnd::Failed(error)) => RunEvent::RunFailed { run_id, error },
80        Err(RunEnd::Cancelled(reason)) => RunEvent::RunCancelled { run_id, reason },
81    }
82}
83
84/// Take a run up again after AgentMux restarted: from `checkpoint`, its newest,
85/// on `graph`, the graph the checkpoint was written on. The blocks that were done
86/// are not run again, and what they said is what the rest reads. The run goes
87/// on under the same id, keeps writing checkpoints through `persist`, and
88/// ends as any run does. `checkpoint.run_id` names it.
89pub async fn resume_drone(graph: DroneGraph, checkpoint: Checkpoint, persist: Persist, replay: Option<Arc<Replay>>) -> Result<RunHandle, String> {
90    let run_id = checkpoint.run_id.clone();
91    let (tx, rx) = mpsc::unbounded_channel();
92    let final_states: Arc<tokio::sync::Mutex<HashMap<String, BlockState>>> = Arc::new(tokio::sync::Mutex::new(HashMap::new()));
93    let cancel = Cancel::default();
94    crate::backend::drone_cancel::register_run(&run_id, &cancel);
95    let states = final_states.clone();
96    let id = run_id.clone();
97    tokio::spawn(async move {
98        let _ = tx.send(RunEvent::Resumed { run_id: id.clone(), step: checkpoint.step });
99        let limits = super::scheduler::Limits { run_cap_usd: checkpoint.run_cap_usd, cancel, persist: Some(persist), chain: Vec::new(), lookup: crate::drone::host::lookup(), replay };
100        let ended = super::scheduler::resume((&graph, &checkpoint, limits), &tx, &states).await;
101        crate::backend::drone_cancel::forget_run(&id);
102        let _ = tx.send(end_event(id, ended));
103    });
104    Ok(RunHandle { run_id, events: rx, final_states })
105}
106
107/// Start the run that replays an earlier one: `first` is its first checkpoint
108/// (`replay::fork_checkpoint`), on `graph`, the graph the earlier run was on. It is a run of its
109/// own, with its own id and checkpoints; the blocks that were finished at the step it starts from
110/// are not run again, and a block with effects says what it said before instead of doing it again
111/// unless `replay.fork.real`.
112pub async fn replay_drone(graph: DroneGraph, first: Checkpoint, persist: Persist, replay: Arc<Replay>) -> Result<RunHandle, String> {
113    let run_id = first.run_id.clone();
114    let (tx, rx) = mpsc::unbounded_channel();
115    let final_states: Arc<tokio::sync::Mutex<HashMap<String, BlockState>>> = Arc::new(tokio::sync::Mutex::new(HashMap::new()));
116    let cancel = Cancel::default();
117    crate::backend::drone_cancel::register_run(&run_id, &cancel);
118    let states = final_states.clone();
119    let id = run_id.clone();
120    tokio::spawn(async move {
121        let _ = tx.send(RunEvent::RunStarted { run_id: id.clone(), drone_id: first.drone_id.clone() });
122        let limits = super::scheduler::Limits { run_cap_usd: first.run_cap_usd, cancel, persist: Some(persist), chain: Vec::new(), lookup: crate::drone::host::lookup(), replay: Some(replay) };
123        let ended = super::scheduler::replay((&graph, &first, limits), &tx, &states).await;
124        crate::backend::drone_cancel::forget_run(&id);
125        let _ = tx.send(end_event(id, ended));
126    });
127    Ok(RunHandle { run_id, events: rx, final_states })
128}
129
130pub(super) async fn mark_state(
131    states: &Arc<tokio::sync::Mutex<HashMap<String, BlockState>>>,
132    id: &str,
133    state: BlockState,
134) {
135    let mut g = states.lock().await;
136    g.insert(id.to_string(), state);
137}
138
139#[cfg(test)]
140mod tests {
141    use super::super::scheduler::over_run_cap;
142    use super::*;
143    use crate::drone::types::{FlowEdge, FlowNode, NodePosition};
144    use serde_json::json;
145
146    fn n(id: &str, kind: &str) -> FlowNode {
147        FlowNode {
148            id: id.to_string(),
149            position: NodePosition::default(),
150            data: json!({ "kind": kind }),
151            node_type: None,
152        }
153    }
154
155    fn e(id: &str, src: &str, dst: &str) -> FlowEdge {
156        FlowEdge {
157            id: id.to_string(),
158            source: src.to_string(),
159            target: dst.to_string(),
160            source_handle: None,
161            target_handle: None,
162        }
163    }
164
165    // ────────────────────────────────────────────────────────────────
166    // Condition branch pruning (codex P2 on PR #755)
167    // ────────────────────────────────────────────────────────────────
168
169    fn eh(id: &str, src: &str, dst: &str, handle: Option<&str>) -> FlowEdge {
170        FlowEdge {
171            id: id.to_string(),
172            source: src.to_string(),
173            target: dst.to_string(),
174            source_handle: handle.map(|s| s.to_string()),
175            target_handle: None,
176        }
177    }
178
179    #[tokio::test]
180    async fn execute_preserves_started_at_in_block_state() {
181        // Reagent P2: BlockDone used to overwrite started_at with None,
182        // making per-block duration uncomputable from the persisted
183        // run record. Verify the timestamp survives the running -> done
184        // transition.
185        let mut vars_node = n("v1", "variables");
186        // Variables block reads `entries: [{name, value}]`, not `vars`.
187        // Earlier draft used the wrong key — the test still passed
188        // because it only asserts started_at, but the Variables block
189        // was running an empty-entries no-op rather than the intended
190        // path. (reagent P2 on PR #755 round 7.)
191        vars_node.data = json!({
192            "kind": "variables",
193            "entries": [{ "name": "v", "value": 1 }]
194        });
195        let mut resp_node = n("r1", "response");
196        resp_node.data = json!({ "kind": "response", "template": "done" });
197        let g = DroneGraph {
198            nodes: vec![vars_node, resp_node],
199            edges: vec![e("e1", "v1", "r1")],
200        };
201
202        let handle = run_drone("wf1".to_string(), g, Value::Null, (None, None)).await.unwrap();
203        let mut rx = handle.events;
204        while let Some(ev) = rx.recv().await {
205            if matches!(ev, RunEvent::RunDone { .. } | RunEvent::RunFailed { .. }) {
206                break;
207            }
208        }
209
210        let states = handle.final_states.lock().await;
211        let v1 = states.get("v1").expect("v1 state");
212        let r1 = states.get("r1").expect("r1 state");
213        assert_eq!(v1.status, "done");
214        assert!(
215            v1.started_at.is_some() && v1.started_at.unwrap() > 0,
216            "v1 started_at must survive the done transition; got {:?}",
217            v1.started_at
218        );
219        assert!(v1.completed_at.is_some());
220        assert!(v1.completed_at.unwrap() >= v1.started_at.unwrap());
221        assert!(r1.started_at.is_some());
222        assert!(r1.completed_at.is_some());
223    }
224
225    #[test]
226    fn flow_edge_serializes_with_camelcase_handle_fields() {
227        // Wire format must match xyflow + the frontend TS
228        // `DroneFlowEdge` shape (sourceHandle / targetHandle).
229        // Snake-case would silently drop the field on the frontend
230        // roundtrip, leaving the executor's branch-pruning permissive.
231        let edge = FlowEdge {
232            id: "e1".to_string(),
233            source: "a".to_string(),
234            target: "b".to_string(),
235            source_handle: Some("true".to_string()),
236            target_handle: None,
237        };
238        let json = serde_json::to_string(&edge).unwrap();
239        assert!(
240            json.contains("\"sourceHandle\":\"true\""),
241            "expected sourceHandle in JSON; got {json}"
242        );
243        // Roundtrip preserves the handle.
244        let parsed: FlowEdge = serde_json::from_str(&json).unwrap();
245        assert_eq!(parsed.source_handle.as_deref(), Some("true"));
246    }
247
248    /// A cap ends the run before the next block once the Agent blocks before it
249    /// have spent it; a run with no cap, with room, or that spent nothing goes on.
250    #[tokio::test]
251    async fn a_run_is_held_to_its_cap_between_blocks() {
252        assert_eq!(over_run_cap(0.0, None), None);
253        assert_eq!(over_run_cap(3.0, None), None);
254        assert_eq!(over_run_cap(3.0, Some(5.0)), None);
255        assert_eq!(over_run_cap(3.0, Some(3.0)), Some("stopped: the run spent $3.00, its cap of $3.00".to_string()));
256        assert_eq!(over_run_cap(0.0, Some(0.0)), None, "a run that spent nothing has not reached a cap of 0");
257
258        // The cap is passed through: a run with room, or none, finishes.
259        let mut resp = n("r1", "response");
260        resp.data = json!({ "kind": "response", "template": "done" });
261        for cap in [None, Some(5.0), Some(0.0)] {
262            let g = DroneGraph { nodes: vec![resp.clone()], edges: vec![] };
263            let mut handle = run_drone("wf1".to_string(), g, Value::Null, (cap, None)).await.unwrap();
264            let mut out = None;
265            while let Some(ev) = handle.events.recv().await {
266                if let RunEvent::RunDone { output, .. } = ev {
267                    out = Some(output);
268                }
269            }
270            assert_eq!(out, Some(json!("done")), "{cap:?}");
271        }
272    }
273
274    /// `{{trigger.*}}` reads what started the run; with nothing it stays visible.
275    #[tokio::test]
276    async fn a_run_reads_its_trigger() {
277        let mut resp = n("r1", "response");
278        resp.data = json!({ "kind": "response", "template": "{{trigger.repo}}#{{trigger.pr.number}} {{trigger.none}}" });
279        let g = DroneGraph { nodes: vec![resp], edges: vec![] };
280        let input = json!({ "repo": "agentmux", "pr": { "number": 12 } });
281        let mut handle = run_drone("wf1".to_string(), g, input, (None, None)).await.unwrap();
282        let mut out = None;
283        while let Some(ev) = handle.events.recv().await {
284            match ev {
285                RunEvent::RunDone { output, .. } => out = Some(output),
286                RunEvent::RunFailed { error, .. } => panic!("run failed: {error}"),
287                _ => {}
288            }
289        }
290        assert_eq!(out, Some(json!("agentmux#12 {{trigger.none}}")));
291    }
292
293    #[tokio::test]
294    async fn execute_skips_pruned_branch_end_to_end() {
295        // Variables(v=10) → Condition({{var.v}} < 5) → Response("hit_true")
296        //                                            ↘ Response("hit_false")
297        // Result: cond is false, true-branch Response is skipped,
298        // false-branch Response runs and becomes the run output.
299        //
300        // The Variables block reads `entries: [{name, value}]` (not
301        // `vars`), so the data shape mirrors what the canvas emits.
302        // An earlier draft of this test used the wrong key and the
303        // condition passed by coincidence (unresolved `{{var.v}}`
304        // string-compared against `5`); reagent caught it.
305        let mut vars_node = n("v1", "variables");
306        vars_node.data = json!({
307            "kind": "variables",
308            "entries": [{ "name": "v", "value": 10 }]
309        });
310        let mut cond_node = n("c1", "condition");
311        cond_node.data = json!({
312            "kind": "condition",
313            "expr": "{{var.v}} < 5"
314        });
315        let mut t_resp = n("rt", "response");
316        t_resp.data = json!({
317            "kind": "response",
318            "template": "hit_true"
319        });
320        let mut f_resp = n("rf", "response");
321        f_resp.data = json!({
322            "kind": "response",
323            "template": "hit_false"
324        });
325        let g = DroneGraph {
326            nodes: vec![vars_node, cond_node, t_resp, f_resp],
327            edges: vec![
328                e("e1", "v1", "c1"),
329                eh("e2", "c1", "rt", Some("true")),
330                eh("e3", "c1", "rf", Some("false")),
331            ],
332        };
333
334        let handle = run_drone("wf1".to_string(), g, Value::Null, (None, None)).await.unwrap();
335        // Drain events to completion.
336        let mut rx = handle.events;
337        let mut got_done_ids: Vec<String> = Vec::new();
338        let mut final_output: Option<Value> = None;
339        while let Some(ev) = rx.recv().await {
340            match ev {
341                RunEvent::BlockDone { block_id, .. } => got_done_ids.push(block_id),
342                RunEvent::RunDone { output, .. } => {
343                    final_output = Some(output);
344                    break;
345                }
346                RunEvent::RunFailed { error, .. } => panic!("run failed: {error}"),
347                _ => {}
348            }
349        }
350
351        // false-branch ran; true-branch was skipped — no BlockDone for "rt".
352        assert!(got_done_ids.contains(&"rf".to_string()));
353        assert!(
354            !got_done_ids.contains(&"rt".to_string()),
355            "true branch must NOT run when condition is false; got: {got_done_ids:?}"
356        );
357
358        // Final state for the skipped block records "skipped".
359        let states = handle.final_states.lock().await;
360        let rt_state = states.get("rt").expect("rt state recorded");
361        assert_eq!(rt_state.status, "skipped");
362
363        // The run's response output is the false-branch's resolution,
364        // unwrapped from Response's `{ "value": ... }` envelope so
365        // downstream consumers see the bare string (codex P3).
366        assert_eq!(final_output, Some(json!("hit_false")));
367    }
368}