Skip to main content

agentmux_srv/drone/
data_flow.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `{{var}}` interpolation — Mustache-style. Resolves
5//! `{{block_id.path}}`, `{{var.name}}`, `{{env.NAME}}` against the
6//! execution context (RFC #753 §2 Q5).
7//!
8//! A reference may carry filters, `{{a.log | tail:20 | lower}}` (see `filters`).
9//!
10//! The Phase 1 resolver is intentionally simple: regex find-replace
11//! over the input string. Loop scope (`{{loop.index}}`, `{{loop.item}}`)
12//! is added in Phase 2 alongside the Loop block.
13
14use std::collections::HashMap;
15
16use serde_json::Value;
17
18use super::state::{Reducer, RunState};
19use super::value::Tv;
20
21mod filters;
22
23/// Only env vars starting with this prefix are exposed to drone
24/// templates via `{{env.NAME}}`. See `ExecutionScope::lookup` for
25/// the security rationale.
26const DRONE_ENV_PREFIX: &str = "AGENTMUX_DR_";
27
28/// Holds the per-run scope. Maps:
29///   * `outputs[block_id]` — the JSON output of a completed block
30///   * `vars[name]` — drone-scope variables (set by Variables block)
31///   * `trigger` — what started the run: the input of `rundrone`, or what
32///     the job passed; `Null` when nothing did (`{{trigger.*}}`)
33///   * `drone_id` — the drone the run belongs to, for what a block keeps across
34///     runs and must not share with another drone (the Task block's dedupe key);
35///     empty for a scope built outside a run
36#[derive(Debug, Default, Clone)]
37pub struct ExecutionScope {
38    pub outputs: HashMap<String, Value>,
39    /// What `{{var.name}}` reads: a mirror of [`state`](Self::state)'s values.
40    pub vars: HashMap<String, Value>,
41    pub trigger: Value,
42    /// The run's named values with their reducers and taint bits. Write through
43    /// [`write_var`](Self::write_var), which keeps `vars` in step.
44    pub state: RunState,
45    /// Each block's output bits `(tainted, derived)`, set by the scheduler and
46    /// by the blocks that compute one. A block with none is clean.
47    pub bits: HashMap<String, (bool, bool)>,
48    /// `{{item}}` and `{{index}}` while a for-each runs its body, and the bits
49    /// of the item.
50    pub locals: HashMap<String, Value>,
51    pub local_bits: (bool, bool),
52    pub drone_id: String,
53    /// A background poll's call: with a Vault credential it may use only what the person already granted ("Always"),
54    /// and never asks (`server::drone_vault::Asking::Never`).
55    pub never_ask: bool,
56}
57
58impl ExecutionScope {
59    pub fn new() -> Self {
60        Self::default()
61    }
62
63    /// A scope for a run started by `trigger`.
64    pub fn with_trigger(trigger: Value) -> Self {
65        Self { trigger, ..Self::default() }
66    }
67
68    /// The value a template stands for: the raw value (a list, an object, a
69    /// number) when the template is one `{{...}}` token, else the text with every
70    /// token filled in.
71    pub fn value_of(&self, template: &str) -> Value {
72        let t = template.trim();
73        let one = t.strip_prefix("{{").and_then(|r| r.strip_suffix("}}")).filter(|inner| !inner.contains("{{") && !inner.contains("}}"));
74        if let Some(v) = one.and_then(|inner| self.lookup(inner.trim())) {
75            return v;
76        }
77        Value::String(self.resolve(template))
78    }
79
80    /// What one `{{path}}` token names, as the value itself, or none when nothing is there. `value_of` answers a
81    /// missing token with its own text; this tells the two apart.
82    pub fn lookup_ref(&self, path: &str) -> Option<Value> {
83        self.lookup(path.trim())
84    }
85
86    /// Declare how writes to `name` combine (`replace` when never declared).
87    pub fn declare_var(&mut self, name: &str, reducer: Reducer) -> Result<(), String> {
88        self.state.declare(name, reducer).map_err(|e| e.to_string())
89    }
90
91    /// Write a variable under its reducer, keeping the value `{{var.name}}` reads
92    /// in step with the state. An error leaves both as they were.
93    pub fn write_var(&mut self, name: &str, value: Tv) -> Result<(), String> {
94        self.state.write(name, value).map_err(|e| e.to_string())?;
95        if let Some(now) = self.state.get(name) {
96            self.vars.insert(name.to_string(), now.v.clone());
97        }
98        Ok(())
99    }
100
101    /// The bits `(tainted, derived)` of a text made by filling in `template`:
102    /// tainted when any value it reads is, derived when none is tainted and one
103    /// is derived. The trigger is outside text when something started the run.
104    pub fn bits_of(&self, template: &str) -> (bool, bool) {
105        let (mut tainted, mut derived) = (false, false);
106        let mut rest = template;
107        while let Some(open) = rest.find("{{") {
108            let Some(len) = find_close(&rest[open + 2..]) else { break };
109            // A filter changes what the text looks like, not where it came from: the bits are the reference's own.
110            let (path, _) = filters::split(&rest[open + 2..open + 2 + len]);
111            rest = &rest[open + 2 + len + 2..];
112            let mut parts = path.split('.');
113            let (t, d) = match parts.next().unwrap_or("") {
114                "trigger" => (!self.trigger.is_null(), false),
115                "env" => (false, false),
116                "item" | "index" if self.locals.contains_key(path.split('.').next().unwrap_or("")) => self.local_bits,
117                "var" | "vars" => parts.next().and_then(|name| self.state.get(name)).map(|tv| (tv.tainted, tv.derived)).unwrap_or((false, false)),
118                node => self.bits.get(node).copied().unwrap_or((false, false)),
119            };
120            tainted |= t;
121            derived |= d;
122        }
123        (tainted, !tainted && derived)
124    }
125
126    /// A scope for a run of the drone `drone_id`, started by `trigger`.
127    pub fn for_drone(drone_id: &str, trigger: Value) -> Self {
128        Self { trigger, drone_id: drone_id.to_string(), ..Self::default() }
129    }
130
131    /// Resolve `{{...}}` tokens in `input` against this scope. Unknown
132    /// tokens are left as-is (Phase 1 — Phase 2 will surface them as
133    /// validation errors).
134    pub fn resolve(&self, input: &str) -> String {
135        self.resolve_with(input, |v| v)
136    }
137
138    /// Like [`resolve`](Self::resolve), but each resolved value goes through
139    /// `wrap` before it is written, so a node can quote what came from outside
140    /// (an event, an API body, an agent's reply) while its own text stays as
141    /// the graph wrote it. An unresolved token is left as-is and not wrapped.
142    pub fn resolve_with(&self, input: &str, wrap: impl Fn(String) -> String) -> String {
143        let mut out = String::with_capacity(input.len());
144        let bytes = input.as_bytes();
145        let mut i = 0;
146        while i < bytes.len() {
147            // `{` is ASCII so the byte-level scan for `{{` is safe to
148            // run at any byte offset — UTF-8 continuation bytes are
149            // always >= 0x80 and never equal `{` (0x7B). The non-token
150            // emit path below walks one full Unicode scalar at a time
151            // to avoid splitting multi-byte sequences into separate
152            // Latin-1 `char`s (mojibake).
153            if i + 1 < bytes.len() && bytes[i] == b'{' && bytes[i + 1] == b'{' {
154                // Find the matching `}}`.
155                if let Some(end_rel) = find_close(&input[i + 2..]) {
156                    let token = &input[i + 2..i + 2 + end_rel];
157                    let resolved = self.lookup(token.trim());
158                    match resolved {
159                        Some(v) => out.push_str(&wrap(value_to_string(&v))),
160                        None => {
161                            // Leave unresolved tokens visible — easier to debug.
162                            out.push_str("{{");
163                            out.push_str(token);
164                            out.push_str("}}");
165                        }
166                    }
167                    i = i + 2 + end_rel + 2;
168                    continue;
169                }
170            }
171            // Copy one full Unicode scalar from `input` starting at
172            // byte i. `&str` guarantees a valid char starts here.
173            let ch_len = input[i..]
174                .chars()
175                .next()
176                .expect("byte index inside &str must start a valid char")
177                .len_utf8();
178            out.push_str(&input[i..i + ch_len]);
179            i += ch_len;
180        }
181        out
182    }
183
184    /// What a token stands for: the reference, then each `| filter` after it.
185    fn lookup(&self, token: &str) -> Option<Value> {
186        match filters::split(token) {
187            (path, Some(steps)) => filters::apply(self.lookup_path(path), steps),
188            (path, None) => self.lookup_path(path),
189        }
190    }
191
192    fn lookup_path(&self, path: &str) -> Option<Value> {
193        // Splits like `block1.response.text` → ["block1", "response", "text"].
194        let mut parts = path.split('.');
195        let head = parts.next()?;
196        let rest: Vec<&str> = parts.collect();
197
198        let root = if head == "var" || head == "vars" {
199            // `{{var.name.path}}` — name is the next part.
200            let name = rest.first()?;
201            let v = self.vars.get(*name)?;
202            return Some(walk(v.clone(), &rest[1..]));
203        } else if (head == "item" || head == "index") && self.locals.contains_key(head) {
204            // `{{item.path}}` and `{{index}}` inside a for-each body.
205            return Some(walk(self.locals.get(head)?.clone(), &rest));
206        } else if head == "trigger" {
207            // `{{trigger.path}}`: the run input. Missing keys resolve to
208            // nothing, so the token stays visible like any unknown one.
209            let mut v = &self.trigger;
210            for key in &rest {
211                v = v.get(*key)?;
212            }
213            return Some(v.clone());
214        } else if head == "env" {
215            // Restrict `{{env.NAME}}` to vars under the drone
216            // namespace prefix. Without this guard a Response template
217            // could read AWS_*, GITHUB_TOKEN, CLAUDE_API_KEY, etc. and
218            // surface them via the persisted run output, exfiltrating
219            // server-side secrets to any caller with drone access.
220            // (reagent P1 on PR #755.) Phase 2 introduces a per-drone
221            // configured allowlist; the prefix is the Phase 1 stopgap.
222            let name = rest.first()?;
223            if !name.starts_with(DRONE_ENV_PREFIX) {
224                return None;
225            }
226            return std::env::var(name).ok().map(Value::String);
227        } else {
228            // Treat head as a block id; rest is dot-path inside its output.
229            self.outputs.get(head)?
230        };
231        Some(walk(root.clone(), &rest))
232    }
233}
234
235fn find_close(s: &str) -> Option<usize> {
236    let bytes = s.as_bytes();
237    let mut i = 0;
238    while i + 1 < bytes.len() {
239        if bytes[i] == b'}' && bytes[i + 1] == b'}' {
240            return Some(i);
241        }
242        i += 1;
243    }
244    None
245}
246
247fn walk(mut v: Value, path: &[&str]) -> Value {
248    for key in path {
249        match v {
250            Value::Object(mut m) => {
251                v = m.remove(*key).unwrap_or(Value::Null);
252            }
253            _ => return Value::Null,
254        }
255    }
256    v
257}
258
259fn value_to_string(v: &Value) -> String {
260    match v {
261        Value::String(s) => s.clone(),
262        Value::Null => String::new(),
263        other => other.to_string(),
264    }
265}
266
267#[cfg(test)]
268mod tests {
269    use super::*;
270    use serde_json::json;
271
272    #[test]
273    fn resolves_block_output_path() {
274        let mut scope = ExecutionScope::new();
275        scope
276            .outputs
277            .insert("agent_1".to_string(), json!({ "response": "hello" }));
278        assert_eq!(scope.resolve("Got: {{agent_1.response}}"), "Got: hello");
279    }
280
281    #[test]
282    fn resolves_drone_var() {
283        let mut scope = ExecutionScope::new();
284        scope.vars.insert("name".to_string(), json!("world"));
285        assert_eq!(scope.resolve("hi {{var.name}}"), "hi world");
286    }
287
288    #[test]
289    fn resolves_trigger_path() {
290        let scope = ExecutionScope::with_trigger(json!({ "run": { "conclusion": "failure", "attempt": 2 } }));
291        assert_eq!(scope.resolve("{{trigger.run.conclusion}} #{{trigger.run.attempt}}"), "failure #2");
292    }
293
294    #[test]
295    fn trigger_without_input_or_key_stays_visible() {
296        let none = ExecutionScope::new();
297        assert_eq!(none.resolve("{{trigger.x}}"), "{{trigger.x}}");
298        let scope = ExecutionScope::with_trigger(json!({ "a": 1 }));
299        assert_eq!(scope.resolve("{{trigger.b}}"), "{{trigger.b}}");
300    }
301
302    #[test]
303    fn leaves_unknown_tokens_intact() {
304        let scope = ExecutionScope::new();
305        assert_eq!(scope.resolve("{{ghost.x}}"), "{{ghost.x}}");
306    }
307
308    #[test]
309    fn deep_path_into_object() {
310        let mut scope = ExecutionScope::new();
311        scope
312            .outputs
313            .insert("api1".to_string(), json!({ "body": { "id": 42 } }));
314        assert_eq!(scope.resolve("got id={{api1.body.id}}"), "got id=42");
315    }
316
317    #[test]
318    fn preserves_text_around_tokens() {
319        let mut scope = ExecutionScope::new();
320        scope.vars.insert("x".to_string(), json!("X"));
321        assert_eq!(scope.resolve("a {{var.x}} b {{var.x}} c"), "a X b X c");
322    }
323
324    #[test]
325    fn empty_input_is_empty() {
326        let scope = ExecutionScope::new();
327        assert_eq!(scope.resolve(""), "");
328    }
329
330    // ────────────────────────────────────────────────────────────────
331    // UTF-8 preservation (reagent P1 + codex P2 on PR #755)
332    // ────────────────────────────────────────────────────────────────
333
334    #[test]
335    fn preserves_multibyte_chars_around_tokens() {
336        let mut scope = ExecutionScope::new();
337        scope.vars.insert("name".to_string(), json!("world"));
338        // 'Olá' has a 2-byte codepoint (á = 0xC3 0xA1).
339        assert_eq!(scope.resolve("Olá {{var.name}}"), "Olá world");
340    }
341
342    #[test]
343    fn preserves_multibyte_token_value() {
344        let mut scope = ExecutionScope::new();
345        scope.vars.insert("greeting".to_string(), json!("こんにちは"));
346        assert_eq!(scope.resolve("hi: {{var.greeting}}"), "hi: こんにちは");
347    }
348
349    #[test]
350    fn preserves_emoji_passthrough() {
351        let scope = ExecutionScope::new();
352        // No tokens — pure passthrough. The pre-fix byte-wise copy
353        // would turn each UTF-8 byte of 🚀 (0xF0 0x9F 0x9A 0x80) into
354        // four separate Latin-1 chars; this assertion catches that.
355        assert_eq!(scope.resolve("ship it 🚀"), "ship it 🚀");
356    }
357
358    #[test]
359    fn preserves_multibyte_in_unresolved_token_passthrough() {
360        let scope = ExecutionScope::new();
361        // Unresolved tokens echo their surrounding context — make
362        // sure that path doesn't corrupt the surrounding bytes either.
363        assert_eq!(scope.resolve("café {{ghost}} ☕"), "café {{ghost}} ☕");
364    }
365
366    // ────────────────────────────────────────────────────────────────
367    // Env-var allowlist (reagent P1 on PR #755 v0.33.841)
368    // ────────────────────────────────────────────────────────────────
369
370    #[test]
371    fn env_var_allowed_under_drone_prefix() {
372        let key = "AGENTMUX_DR_TEST_PASS_KEY";
373        std::env::set_var(key, "hello");
374        let scope = ExecutionScope::new();
375        assert_eq!(
376            scope.resolve(&format!("got: {{{{env.{key}}}}}")),
377            "got: hello"
378        );
379        std::env::remove_var(key);
380    }
381
382    #[test]
383    fn env_var_outside_prefix_is_blocked() {
384        // Setting common secret-shaped names would let drones
385        // exfiltrate them via Response output if the lookup wasn't
386        // namespaced.
387        let secret_key = "AWS_TEST_SECRET_DO_NOT_LEAK";
388        std::env::set_var(secret_key, "TOPSECRET");
389        let scope = ExecutionScope::new();
390        // Without the AGENTMUX_DR_ prefix, lookup returns None —
391        // the template emits the unresolved token (passthrough).
392        let out = scope.resolve(&format!("leak: {{{{env.{secret_key}}}}}"));
393        assert!(!out.contains("TOPSECRET"), "secret value leaked: {out}");
394        std::env::remove_var(secret_key);
395    }
396
397    #[test]
398    fn env_var_path_blocked() {
399        // PATH is universally set; if it leaked, attackers could
400        // confirm a target's directory layout. Plain `env.PATH`
401        // without the prefix is rejected.
402        let scope = ExecutionScope::new();
403        assert_eq!(scope.resolve("{{env.PATH}}"), "{{env.PATH}}");
404    }
405
406    #[test]
407    fn filters_cut_and_reshape_a_reference() {
408        let mut scope = ExecutionScope::new();
409        scope.outputs.insert("run".to_string(), json!({ "log": "a\nb\nc\nd", "body": r#"{"conclusion":"FAILURE","n":3}"# }));
410        assert_eq!(scope.resolve("{{run.log | tail:2}}"), "c\nd");
411        assert_eq!(scope.resolve("{{ run.body | json:conclusion | lower }}!"), "failure!");
412        assert_eq!(scope.resolve("{{run.body | json:n}}"), "3");
413        assert_eq!(scope.resolve("{{run.nothing | default:none}}"), "none");
414        assert_eq!(scope.value_of("{{run.body | json:n}}"), json!(3), "a single token keeps its type");
415        assert_eq!(scope.value_of("{{run.log | head:1}}"), json!("a"));
416    }
417
418    #[test]
419    fn a_bad_filter_or_a_missing_value_leaves_the_token_visible() {
420        let mut scope = ExecutionScope::new();
421        scope.vars.insert("x".to_string(), json!("v"));
422        assert_eq!(scope.resolve("{{var.x | shout}}"), "{{var.x | shout}}");
423        assert_eq!(scope.resolve("{{var.gone | lower}}"), "{{var.gone | lower}}");
424        assert_eq!(scope.resolve("{{env.PATH | default:x}}"), "x", "the env guard still applies, and default fills the refusal");
425    }
426
427    #[test]
428    fn a_filter_does_not_clean_what_a_reference_holds() {
429        let mut scope = ExecutionScope::with_trigger(json!({ "title": "t" }));
430        scope.outputs.insert("a".to_string(), json!({ "r": "x" }));
431        scope.bits.insert("a".to_string(), (true, false));
432        assert_eq!(scope.bits_of("{{a.r}}"), (true, false));
433        assert_eq!(scope.bits_of("{{a.r | trunc:1 | lower}}"), (true, false));
434        assert_eq!(scope.bits_of("{{trigger.title | head:1}}"), (true, false));
435        assert_eq!(scope.bits_of("{{a.r | default:ok}}"), (true, false), "a default does not make the reference clean");
436    }
437}