Skip to main content

agentmux_srv/drone/executor/
schedule.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! What the step scheduler needs to know about a graph, and the rules a graph
5//! with a loop must meet (docs/specs/SPEC_DRONE_GENERAL_AUTOMATION_2026_11_11.md
6//! §3.1). Pure: nothing here runs a block.
7//!
8//! A graph may hold a cycle, but **every cycle must pass through a Condition**,
9//! which is the loop's guard. A guard has `max_iterations` (1 to 1,000, 25 when
10//! absent), `on_cap` (`end_run`, the default, or `exit_loop`), and optionally
11//! `max_cost_usd` and `max_minutes`. Each time a guard sends the run along an
12//! edge that stays inside its cycle that is one more iteration; the scheduler
13//! stops the loop at any cap.
14
15use std::collections::{BTreeMap, BTreeSet, HashMap};
16
17use serde_json::Value;
18
19use crate::drone::types::{DroneGraph, FlowEdge, FlowNode};
20
21pub const DEFAULT_MAX_ITERATIONS: u32 = 25;
22pub const MAX_ITERATIONS_CEILING: u32 = 1_000;
23pub const DEFAULT_MAX_ITEMS: usize = 100;
24pub const MAX_ITEMS_CEILING: usize = 1_000;
25
26/// What happens when a loop reaches its `max_iterations`.
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub enum OnCap {
29    /// The run fails, and says why (the default).
30    EndRun,
31    /// The run leaves the loop by the guard's other edges, with
32    /// `{{<guard>.capped}}` set.
33    ExitLoop,
34}
35
36/// A Condition that sits on a cycle.
37#[derive(Debug, Clone, PartialEq)]
38pub struct Guard {
39    pub max_iterations: u32,
40    pub on_cap: OnCap,
41    /// What the loop's blocks may spend in all, in dollars; none is no limit.
42    pub max_cost_usd: Option<f64>,
43    /// How long the loop may run, in minutes; none is no limit.
44    pub max_minutes: Option<f64>,
45    /// The ids of the edges out of the guard that stay inside its cycle.
46    pub loop_edges: BTreeSet<String>,
47}
48
49/// What the scheduler reads of a graph that passed [`analyze`].
50#[derive(Debug, Clone, Default, PartialEq)]
51pub struct Plan {
52    /// The edges that close a cycle. The scheduler does not wait on them for
53    /// their target to be ready, so the others form an acyclic graph.
54    pub back_edges: BTreeSet<String>,
55    /// Each Condition on a cycle, by node id.
56    pub guards: BTreeMap<String, Guard>,
57    /// For each node on a cycle, every node of its cycle: the ones that run
58    /// again when a loop goes round.
59    pub cycle_of: BTreeMap<String, BTreeSet<String>>,
60    /// The blocks a for-each runs as its body. They are not scheduled on their own.
61    pub owned: BTreeSet<String>,
62}
63
64/// What a for-each does when one item's body fails.
65#[derive(Debug, Clone, Copy, PartialEq, Eq)]
66pub enum OnItemError {
67    /// The run fails (the default).
68    Stop,
69    /// The item is recorded in `errors` and the next one runs.
70    Continue,
71}
72
73/// A for-each block's settings (§3.1). The body is one block of the graph,
74/// named by id, that has no edges of its own and runs once per item.
75#[derive(Debug, Clone, PartialEq)]
76pub struct ForEachConfig {
77    /// A template for the list, such as `{{api.body.items}}`.
78    pub items: String,
79    pub body: String,
80    pub max_items: usize,
81    pub on_item_error: OnItemError,
82    pub on_cap: OnCap,
83    pub max_cost_usd: Option<f64>,
84    pub max_minutes: Option<f64>,
85}
86
87fn positive(node: &FlowNode, key: &str) -> Result<Option<f64>, String> {
88    match node.data.get(key) {
89        None | Some(Value::Null) => Ok(None),
90        Some(v) => v.as_f64().filter(|n| *n > 0.0).map(Some).ok_or_else(|| format!("{key} must be a number above 0")),
91    }
92}
93
94/// Read and check a for-each block's settings.
95pub fn foreach_config(node: &FlowNode) -> Result<ForEachConfig, String> {
96    let text = |key: &str| node.data.get(key).and_then(Value::as_str).map(str::trim).filter(|t| !t.is_empty());
97    let items = text("items").ok_or("a for-each needs `items`: the list to go through, such as {{api.body.items}}")?;
98    let body = text("body").ok_or("a for-each needs `body`: the id of the block to run for each item")?;
99    let max_items = match node.data.get("max_items") {
100        None | Some(Value::Null) => DEFAULT_MAX_ITEMS,
101        Some(v) => v
102            .as_u64()
103            .filter(|n| (1..=MAX_ITEMS_CEILING as u64).contains(n))
104            .ok_or_else(|| format!("max_items must be a whole number from 1 to {MAX_ITEMS_CEILING}"))? as usize,
105    };
106    let on_item_error = match node.data.get("on_item_error").and_then(Value::as_str) {
107        None | Some("stop") => OnItemError::Stop,
108        Some("continue") => OnItemError::Continue,
109        Some(_) => return Err("on_item_error must be stop or continue".to_string()),
110    };
111    let on_cap = match node.data.get("on_cap").and_then(Value::as_str) {
112        None | Some("end_run") => OnCap::EndRun,
113        Some("exit_loop") => OnCap::ExitLoop,
114        Some(_) => return Err("on_cap must be end_run or exit_loop".to_string()),
115    };
116    Ok(ForEachConfig {
117        items: items.to_string(),
118        body: body.to_string(),
119        max_items,
120        on_item_error,
121        on_cap,
122        max_cost_usd: positive(node, "max_cost_usd")?,
123        max_minutes: positive(node, "max_minutes")?,
124    })
125}
126
127/// A reason a graph cannot run, for the author: which block, and what to do.
128#[derive(Debug, Clone, PartialEq, Eq)]
129pub struct Issue {
130    pub node: Option<String>,
131    pub message: String,
132}
133
134impl Issue {
135    fn at(node: &str, message: impl Into<String>) -> Self {
136        Self { node: Some(node.to_string()), message: message.into() }
137    }
138}
139
140fn kind_of(node: &FlowNode) -> &str {
141    node.data.get("kind").and_then(Value::as_str).unwrap_or("")
142}
143
144/// Every pair `(u, v)` with a path of one edge or more from `u` to `v`,
145/// following only edges between nodes `keep` allows.
146fn closure(out: &[Vec<usize>], keep: &[bool]) -> Vec<Vec<bool>> {
147    let n = out.len();
148    let mut reach = vec![vec![false; n]; n];
149    for start in (0..n).filter(|&u| keep[u]) {
150        let mut stack: Vec<usize> = out[start].iter().copied().filter(|&v| keep[v]).collect();
151        while let Some(v) = stack.pop() {
152            if reach[start][v] {
153                continue;
154            }
155            reach[start][v] = true;
156            stack.extend(out[v].iter().copied().filter(|&w| keep[w] && !reach[start][w]));
157        }
158    }
159    reach
160}
161
162/// `u` and everything on a cycle with it.
163fn cycle_group(reach: &[Vec<bool>], u: usize) -> BTreeSet<usize> {
164    (0..reach.len()).filter(|&v| v == u || (reach[u][v] && reach[v][u])).collect()
165}
166
167fn names(ids: &[&str], group: &BTreeSet<usize>) -> Vec<String> {
168    group.iter().map(|&i| ids[i].to_string()).collect()
169}
170
171/// Read a guard's settings. Errors are issues, so a bad value is named, not guessed.
172fn read_guard(node: &FlowNode, loop_edges: BTreeSet<String>, issues: &mut Vec<Issue>) -> Guard {
173    let mut max_iterations = DEFAULT_MAX_ITERATIONS;
174    match node.data.get("max_iterations") {
175        None | Some(Value::Null) => {}
176        Some(v) => match v.as_u64().filter(|n| (1..=MAX_ITERATIONS_CEILING as u64).contains(n)) {
177            Some(n) => max_iterations = n as u32,
178            None => issues.push(Issue::at(
179                &node.id,
180                format!("max_iterations must be a whole number from 1 to {MAX_ITERATIONS_CEILING}"),
181            )),
182        },
183    }
184    let on_cap = match node.data.get("on_cap").and_then(Value::as_str) {
185        None | Some("end_run") => OnCap::EndRun,
186        Some("exit_loop") => OnCap::ExitLoop,
187        Some(_) => {
188            issues.push(Issue::at(&node.id, "on_cap must be end_run or exit_loop"));
189            OnCap::EndRun
190        }
191    };
192    let mut limit = |key: &str| match node.data.get(key) {
193        None | Some(Value::Null) => None,
194        Some(v) => match v.as_f64().filter(|n| *n > 0.0) {
195            Some(n) => Some(n),
196            None => {
197                issues.push(Issue::at(&node.id, format!("{key} must be a number above 0")));
198                None
199            }
200        },
201    };
202    let max_cost_usd = limit("max_cost_usd");
203    let max_minutes = limit("max_minutes");
204    Guard { max_iterations, on_cap, max_cost_usd, max_minutes, loop_edges }
205}
206
207/// The edges that close a cycle, found by a walk from the blocks nothing leads
208/// to, and the blocks that walk never reached.
209fn walk_back_edges(ids: &[&str], edges: &[(usize, usize, &FlowEdge)]) -> (BTreeSet<String>, Vec<usize>) {
210    let n = ids.len();
211    let mut next: Vec<Vec<(usize, &FlowEdge)>> = vec![Vec::new(); n];
212    let mut has_incoming = vec![false; n];
213    for &(s, t, e) in edges {
214        next[s].push((t, e));
215        has_incoming[t] = true;
216    }
217    for list in &mut next {
218        list.sort_by(|a, b| (ids[a.0], &a.1.id).cmp(&(ids[b.0], &b.1.id)));
219    }
220    // 0 not seen, 1 on the walk's path, 2 finished.
221    let mut colour = vec![0u8; n];
222    let mut back = BTreeSet::new();
223    for root in (0..n).filter(|&i| !has_incoming[i]) {
224        colour[root] = 1;
225        let mut path: Vec<(usize, usize)> = vec![(root, 0)];
226        while let Some(top) = path.len().checked_sub(1) {
227            let (u, at) = path[top];
228            let Some(&(v, edge)) = next[u].get(at) else {
229                colour[u] = 2;
230                path.pop();
231                continue;
232            };
233            path[top].1 += 1;
234            match colour[v] {
235                1 => {
236                    back.insert(edge.id.clone());
237                }
238                0 => {
239                    colour[v] = 1;
240                    path.push((v, 0));
241                }
242                _ => {}
243            }
244        }
245    }
246    let unreached = (0..n).filter(|&i| colour[i] == 0).collect();
247    (back, unreached)
248}
249
250/// Check each for-each: its settings, and that its body is a block of the graph
251/// that is not wired into it, is not a for-each, and is not another one's body.
252fn check_foreach(sorted: &[&FlowNode], edges: &[(usize, usize, &FlowEdge)], plan: &mut Plan, issues: &mut Vec<Issue>) {
253    for node in sorted.iter().filter(|n| kind_of(n) == "foreach") {
254        let cfg = match foreach_config(node) {
255            Ok(cfg) => cfg,
256            Err(message) => {
257                issues.push(Issue::at(&node.id, message));
258                continue;
259            }
260        };
261        let Some(body) = sorted.iter().find(|n| n.id == cfg.body) else {
262            issues.push(Issue::at(&node.id, format!("the body {:?} is not a block of this drone", cfg.body)));
263            continue;
264        };
265        let wired = edges.iter().any(|(s, t, _)| sorted[*s].id == body.id || sorted[*t].id == body.id);
266        if body.id == node.id {
267            issues.push(Issue::at(&node.id, "a for-each cannot be its own body"));
268        } else if kind_of(body) == "foreach" {
269            issues.push(Issue::at(&node.id, format!("the body {:?} is itself a for-each: nest loops with a sub-drone", body.id)));
270        } else if kind_of(body) == "wait" {
271            issues.push(Issue::at(&node.id, format!("the body {:?} is a Wait block: a wait is kept in the run as a whole, so put it before or after the for-each", body.id)));
272        } else if kind_of(body) == "approval" {
273            issues.push(Issue::at(&node.id, format!("the body {:?} is an Approval block: it waits as a Wait does, kept in the run as a whole, so put it before or after the for-each", body.id)));
274        } else if wired {
275            issues.push(Issue::at(&body.id, format!("{:?} is the body of the for-each {:?} and runs once per item: take its edges off", body.id, node.id)));
276        } else if !plan.owned.insert(body.id.clone()) {
277            issues.push(Issue::at(&node.id, format!("the body {:?} is already the body of another for-each", body.id)));
278        }
279    }
280}
281
282/// The longest a block may be given to run: a day.
283const MAX_TIMEOUT_SECONDS: u64 = 86_400;
284
285/// A block's own `timeout_seconds`, when it has one: a whole number from 1 to a day.
286pub(super) fn timeout_seconds(node: &FlowNode) -> Result<Option<u64>, String> {
287    match node.data.get("timeout_seconds") {
288        None | Some(Value::Null) => Ok(None),
289        Some(v) => v
290            .as_u64()
291            .filter(|s| (1..=MAX_TIMEOUT_SECONDS).contains(s))
292            .map(Some)
293            .ok_or_else(|| format!("{}: timeout_seconds must be a whole number from 1 to {MAX_TIMEOUT_SECONDS}", node.id)),
294    }
295}
296
297/// Each block's own `timeout_seconds` and `retry` are well formed.
298fn check_block_limits(sorted: &[&FlowNode], issues: &mut Vec<Issue>) {
299    for node in sorted {
300        let wait = (kind_of(node) == "wait").then(|| super::blocks::wait::check(node).err()).flatten();
301        let call = (kind_of(node) == "drone").then(|| super::blocks::call::parse(node).err()).flatten();
302        let run = (kind_of(node) == "run").then(|| super::blocks::run::check(node).err()).flatten();
303        let bad = timeout_seconds(node).err().into_iter().chain(super::retry::retry_of(node).err()).chain(wait).chain(call).chain(run);
304        issues.extend(bad.map(|message| Issue { node: Some(node.id.clone()), message }));
305    }
306}
307
308/// Each Join is set rightly and has branches to bring together.
309fn check_joins(sorted: &[&FlowNode], edges: &[(usize, usize, &FlowEdge)], issues: &mut Vec<Issue>) {
310    for (index, node) in sorted.iter().enumerate().filter(|(_, n)| kind_of(n) == "join") {
311        let branches = edges.iter().filter(|(_, t, _)| *t == index).count();
312        if let Err(message) = super::blocks::join::check(node, branches) {
313            issues.push(Issue::at(&node.id, message));
314        }
315    }
316}
317
318/// Check the graph's loops and say how the scheduler should run it. A graph
319/// with no cycle gets an empty plan.
320pub fn analyze(graph: &DroneGraph) -> Result<Plan, Vec<Issue>> {
321    let mut sorted: Vec<&FlowNode> = graph.nodes.iter().collect();
322    sorted.sort_by(|a, b| a.id.cmp(&b.id));
323    let ids: Vec<&str> = sorted.iter().map(|n| n.id.as_str()).collect();
324    let index: HashMap<&str, usize> = ids.iter().enumerate().map(|(i, id)| (*id, i)).collect();
325
326    let mut issues = Vec::new();
327    let mut edges: Vec<(usize, usize, &FlowEdge)> = Vec::new();
328    for e in &graph.edges {
329        match (index.get(e.source.as_str()), index.get(e.target.as_str())) {
330            (Some(&s), Some(&t)) => edges.push((s, t, e)),
331            _ => issues.push(Issue { node: None, message: format!("edge references unknown node ({} → {})", e.source, e.target) }),
332        }
333    }
334    if !issues.is_empty() {
335        return Err(issues);
336    }
337
338    let n = ids.len();
339    let mut out: Vec<Vec<usize>> = vec![Vec::new(); n];
340    for &(s, t, _) in &edges {
341        out[s].push(t);
342    }
343    let all = closure(&out, &vec![true; n]);
344    let is_condition: Vec<bool> = sorted.iter().map(|node| kind_of(node) == "condition").collect();
345
346    // A cycle through no Condition has nothing to stop it.
347    let no_guard = closure(&out, &is_condition.iter().map(|c| !c).collect::<Vec<_>>());
348    let mut reported = BTreeSet::new();
349    for u in (0..n).filter(|&u| no_guard[u][u]) {
350        let group = cycle_group(&no_guard, u);
351        if reported.insert(group.clone()) {
352            issues.push(Issue {
353                node: Some(ids[u].to_string()),
354                message: format!(
355                    "these blocks loop with no Condition among them: {}. Put a Condition in the loop; its max_iterations (25 when not set) is what stops it",
356                    names(&ids, &group).join(", ")
357                ),
358            });
359        }
360    }
361
362    let mut plan = Plan::default();
363    for u in (0..n).filter(|&u| all[u][u]) {
364        let group = cycle_group(&all, u);
365        plan.cycle_of.insert(ids[u].to_string(), group.iter().map(|&i| ids[i].to_string()).collect());
366        if is_condition[u] {
367            let loop_edges = edges.iter().filter(|(s, t, _)| *s == u && group.contains(t)).map(|(_, _, e)| e.id.clone()).collect();
368            plan.guards.insert(ids[u].to_string(), read_guard(sorted[u], loop_edges, &mut issues));
369        }
370    }
371
372    check_foreach(&sorted, &edges, &mut plan, &mut issues);
373    check_block_limits(&sorted, &mut issues);
374    check_joins(&sorted, &edges, &mut issues);
375    super::writers::check(&sorted, &edges, &all, &plan, &mut issues);
376
377    let (back_edges, unreached) = walk_back_edges(&ids, &edges);
378    plan.back_edges = back_edges;
379    if !unreached.is_empty() {
380        let list: Vec<&str> = unreached.iter().map(|&i| ids[i]).collect();
381        issues.push(Issue {
382            node: Some(list[0].to_string()),
383            message: format!("{} can only be reached from each other: add a block that leads into the loop", list.join(", ")),
384        });
385    }
386    if issues.is_empty() {
387        Ok(plan)
388    } else {
389        Err(issues)
390    }
391}
392
393#[cfg(test)]
394mod tests {
395    use super::*;
396    use crate::drone::types::NodePosition;
397    use serde_json::json;
398
399    fn node(id: &str, kind: &str, extra: Value) -> FlowNode {
400        let mut data = json!({ "kind": kind });
401        if let (Some(d), Some(x)) = (data.as_object_mut(), extra.as_object()) {
402            d.extend(x.clone());
403        }
404        FlowNode { id: id.to_string(), position: NodePosition::default(), data, node_type: None }
405    }
406
407    fn edge(id: &str, source: &str, target: &str, handle: Option<&str>) -> FlowEdge {
408        FlowEdge {
409            id: id.to_string(),
410            source: source.to_string(),
411            target: target.to_string(),
412            source_handle: handle.map(str::to_string),
413            target_handle: None,
414        }
415    }
416
417    /// start → check → guard; guard "true" → done; guard "false" → fix → check.
418    fn retry_loop(guard: Value) -> DroneGraph {
419        DroneGraph {
420            nodes: vec![
421                node("start", "variables", json!({})),
422                node("check", "agent", json!({})),
423                node("guard", "condition", guard),
424                node("fix", "agent", json!({})),
425                node("done", "response", json!({})),
426            ],
427            edges: vec![
428                edge("e0", "start", "check", None),
429                edge("e1", "check", "guard", None),
430                edge("e2", "guard", "done", Some("true")),
431                edge("e3", "guard", "fix", Some("false")),
432                edge("e4", "fix", "check", None),
433            ],
434        }
435    }
436
437    #[test]
438    fn a_graph_with_no_cycle_has_an_empty_plan() {
439        let g = DroneGraph {
440            nodes: vec![node("a", "variables", json!({})), node("b", "api", json!({})), node("c", "condition", json!({}))],
441            edges: vec![edge("e1", "a", "b", None), edge("e2", "b", "c", None)],
442        };
443        assert_eq!(analyze(&g), Ok(Plan::default()));
444    }
445
446    #[test]
447    fn a_cycle_through_a_condition_is_a_guarded_loop() {
448        let plan = analyze(&retry_loop(json!({ "expr": "{{check.response}} == OK" }))).unwrap();
449        assert_eq!(plan.back_edges, BTreeSet::from(["e4".to_string()]));
450        let guard = &plan.guards["guard"];
451        assert_eq!((guard.max_iterations, guard.on_cap), (25, OnCap::EndRun), "the defaults");
452        assert_eq!(guard.loop_edges, BTreeSet::from(["e3".to_string()]), "only the edge that stays in the loop counts");
453        let cycle: BTreeSet<String> = ["check", "fix", "guard"].iter().map(|s| s.to_string()).collect();
454        assert_eq!(plan.cycle_of["fix"], cycle);
455        assert!(!plan.cycle_of.contains_key("done"), "a block outside the loop is not in it");
456    }
457
458    #[test]
459    fn the_guard_reads_its_own_limit_and_what_to_do_at_it() {
460        let plan = analyze(&retry_loop(json!({ "max_iterations": 3, "on_cap": "exit_loop" }))).unwrap();
461        assert_eq!((plan.guards["guard"].max_iterations, plan.guards["guard"].on_cap), (3, OnCap::ExitLoop));
462    }
463
464    #[test]
465    fn a_loop_may_also_limit_its_cost_and_its_time() {
466        let g = analyze(&retry_loop(json!({ "max_cost_usd": 0.5, "max_minutes": 10 }))).unwrap().guards["guard"].clone();
467        assert_eq!((g.max_cost_usd, g.max_minutes), (Some(0.5), Some(10.0)));
468        let none = analyze(&retry_loop(json!({}))).unwrap().guards["guard"].clone();
469        assert_eq!((none.max_cost_usd, none.max_minutes), (None, None));
470        for bad in [json!(0), json!(-1), json!("lots")] {
471            let issues = analyze(&retry_loop(json!({ "max_cost_usd": bad }))).unwrap_err();
472            assert!(issues[0].message.contains("max_cost_usd"), "{issues:?}");
473        }
474    }
475
476    #[test]
477    fn a_limit_outside_one_to_a_thousand_is_refused_and_named() {
478        for bad in [json!(0), json!(1001), json!("many"), json!(2.5), json!(-1)] {
479            let issues = analyze(&retry_loop(json!({ "max_iterations": bad }))).unwrap_err();
480            assert!(issues.iter().any(|i| i.node.as_deref() == Some("guard") && i.message.contains("max_iterations")), "{bad}: {issues:?}");
481        }
482        assert!(analyze(&retry_loop(json!({ "max_iterations": 1000 }))).is_ok(), "the ceiling itself is allowed");
483        let issues = analyze(&retry_loop(json!({ "on_cap": "forever" }))).unwrap_err();
484        assert!(issues[0].message.contains("on_cap"), "{issues:?}");
485    }
486
487    #[test]
488    fn a_cycle_with_no_condition_is_refused_and_says_which_blocks() {
489        let g = DroneGraph {
490            nodes: vec![node("start", "variables", json!({})), node("a", "api", json!({})), node("b", "agent", json!({}))],
491            edges: vec![edge("e1", "start", "a", None), edge("e2", "a", "b", None), edge("e3", "b", "a", None)],
492        };
493        let issues = analyze(&g).unwrap_err();
494        assert_eq!(issues.len(), 1, "one cycle, one issue: {issues:?}");
495        assert!(issues[0].message.contains("a, b") && issues[0].message.contains("Condition"), "{issues:?}");
496    }
497
498    #[test]
499    fn a_second_cycle_that_skips_the_guard_is_still_refused() {
500        // The guarded loop check → guard → fix → check, plus fix ⇄ helper with no Condition.
501        let mut g = retry_loop(json!({}));
502        g.nodes.push(node("helper", "api", json!({})));
503        g.edges.push(edge("e5", "fix", "helper", None));
504        g.edges.push(edge("e6", "helper", "fix", None));
505        let issues = analyze(&g).unwrap_err();
506        assert!(issues.iter().any(|i| i.message.contains("fix, helper")), "{issues:?}");
507    }
508
509    #[test]
510    fn a_block_that_leads_to_itself_needs_to_be_a_condition() {
511        let own = |kind: &str| DroneGraph {
512            nodes: vec![node("start", "variables", json!({})), node("x", kind, json!({}))],
513            edges: vec![edge("e1", "start", "x", None), edge("e2", "x", "x", Some("false"))],
514        };
515        assert!(analyze(&own("api")).is_err());
516        let plan = analyze(&own("condition")).unwrap();
517        assert_eq!(plan.back_edges, BTreeSet::from(["e2".to_string()]));
518        assert_eq!(plan.guards["x"].loop_edges, BTreeSet::from(["e2".to_string()]));
519    }
520
521    #[test]
522    fn a_loop_nothing_leads_into_is_refused() {
523        let g = DroneGraph {
524            nodes: vec![node("a", "condition", json!({})), node("b", "api", json!({}))],
525            edges: vec![edge("e1", "a", "b", Some("true")), edge("e2", "b", "a", None)],
526        };
527        let issues = analyze(&g).unwrap_err();
528        assert!(issues[0].message.contains("a, b") && issues[0].message.contains("leads into"), "{issues:?}");
529    }
530
531    #[test]
532    fn an_edge_to_a_block_that_is_not_there_is_refused() {
533        let g = DroneGraph { nodes: vec![node("a", "api", json!({}))], edges: vec![edge("e1", "a", "ghost", None)] };
534        assert!(analyze(&g).unwrap_err()[0].message.contains("unknown node"));
535    }
536
537    fn foreach_graph(extra: Value, body_edges: bool) -> DroneGraph {
538        let mut data = json!({ "items": "{{trigger.list}}", "body": "work" });
539        data.as_object_mut().unwrap().extend(extra.as_object().cloned().unwrap_or_default());
540        let mut g = DroneGraph {
541            nodes: vec![node("start", "variables", json!({})), node("each", "foreach", data), node("work", "agent", json!({}))],
542            edges: vec![edge("e1", "start", "each", None)],
543        };
544        if body_edges {
545            g.edges.push(edge("e2", "start", "work", None));
546        }
547        g
548    }
549
550    #[test]
551    fn a_for_each_owns_its_body_and_reads_its_limits() {
552        let plan = analyze(&foreach_graph(json!({}), false)).unwrap();
553        assert_eq!(plan.owned, BTreeSet::from(["work".to_string()]));
554        let g = foreach_graph(json!({ "max_items": 7, "on_item_error": "continue", "on_cap": "exit_loop", "max_cost_usd": 2 }), false);
555        let cfg = foreach_config(&g.nodes[1]).unwrap();
556        assert_eq!((cfg.max_items, cfg.on_item_error, cfg.on_cap, cfg.max_cost_usd), (7, OnItemError::Continue, OnCap::ExitLoop, Some(2.0)));
557        let plain = foreach_config(&foreach_graph(json!({}), false).nodes[1]).unwrap();
558        assert_eq!((plain.max_items, plain.on_item_error, plain.on_cap), (100, OnItemError::Stop, OnCap::EndRun), "the defaults");
559    }
560
561    #[test]
562    fn a_for_each_that_cannot_run_is_refused_and_says_what_to_fix() {
563        for (extra, wants) in [
564            (json!({ "max_items": 0 }), "max_items"),
565            (json!({ "max_items": 1001 }), "max_items"),
566            (json!({ "on_item_error": "never" }), "on_item_error"),
567            (json!({ "body": "ghost" }), "not a block of this drone"),
568            (json!({ "body": "each" }), "its own body"),
569            (json!({ "items": "" }), "needs `items`"),
570        ] {
571            let issues = analyze(&foreach_graph(extra.clone(), false)).unwrap_err();
572            assert!(issues.iter().any(|i| i.message.contains(wants)), "{extra}: {issues:?}");
573        }
574        let issues = analyze(&foreach_graph(json!({}), true)).unwrap_err();
575        assert!(issues[0].message.contains("take its edges off"), "{issues:?}");
576    }
577
578    #[test]
579    fn a_for_each_body_is_not_a_for_each_and_is_not_shared() {
580        let mut g = foreach_graph(json!({}), false);
581        g.nodes.push(node("again", "foreach", json!({ "items": "{{trigger.y}}", "body": "work" })));
582        g.edges.push(edge("e4", "start", "again", None));
583        let issues = analyze(&g).unwrap_err();
584        assert!(issues.iter().any(|i| i.message.contains("already the body of another")), "{issues:?}");
585        let mut nested = foreach_graph(json!({ "body": "inner" }), false);
586        nested.nodes.push(node("inner", "foreach", json!({ "items": "{{trigger.x}}", "body": "work" })));
587        assert!(analyze(&nested).unwrap_err().iter().any(|i| i.message.contains("sub-drone")));
588    }
589
590    #[test]
591    fn a_wait_cannot_be_a_for_each_body() {
592        let mut g = foreach_graph(json!({}), false);
593        g.nodes.retain(|n| n.id != "work");
594        g.nodes.push(node("work", "wait", json!({ "for": "1m" })));
595        let issues = analyze(&g).unwrap_err();
596        assert!(issues.iter().any(|i| i.message.contains("is a Wait block")), "{issues:?}");
597    }
598
599    #[test]
600    fn an_approval_cannot_be_a_for_each_body() {
601        let mut g = foreach_graph(json!({}), false);
602        g.nodes.retain(|n| n.id != "work");
603        g.nodes.push(node("work", "approval", json!({ "title": "ok?" })));
604        let issues = analyze(&g).unwrap_err();
605        assert!(issues.iter().any(|i| i.message.contains("is an Approval block")), "{issues:?}");
606    }
607}