1use serde_json::{json, Value};
20
21use crate::drone::data_flow::ExecutionScope;
22use crate::drone::transform::evaluate_condition;
23use crate::drone::types::FlowNode;
24
25pub async fn run(node: &FlowNode, scope: &ExecutionScope) -> Result<Value, String> {
26 let expr = node
27 .data
28 .get("expr")
29 .and_then(|v| v.as_str())
30 .ok_or_else(|| "Condition block missing `expr`".to_string())?;
31 let raw = expr.trim();
35 let scanned = scan(raw)?;
36 if scanned.rich {
37 let mut bound = serde_json::Map::new();
38 for (name, path) in &scanned.refs {
39 bound.insert(name.clone(), scope.lookup_ref(path).unwrap_or(Value::Null));
40 }
41 let result = evaluate_condition(&scanned.rewritten, &bound).map_err(|e| format!("condition: {e}"))?;
42 return Ok(json!({ "result": result }));
43 }
44 let result = match split_binop(raw) {
45 Some((lhs, op, rhs)) => compare(&scope.resolve(lhs), op, &scope.resolve(rhs)),
46 None => bare_boolean(&scope.resolve(raw))?,
47 };
48 Ok(json!({ "result": result }))
49}
50
51struct Scanned {
54 rich: bool,
55 rewritten: String,
56 refs: Vec<(String, String)>,
57}
58
59const WORD_OPERATORS: [&str; 4] = ["contains", "matches", "in_set", "exists"];
61
62fn scan(raw: &str) -> Result<Scanned, String> {
63 let chars: Vec<char> = raw.chars().collect();
64 let mut out = Scanned { rich: false, rewritten: String::new(), refs: Vec::new() };
65 let (mut i, mut quote, mut quoted_ref) = (0, None::<char>, false);
66 let mut prev = None::<char>; while i < chars.len() {
68 let c = chars[i];
69 if let Some(q) = quote {
70 if c == '\\' && i + 1 < chars.len() {
71 out.rewritten.push(c);
72 out.rewritten.push(chars[i + 1]);
73 i += 2;
74 continue;
75 }
76 quoted_ref |= c == '{' && chars.get(i + 1) == Some(&'{');
77 if c == q {
78 quote = None;
79 }
80 out.rewritten.push(c);
81 i += 1;
82 continue;
83 }
84 if c == '{' && chars.get(i + 1) == Some(&'{') {
85 let close = (i + 2..chars.len().saturating_sub(1)).find(|&k| chars[k] == '}' && chars[k + 1] == '}');
86 let close = close.ok_or_else(|| "a `{{` in the condition has no `}}`".to_string())?;
87 let path: String = chars[i + 2..close].iter().collect();
88 let name = format!("r{}", out.refs.len());
89 out.rewritten.push_str(&format!("item.{name}"));
90 out.refs.push((name, path.trim().to_string()));
91 prev = Some('}');
92 i = close + 2;
93 continue;
94 }
95 match c {
96 '\'' | '"' => quote = Some(c),
97 '(' | ')' | '[' | ']' => out.rich = true,
98 '&' | '|' if chars.get(i + 1) == Some(&c) => out.rich = true,
99 '!' if chars.get(i + 1) != Some(&'=') && matches!(prev, None | Some('(' | '&' | '|' | '!')) => out.rich = true,
100 c if c.is_alphabetic() || c == '_' => {
101 let end = (i..chars.len()).find(|&k| !(chars[k].is_alphanumeric() || chars[k] == '_')).unwrap_or(chars.len());
102 let word: String = chars[i..end].iter().collect();
103 out.rich |= WORD_OPERATORS.contains(&word.as_str());
104 out.rewritten.push_str(&word);
105 prev = Some('a');
106 i = end;
107 continue;
108 }
109 _ => {}
110 }
111 out.rewritten.push(c);
112 if !c.is_whitespace() {
113 prev = Some(c);
114 }
115 i += 1;
116 }
117 if out.rich && quoted_ref {
118 return Err("a {{reference}} cannot sit inside quotes in a condition with && || ! ( ) [ ] or contains, matches, in_set, exists: put it outside the quotes".to_string());
119 }
120 Ok(out)
121}
122
123fn bare_boolean(text: &str) -> Result<bool, String> {
124 let trimmed = text.trim();
125 if trimmed.eq_ignore_ascii_case("true") {
126 Ok(true)
127 } else if trimmed.eq_ignore_ascii_case("false") {
128 Ok(false)
129 } else {
130 Err(format!("could not parse condition: `{trimmed}`"))
131 }
132}
133
134fn compare(lhs: &str, op: &str, rhs: &str) -> bool {
135 let lhs = lhs.trim().trim_matches(|c| c == '\'' || c == '"');
136 let rhs = rhs.trim().trim_matches(|c| c == '\'' || c == '"');
137 if let (Ok(a), Ok(b)) = (lhs.parse::<f64>(), rhs.parse::<f64>()) {
138 return match op {
139 "==" => (a - b).abs() < f64::EPSILON,
140 "!=" => (a - b).abs() >= f64::EPSILON,
141 "<" => a < b,
142 "<=" => a <= b,
143 ">" => a > b,
144 _ => a >= b,
145 };
146 }
147 match op {
148 "==" => lhs == rhs,
149 "!=" => lhs != rhs,
150 "<" => lhs < rhs,
151 "<=" => lhs <= rhs,
152 ">" => lhs > rhs,
153 _ => lhs >= rhs,
154 }
155}
156
157fn split_binop(s: &str) -> Option<(&str, &str, &str)> {
160 for op in &["==", "!=", "<=", ">=", "<", ">"] {
161 if let Some(idx) = s.find(op) {
162 return Some((&s[..idx], op, &s[idx + op.len()..]));
165 }
166 }
167 None
168}
169
170#[cfg(test)]
171mod tests {
172 use super::*;
173 use crate::drone::types::NodePosition;
174
175 fn mk(expr: &str) -> FlowNode {
176 FlowNode {
177 id: "c".to_string(),
178 position: NodePosition::default(),
179 data: json!({ "kind": "condition", "expr": expr }),
180 node_type: None,
181 }
182 }
183
184 #[tokio::test]
185 async fn numeric_lt() {
186 let n = mk("3 < 5");
187 let out = run(&n, &ExecutionScope::new()).await.unwrap();
188 assert_eq!(out, json!({ "result": true }));
189 }
190
191 #[tokio::test]
192 async fn string_eq() {
193 let n = mk("'a' == 'a'");
194 let out = run(&n, &ExecutionScope::new()).await.unwrap();
195 assert_eq!(out, json!({ "result": true }));
196 }
197
198 #[tokio::test]
199 async fn rejects_unparseable() {
200 let n = mk("foo bar baz");
201 let r = run(&n, &ExecutionScope::new()).await;
202 assert!(r.is_err());
203 }
204
205 #[tokio::test]
206 async fn bare_true() {
207 let n = mk("true");
208 let out = run(&n, &ExecutionScope::new()).await.unwrap();
209 assert_eq!(out, json!({ "result": true }));
210 }
211
212 #[tokio::test]
213 async fn resolves_var_in_expr() {
214 let n = mk("{{var.count}} >= 10");
215 let mut scope = ExecutionScope::new();
216 scope.vars.insert("count".to_string(), json!(15));
217 let out = run(&n, &scope).await.unwrap();
218 assert_eq!(out, json!({ "result": true }));
219 }
220
221 #[tokio::test]
222 async fn a_value_that_holds_an_operator_does_not_change_what_is_compared() {
223 let n = mk("{{a.response}} != OK");
224 let mut scope = ExecutionScope::new();
225 for reply in ["status == red", "if a == b then c", "x != OK", "5 > 3", "OK"] {
226 scope.outputs.insert("a".to_string(), json!({ "response": reply }));
227 let out = run(&n, &scope).await.unwrap();
228 assert_eq!(out, json!({ "result": reply != "OK" }), "{reply:?}");
229 }
230 }
231
232 async fn ask(expr: &str, scope: &ExecutionScope) -> Result<bool, String> {
235 run(&mk(expr), scope).await.map(|out| out["result"].as_bool().unwrap())
236 }
237
238 fn scope_with(outputs: Value) -> ExecutionScope {
239 let mut scope = ExecutionScope::new();
240 for (id, out) in outputs.as_object().unwrap() {
241 scope.outputs.insert(id.clone(), out.clone());
242 }
243 scope
244 }
245
246 #[tokio::test]
247 async fn combines_references_with_and_or_not_and_grouping() {
248 let scope = scope_with(json!({ "a": { "output": { "confidence": "high", "area": "srv" }, "cost_usd": 0.4 } }));
249 assert_eq!(ask("{{a.output.confidence}} != 'low' && {{a.output.area}} == 'srv'", &scope).await, Ok(true));
250 assert_eq!(ask("!({{a.output.confidence}} == 'high')", &scope).await, Ok(false));
251 assert_eq!(ask("({{a.cost_usd}} > 1 || {{a.output.area}} == 'srv') && !({{a.output.area}} == 'ui')", &scope).await, Ok(true));
252 assert_eq!(ask("{{a.cost_usd}} < 1 && ({{a.output.confidence}} == 'low' || {{a.output.area}} == 'ui')", &scope).await, Ok(false));
253 }
254
255 #[tokio::test]
256 async fn contains_matches_in_set_and_exists_read_typed_values() {
257 let scope = scope_with(json!({
258 "api": { "body": { "labels": ["bug", "srv"], "title": "Crash on start" }, "log": "step 3 failed: disk full" },
259 }));
260 assert_eq!(ask("{{api.body.labels}} contains 'bug'", &scope).await, Ok(true));
261 assert_eq!(ask("{{api.body.title}} contains 'Crash'", &scope).await, Ok(true));
262 assert_eq!(ask("{{api.log}} matches 'step [0-9]+ failed'", &scope).await, Ok(true));
263 assert_eq!(ask("{{api.body.labels}} contains 'docs'", &scope).await, Ok(false));
264 assert_eq!(ask("exists({{api.body.title}}) && !exists({{api.body.owner}})", &scope).await, Ok(true));
265 assert_eq!(ask("{{api.body.title}} in_set ['Crash on start', 'Slow']", &scope).await, Ok(true));
266 assert_eq!(ask("exists({{nobody.says}})", &scope).await, Ok(false), "a reference to nothing is nothing");
267 }
268
269 #[tokio::test]
270 async fn what_a_reference_holds_is_never_read_as_syntax() {
271 let mut scope = ExecutionScope::new();
272 let hostile = ["x' || true || '", "a && b", "true) || (true", "1 == 1", "x\\' contains 'y"];
273 for reply in hostile {
274 scope.outputs.insert("a".to_string(), json!({ "response": reply }));
275 assert_eq!(ask("{{a.response}} == 'ok' && true", &scope).await, Ok(false), "{reply:?}");
276 assert_eq!(ask("!({{a.response}} == 'ok') && {{a.response}} contains ' '", &scope).await.is_ok(), true, "{reply:?}");
277 }
278 scope.outputs.insert("a".to_string(), json!({ "response": "ok" }));
279 assert_eq!(ask("{{a.response}} == 'ok' && true", &scope).await, Ok(true));
280 }
281
282 #[tokio::test]
283 async fn a_reference_may_carry_filters_in_both_forms() {
284 let scope = scope_with(json!({ "a": { "log": "all fine\nERROR disk full", "body": r#"{"n":3,"s":"ABC"}"# } }));
285 assert_eq!(ask("{{a.log | tail:1}} contains 'ERROR'", &scope).await, Ok(true));
286 assert_eq!(ask("{{a.log | head:1}} contains 'ERROR'", &scope).await, Ok(false));
287 assert_eq!(ask("{{a.body | json:n}} > 2 && {{a.body | json:s | lower}} == 'abc'", &scope).await, Ok(true));
288 assert_eq!(ask("exists({{a.body | json:gone}}) || {{a.missing | default:none}} == 'none'", &scope).await, Ok(true));
289 assert_eq!(ask("{{a.log | trunc:3}} == all", &scope).await, Ok(true), "the simple form reads filters too");
290 }
291
292 #[tokio::test]
293 async fn the_simple_form_keeps_its_reading_with_bare_words() {
294 let mut scope = ExecutionScope::new();
295 scope.outputs.insert("a".to_string(), json!({ "response": "OK!" }));
296 assert_eq!(ask("{{a.response}} == OK!", &scope).await, Ok(true), "a bang after text is no negation");
297 assert_eq!(ask("{{a.response}} != OK", &scope).await, Ok(true));
298 assert_eq!(ask("3 != 4", &scope).await, Ok(true));
299 }
300
301 #[tokio::test]
302 async fn a_reference_inside_quotes_is_refused_in_the_new_form_and_a_bad_expression_says_why() {
303 let scope = scope_with(json!({ "a": { "response": "x" } }));
304 let err = ask("'{{a.response}}' contains 'x'", &scope).await.unwrap_err();
305 assert!(err.contains("cannot sit inside quotes"), "{err}");
306 let err = ask("{{a.response} contains 'x'", &scope).await.unwrap_err();
307 assert!(err.contains("no `}}`"), "{err}");
308 let err = ask("{{a.response}} contains", &scope).await.unwrap_err();
309 assert!(err.starts_with("condition: "), "{err}");
310 let err = ask("{{a.response}} && true", &scope).await.unwrap_err();
311 assert!(err.contains("true or false is expected"), "{err}");
312 }
313
314 #[tokio::test]
316 async fn the_after_upgrade_checks_condition_is_true_only_when_agents_muxbus_and_peers_are_all_up() {
317 use crate::backend::job_templates::{graph, package, DRONE_BUILTINS};
318 let b = DRONE_BUILTINS.iter().find(|b| b.id == "agentmux.after-upgrade-check").unwrap();
319 let pkg = package::load_embedded(b.id, b.files).unwrap();
320 let given = json!({ "leader": "agenty", "steward": "masty" }).as_object().cloned().unwrap();
321 let g = graph::render(pkg.graph.as_ref().unwrap(), &pkg.manifest, &given).unwrap();
322 let cond = g.nodes.iter().find(|n| n.id == "healthy").unwrap();
323 let ask = |all_up: bool, connected: bool, answered: u32, count: u32| {
324 let scope = scope_with(json!({ "agents": { "all_up": all_up }, "muxbus": { "connected": connected }, "peers": { "answered": answered, "count": count } }));
325 async move { run(cond, &scope).await.unwrap()["result"].clone() }
326 };
327 assert_eq!(ask(true, true, 3, 3).await, json!(true), "everything up");
328 assert_eq!(ask(true, true, 0, 0).await, json!(true), "a machine with no peers has none to miss");
329 assert_eq!(ask(false, true, 3, 3).await, json!(false), "an agent down");
330 assert_eq!(ask(true, false, 3, 3).await, json!(false), "MuxBus down");
331 assert_eq!(ask(true, true, 2, 3).await, json!(false), "a peer silent");
332 }
333
334 #[tokio::test]
336 async fn the_acceptance_drones_conditions_read_a_poll_item_and_a_call_as_the_templates_mean() {
337 use crate::backend::job_templates::{graph, package, DRONE_BUILTINS};
338 let cond = |id: &str, node: &str, given: Value| {
339 let b = DRONE_BUILTINS.iter().find(|b| b.id == id).unwrap();
340 let pkg = package::load_embedded(b.id, b.files).unwrap();
341 let g = graph::render(pkg.graph.as_ref().unwrap(), &pkg.manifest, given.as_object().unwrap()).unwrap();
342 g.nodes.iter().find(|n| n.id == node).unwrap().clone()
343 };
344 let scope_item = |item: Value, outputs: Value| {
345 let mut scope = ExecutionScope::with_trigger(json!({ "key": item["id"].to_string(), "item": item }));
346 for (id, out) in outputs.as_object().unwrap() {
347 scope.outputs.insert(id.clone(), out.clone());
348 }
349 scope
350 };
351 let nightly = "agentmux.triage-failed-nightly";
353 let params = json!({ "repo": "acme/site", "leader": "agenty" });
354 let found = cond(nightly, "found", params.clone());
355 assert_eq!(run(&found, &scope_with(json!({ "failed": { "value": { "id": 77 } } }))).await.unwrap()["result"], json!(true));
356 assert_eq!(run(&found, &scope_with(json!({ "failed": { "value": null } }))).await.unwrap()["result"], json!(false), "no failed job in the run");
357 let sure = cond(nightly, "sure", params);
358 assert_eq!(run(&sure, &scope_with(json!({ "triage": { "output": { "confidence": "high" } } }))).await.unwrap()["result"], json!(true));
359 assert_eq!(run(&sure, &scope_with(json!({ "triage": { "output": { "confidence": "low" } } }))).await.unwrap()["result"], json!(false));
360 let flaky = cond("agentmux.rerun-flaky-job", "flaky", json!({ "repo": "acme/site", "workflow": "CI", "leader": "agenty" }));
362 let ask = |name: &str, attempt: u32| {
363 let scope = scope_item(json!({ "id": 5, "name": name, "run_attempt": attempt }), json!({}));
364 let flaky = flaky.clone();
365 async move { run(&flaky, &scope).await.unwrap()["result"].clone() }
366 };
367 assert_eq!(ask("CI", 1).await, json!(true));
368 assert_eq!(ask("CI", 2).await, json!(false), "a run that was already re-run");
369 assert_eq!(ask("Docs", 1).await, json!(false), "another workflow");
370 let merged = cond("agentmux.merged-pr-still-claimed", "merged", json!({ "repo": "acme/site", "steward": "masty" }));
372 let was = |merged_at: Value| {
373 let scope = scope_item(json!({ "id": 9, "number": 9, "merged_at": merged_at }), json!({}));
374 let merged = merged.clone();
375 async move { run(&merged, &scope).await.unwrap()["result"].clone() }
376 };
377 assert_eq!(was(json!("2026-11-15T10:00:00Z")).await, json!(true));
378 assert_eq!(was(Value::Null).await, json!(false), "closed without a merge");
379 let any = cond("agentmux.merged-pr-still-claimed", "found", json!({ "repo": "acme/site", "steward": "masty" }));
380 assert_eq!(run(&any, &scope_with(json!({ "claimed": { "count": 1 } }))).await.unwrap()["result"], json!(true));
381 assert_eq!(run(&any, &scope_with(json!({ "claimed": { "count": 0 } }))).await.unwrap()["result"], json!(false));
382 let tell = cond("agentmux.merged-pr-still-claimed", "tell", json!({ "repo": "acme/site", "steward": "masty" }));
385 let mut scope = scope_item(json!({ "id": 9, "number": 9, "html_url": "https://github.com/acme/site/pull/9" }), json!({}));
386 scope.outputs.insert("claimed".to_string(), json!({ "count": 1, "tasks": [{ "num": 412, "title": "Fix the thing", "holder": "agent5" }] }));
387 let body = scope.resolve(tell.data["body"].as_str().unwrap());
388 assert!(body.contains("task #412 (Fix the thing) is still claimed by agent5."), "{body}");
389 assert!(body.contains("https://github.com/acme/site/pull/9"), "{body}");
390 }
391}