Skip to main content

agentmux_srv_core/backend/job_templates/
graph.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The Drone graph a template carries in `graph.json`
5//! (docs/specs/SPEC_DRONE_REAL_WORLD_JOBS_2026_11_11.md, "What is a template?").
6//!
7//! A graph is checked when the package is read, so a template that names a
8//! node this build does not have is `invalid` in the list, with the node named,
9//! and never reaches the operator's approval. [`summarize`] is what the
10//! approval prompt shows of the graph itself: how many nodes, how many of
11//! them start an agent, and every call that writes outside AgentMux.
12
13use std::collections::HashSet;
14
15use serde::{Deserialize, Serialize};
16use serde_json::{Map, Value};
17
18use super::manifest::{self, JobTemplateManifest};
19use crate::backend::storage::drone_types::{BlockKind, DroneGraph};
20
21/// The most nodes and edges a template graph holds.
22pub const MAX_NODES: usize = 100;
23pub const MAX_EDGES: usize = 300;
24
25/// The node kinds this build has, for the error that names a missing one.
26const KINDS: &str = "agent, condition, api, response, variables, message, task, notify, app_query, spawn, transform, foreach, wait, drone, join, run";
27
28/// What the approval prompt shows of a template's graph.
29#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, ts_rs::TS)]
30#[ts(export, export_to = "../../../frontend/types/rpc/")]
31pub struct DroneSummary {
32    pub nodes: u32,
33    /// Nodes that start an agent (an Agent node, or a Spawn node that opens a worker), each of which spends money.
34    pub agents: u32,
35    /// Every call that writes outside AgentMux, as `node id: METHOD url`.
36    pub writes_outside: Vec<String>,
37    /// Every place the template reads a credential from the Vault (an `auth.vault`), as `where: entry`, found in the
38    /// graph and the trigger themselves, not in what the manifest declares. [`summarize`] leaves it empty:
39    /// whoever has the trigger fills it in with [`credentials`].
40    #[serde(default)]
41    pub credentials: Vec<String>,
42}
43
44/// `graph.json` read and checked.
45pub fn parse(raw: &[u8]) -> Result<DroneGraph, String> {
46    let graph: DroneGraph = serde_json::from_slice(raw).map_err(|e| format!("graph.json: {e}"))?;
47    check(&graph)?;
48    Ok(graph)
49}
50
51/// The kind a node names in `data.kind`.
52fn kind_of(node: &crate::backend::storage::drone_types::FlowNode) -> Result<BlockKind, String> {
53    let name = node.data.get("kind").and_then(|k| k.as_str()).unwrap_or("");
54    BlockKind::parse(name).ok_or_else(|| format!("graph.json: node {:?} is a {name:?} node, and this AgentMux has only {KINDS}", node.id))
55}
56
57/// A graph this build can hold: within its limits, every node of a kind it
58/// has, every edge between nodes that exist.
59pub fn check(graph: &DroneGraph) -> Result<(), String> {
60    if graph.nodes.is_empty() {
61        return Err("graph.json has no nodes".to_string());
62    }
63    if graph.nodes.len() > MAX_NODES || graph.edges.len() > MAX_EDGES {
64        return Err(format!("graph.json is at most {MAX_NODES} nodes and {MAX_EDGES} edges"));
65    }
66    let mut ids = HashSet::new();
67    for node in &graph.nodes {
68        if node.id.trim().is_empty() || !ids.insert(node.id.as_str()) {
69            return Err(format!("graph.json: node id {:?} is empty or used twice", node.id));
70        }
71        // What another drone does is on the machine it is installed on, not in the template, so the
72        // prompt could not list it: a template does not call one.
73        let kind = kind_of(node)?;
74        if kind == BlockKind::Drone {
75            return Err(format!("graph.json: node {:?} calls another drone, and a template cannot: what that drone does could not be shown when the template is approved", node.id));
76        }
77        // A command is fixed content too: what it runs is not in the graph, and nothing here pins it.
78        if kind == BlockKind::Run {
79            return Err(format!("graph.json: node {:?} runs a command, and a template cannot: what the command does could not be shown when the template is approved", node.id));
80        }
81    }
82    for edge in &graph.edges {
83        for end in [&edge.source, &edge.target] {
84            if !ids.contains(end.as_str()) {
85                return Err(format!("graph.json: edge {:?} names node {end:?}, which isn't in the graph", edge.id));
86            }
87        }
88    }
89    Ok(())
90}
91
92/// What the prompt shows of a checked graph. An `api` node that is not a
93/// plain read writes outside; a Spawn node starts an agent, so it counts with
94/// the Agent nodes; the other nodes this build has stay inside AgentMux (a
95/// message goes to an agent on this computer).
96pub fn summarize(graph: &DroneGraph) -> DroneSummary {
97    let mut out = DroneSummary { nodes: graph.nodes.len() as u32, ..DroneSummary::default() };
98    for node in &graph.nodes {
99        let text = |key: &str| node.data.get(key).and_then(|v| v.as_str()).map(str::trim).unwrap_or("");
100        match kind_of(node) {
101            Ok(BlockKind::Agent | BlockKind::Spawn) => out.agents += 1,
102            Ok(BlockKind::Api) => {
103                let method = text("method").to_uppercase();
104                let method = if method.is_empty() { "GET".to_string() } else { method };
105                if method != "GET" && method != "HEAD" {
106                    out.writes_outside.push(format!("{}: {method} {}", node.id, text("url")));
107                }
108            }
109            _ => {}
110        }
111    }
112    out
113}
114
115/// Whether the graph has a node that writes outside AgentMux (an API call that is not a read) and an Approval block
116/// stands on every path to each of them, so no run reaches a write without a person's yes. False when it has no such
117/// write, or one of them can be reached without passing an Approval.
118pub fn approval_guards_every_write(graph: &DroneGraph) -> bool {
119    let kind = |n: &crate::backend::storage::drone_types::FlowNode| n.data.get("kind").and_then(|k| k.as_str()).and_then(BlockKind::parse);
120    let writes: Vec<&str> = graph
121        .nodes
122        .iter()
123        .filter(|n| kind(n) == Some(BlockKind::Api))
124        .filter(|n| {
125            let method = n.data.get("method").and_then(|m| m.as_str()).unwrap_or("GET").to_uppercase();
126            !matches!(method.as_str(), "GET" | "HEAD" | "OPTIONS")
127        })
128        .map(|n| n.id.as_str())
129        .collect();
130    if writes.is_empty() {
131        return false;
132    }
133    let approvals: HashSet<&str> = graph.nodes.iter().filter(|n| kind(n) == Some(BlockKind::Approval)).map(|n| n.id.as_str()).collect();
134    let targets: HashSet<&str> = graph.edges.iter().map(|e| e.target.as_str()).collect();
135    // Walk from every node nothing leads to, and do not go past an Approval.
136    let mut seen: HashSet<&str> = HashSet::new();
137    let mut stack: Vec<&str> = graph.nodes.iter().map(|n| n.id.as_str()).filter(|id| !targets.contains(id)).collect();
138    while let Some(id) = stack.pop() {
139        if !seen.insert(id) {
140            continue;
141        }
142        // Past an Approval only by its `error` handle (no, or silence) runs without a yes: those targets stay reachable.
143        let guarded = approvals.contains(id);
144        stack.extend(
145            graph
146                .edges
147                .iter()
148                .filter(|e| e.source == id && (!guarded || e.source_handle.as_deref() == Some("error")))
149                .map(|e| e.target.as_str()),
150        );
151    }
152    !approvals.is_empty() && writes.iter().all(|w| !seen.contains(w))
153}
154
155/// Every Vault entry the template reads a credential from, as `where: entry`: an `auth.vault` on a node or
156/// anywhere in the trigger (its poll's filter), whether the entry is a literal id or a `{{param.x}}`. This is
157/// what the template does, whatever its manifest's `secrets` says.
158pub fn credentials(graph: &DroneGraph, trigger: Option<&Value>) -> Vec<String> {
159    let mut out = Vec::new();
160    if let Some(t) = trigger {
161        vault_refs(t, "trigger", &mut out);
162    }
163    for node in &graph.nodes {
164        vault_refs(&node.data, &format!("node {}", node.id), &mut out);
165    }
166    out
167}
168
169fn vault_refs(v: &Value, at: &str, out: &mut Vec<String>) {
170    match v {
171        Value::Object(map) => {
172            if let Some(entry) = map.get("auth").and_then(|a| a.get("vault")) {
173                out.push(format!("{at}: {}", entry.as_str().map(str::to_string).unwrap_or_else(|| entry.to_string())));
174            }
175            map.values().for_each(|child| vault_refs(child, at, out));
176        }
177        Value::Array(items) => items.iter().for_each(|i| vault_refs(i, at, out)),
178        _ => {}
179    }
180}
181
182// ── Parameters ──────────────────────────────────────────────────────────────
183
184/// A parameter placeholder in a node's text: `{{param.repo}}`. Any other
185/// `{{` belongs to the drone's own templating and is left as it is.
186const PARAM_OPEN: &str = "{{param.";
187
188enum Seg<'a> {
189    Text(&'a str),
190    Param(&'a str),
191}
192
193/// `text` split into plain text and the parameter names it uses. A
194/// `{{param.` that does not close as a well-formed name is an error, so a
195/// typo can't pass as text.
196fn split_params(text: &str) -> Result<Vec<Seg<'_>>, String> {
197    let mut out = Vec::new();
198    let mut rest = text;
199    while let Some(start) = rest.find(PARAM_OPEN) {
200        out.push(Seg::Text(&rest[..start]));
201        let after = &rest[start + PARAM_OPEN.len()..];
202        let name = after.find("}}").map(|end| &after[..end]).filter(|n| manifest::valid_param_name(n));
203        let Some(name) = name else {
204            return Err(format!("{PARAM_OPEN} must open a placeholder like {PARAM_OPEN}repo}}}}"));
205        };
206        out.push(Seg::Param(name));
207        rest = &after[name.len() + 2..];
208    }
209    out.push(Seg::Text(rest));
210    Ok(out)
211}
212
213/// Every string inside the node's `data`, to read or rewrite.
214fn each_string(value: &mut Value, f: &mut dyn FnMut(&mut String) -> Result<(), String>) -> Result<(), String> {
215    match value {
216        Value::String(s) => f(s),
217        Value::Array(items) => items.iter_mut().try_for_each(|v| each_string(v, f)),
218        Value::Object(map) => map.values_mut().try_for_each(|v| each_string(v, f)),
219        _ => Ok(()),
220    }
221}
222
223/// The parameter names the graph uses, each of which the manifest must declare.
224pub fn param_names(graph: &DroneGraph) -> Result<Vec<String>, String> {
225    let mut names = Vec::new();
226    for node in &graph.nodes {
227        let mut data = node.data.clone();
228        each_string(&mut data, &mut |s| {
229            for part in split_params(s).map_err(|e| format!("graph.json: node {:?}: {e}", node.id))? {
230                if let Seg::Param(name) = part {
231                    names.push(name.to_string());
232                }
233            }
234            Ok(())
235        })?;
236    }
237    Ok(names)
238}
239
240/// The graph with each `{{param.NAME}}` replaced by its parameter's value
241/// (the given one, else the default). The values go in once and are never read
242/// for placeholders. A `{{` that a value contains, or that a value forms with the
243/// text next to it, is refused: the drone's own templating would read it at run
244/// time.
245pub fn render(graph: &DroneGraph, m: &JobTemplateManifest, given: &Map<String, Value>) -> Result<DroneGraph, String> {
246    let params = manifest::resolve_params(m, given)?;
247    refuse_reference_in_values(&params)?;
248    let mut out = graph.clone();
249    for node in &mut out.nodes {
250        let id = node.id.clone();
251        // A value put into a condition's expression is read as part of it: no quote or backslash, so it cannot close a
252        // literal and add to the expression.
253        let in_expression = node.data.get("kind").and_then(Value::as_str) == Some("condition");
254        each_string(&mut node.data, &mut |s| {
255            *s = fill(s, &params, in_expression)?;
256            Ok(())
257        })
258        .map_err(|e| format!("node {id:?}: {e}"))?;
259    }
260    Ok(out)
261}
262
263/// A parameter value that holds `{{` would be read as a reference by the drone's own templating.
264fn refuse_reference_in_values(params: &Map<String, Value>) -> Result<(), String> {
265    match params.iter().find(|(_, v)| manifest::as_text(v).contains("{{")) {
266        Some((name, _)) => Err(format!("parameter {name:?} can't contain {{{{: a drone would read it as a reference")),
267        None => Ok(()),
268    }
269}
270
271/// A parameter put into an address (after `scheme://`) is a name or `owner/name`: letters, digits, `.`, `_` and `-`, at
272/// most one `/` between two such parts, and no `.` or `..` part. Anything else (`?`, `#`, `%`, `@`, `:`, a space, a second
273/// slash) could turn the call into another one under the same Vault token.
274fn address_part(name: &str, value: &str) -> Result<(), String> {
275    let part_ok = |p: &str| !p.is_empty() && p != "." && p != ".." && p.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'));
276    let mut parts = value.split('/');
277    let (a, b, c) = (parts.next().unwrap_or(""), parts.next(), parts.next());
278    if part_ok(a) && b.is_none_or(part_ok) && c.is_none() {
279        return Ok(());
280    }
281    Err(format!("parameter {name:?} is put into an address, so it is a name or owner/name (letters, digits, '.', '_' and '-', one '/' at most), not {value:?}"))
282}
283
284/// A parameter put into a condition's expression holds no quote mark and no backslash: a value with one could close the
285/// literal it sits in and change what the condition says.
286fn expression_part(name: &str, value: &str) -> Result<(), String> {
287    if value.chars().any(|c| matches!(c, '\'' | '"' | '`' | '\\')) {
288        return Err(format!("parameter {name:?} is put into a condition, so it holds no quote mark or backslash: {value:?}"));
289    }
290    Ok(())
291}
292
293/// `s` with each `{{param.NAME}}` replaced by the parameter's text. The values go in once and are never read for
294/// placeholders.
295fn fill(s: &str, params: &Map<String, Value>, in_expression: bool) -> Result<String, String> {
296    let mut text = String::with_capacity(s.len());
297    let mut inserted = Vec::new();
298    for part in split_params(s)? {
299        match part {
300            Seg::Text(plain) => text.push_str(plain),
301            Seg::Param(name) => {
302                let value = params.get(name).map(manifest::as_text).unwrap_or_default();
303                // Where a value lands decides what it may hold: in an address a Vault token is sent to, or in an expression.
304                if text.contains("://") {
305                    address_part(name, &value)?;
306                }
307                if in_expression {
308                    expression_part(name, &value)?;
309                }
310                let start = text.len();
311                text.push_str(&value);
312                inserted.push(start..text.len());
313            }
314        }
315    }
316    if opens_reference_in(&text, &inserted) {
317        return Err("a parameter value forms {{ with the text next to it: a drone would read it as a reference".to_string());
318    }
319    Ok(text)
320}
321
322/// The parameter names a JSON value's strings use (a template's trigger default), each of which the manifest must declare.
323pub fn param_names_in(value: &Value) -> Result<Vec<String>, String> {
324    let mut names = Vec::new();
325    each_string(&mut value.clone(), &mut |s| {
326        for part in split_params(s)? {
327            if let Seg::Param(name) = part {
328                names.push(name.to_string());
329            }
330        }
331        Ok(())
332    })?;
333    Ok(names)
334}
335
336/// `value` with each `{{param.NAME}}` in its strings replaced, for a template's trigger default: the repository a poll
337/// asks about is the one the drone's calls name. `params` are the resolved ones.
338pub fn render_value(value: &mut Value, params: &Map<String, Value>) -> Result<(), String> {
339    refuse_reference_in_values(params)?;
340    each_string(value, &mut |s| {
341        *s = fill(s, params, false)?;
342        Ok(())
343    })
344}
345
346/// Whether a `{{` in `text` takes in a byte of a value that was put in, which
347/// the template text alone would not have written.
348fn opens_reference_in(text: &str, inserted: &[std::ops::Range<usize>]) -> bool {
349    text.as_bytes()
350        .windows(2)
351        .enumerate()
352        .any(|(at, pair)| pair == b"{{" && inserted.iter().any(|r| at < r.end && at + 2 > r.start))
353}