Skip to main content

agentmux_srv/drone/
payload_schema.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! What a drone can read of what started it (`{{trigger.*}}`), field by field, and which of it is outside text
5//! (Drone real-world jobs spec §3.6).
6//!
7//! Every trigger kind publishes a schema: each field is **clean** (a number, a flag, a value from a short list, an id
8//! AgentMux made) or **tainted** (a text somebody outside the person's own design wrote: a title, a log, a body, a
9//! file name). The canvas lists the fields to complete `{{trigger.…}}` and marks a reference to a tainted one.
10//!
11//! This is what the graph can be told about its input; it is not what keeps a run safe. The engine still treats the
12//! whole trigger as outside text (`ExecutionScope::bits_of`) until the taint rules of phase 4 read these schemas, so
13//! a mistake here shows a wrong mark and never lets a value through.
14
15use serde::Serialize;
16use serde_json::{Map, Value};
17
18use crate::backend::jobs::definition::event_source;
19use crate::backend::jobs::{app_events, poll};
20
21/// One field a run reads as `{{trigger.<path>}}`.
22#[derive(Debug, Clone, PartialEq, Serialize, ts_rs::TS)]
23#[ts(export, export_to = "../../../frontend/types/rpc/")]
24pub struct PayloadField {
25    /// The dotted path under `trigger`, `*` for "any field the sender chose".
26    pub path: String,
27    /// `text`, `number`, `flag`, `id`, `choice`, or `any`.
28    pub kind: String,
29    /// True for a typed value; false for outside text.
30    pub clean: bool,
31    /// One line for the person: what it is.
32    pub note: String,
33}
34
35fn field(path: &str, kind: &str, clean: bool, note: &str) -> PayloadField {
36    PayloadField { path: path.to_string(), kind: kind.to_string(), clean, note: note.to_string() }
37}
38
39/// What every run of a drone job has, whatever started it. These are set by AgentMux, never by the sender.
40fn framing() -> Vec<PayloadField> {
41    vec![
42        field("kind", "choice", true, "how the run started: schedule, manual, retry or event"),
43        field("run_id", "id", true, "this run's id in the ledger"),
44        field("fired_at_ms", "number", true, "when the run started"),
45        field("scheduled_for_ms", "number", true, "the slot a timer run was due for"),
46        field("job.id", "id", true, "the job that started the run"),
47        field("job.name", "text", false, "the job's name"),
48    ]
49}
50
51/// The fields of the event named in an `app_event` filter, as `app_events::event_of` builds them.
52fn app_event_fields(event: &str) -> Vec<PayloadField> {
53    let mut out = vec![field("event", "choice", true, "the event's name")];
54    for name in app_events::fields_of(event).unwrap_or(&[]) {
55        out.push(match (event, *name) {
56            (_, "agent") => field("agent", "id", true, "the agent's name"),
57            (_, "outcome") => field("outcome", "choice", true, "completed, errored or interrupted"),
58            (_, "cost_usd") => field("cost_usd", "number", true, "what the turn cost"),
59            (_, "reason") => field("reason", "text", false, "why the agent stopped, as the failure says it"),
60            (_, "version") => field("version", "text", true, "the version AgentMux started as"),
61            (_, "upgraded") => field("upgraded", "flag", true, "whether this start made an upgrade"),
62            (_, "upgraded_from") => field("upgraded_from", "text", true, "the version it upgraded from, empty if none"),
63            // A field added to an event but not yet described here: outside text until someone says otherwise.
64            (_, other) => field(other, "any", false, "not described yet"),
65        });
66    }
67    out
68}
69
70/// The fields of one poll item, by query. `item` is one entry of the list the check answered with.
71fn poll_fields(query: &str) -> Vec<PayloadField> {
72    let mut out = vec![field("query", "choice", true, "which check found it")];
73    match query {
74        "tasks" => out.extend([
75            field("key", "id", true, "the task's number"),
76            field("item.num", "number", true, "the task's number"),
77            field("item.state", "choice", true, "where the task stands"),
78            field("item.holder", "id", true, "the agent that holds it"),
79            field("item.title", "text", false, "the task's title"),
80            field("item.pr", "text", false, "the pull request link"),
81            field("item.branch", "text", false, "the branch name"),
82        ]),
83        "jobs" => out.extend([
84            field("key", "id", true, "the run's id"),
85            field("item.id", "id", true, "the run's id"),
86            field("item.job_id", "id", true, "the job's id"),
87            field("item.state", "choice", true, "the run's state"),
88            field("item.outcome", "choice", true, "how the run ended"),
89            field("item.trigger", "choice", true, "how the run started"),
90            field("item.started_ms", "number", true, "when it started"),
91            field("item.ended_ms", "number", true, "when it ended"),
92            field("item.cost_usd", "number", true, "what it cost"),
93            field("item.job", "text", false, "the job's name"),
94            field("item.summary", "text", false, "the run's summary line"),
95        ]),
96        "agents" => out.extend([
97            field("key", "id", true, "the agent and its state"),
98            field("item.agent", "id", true, "the agent's name"),
99            field("item.state", "choice", true, "the agent's state"),
100            field("item.detail", "text", false, "what the state says"),
101        ]),
102        "lan_peers" => out.extend([
103            field("key", "text", false, "the peer's host name, as the peer says it"),
104            field("item", "any", false, "what the peer reports about itself"),
105        ]),
106        // A site's list: nothing in it is AgentMux's own.
107        _ => out.extend([field("key", "text", false, "the item's id, as the site gives it"), field("item", "any", false, "the item, as the site gives it")]),
108    }
109    out
110}
111
112/// What a run started by hand or by an agent (`fire`) reads: whatever the caller gave. Not even the framing is AgentMux's
113/// here, because only a job's run has it (`job_actions::drone_trigger`); a caller can send or leave out any of it.
114pub fn by_hand_fields() -> Vec<PayloadField> {
115    vec![field("*", "any", false, "what the caller gave: outside text")]
116}
117
118/// The fields a run reads, for a job started by `source` (an `event_source`, or `None` for a timer or a hand run) with
119/// the trigger's own `filter`. The framing fields come first.
120pub fn fields_of(source: Option<&str>, filter: &Map<String, Value>) -> Vec<PayloadField> {
121    let mut out = framing();
122    match source {
123        Some(event_source::APP_EVENT) => out.extend(app_event_fields(filter.get("event").and_then(Value::as_str).unwrap_or(""))),
124        Some(event_source::POLL) => out.extend(poll_fields(filter.get("query").and_then(Value::as_str).unwrap_or(""))),
125        Some(event_source::FILE_WATCH) => out.extend([
126            field("root", "text", true, "the folder the job watches"),
127            field("count", "number", true, "how many paths changed"),
128            field("change", "choice", true, "created, modified, removed or mixed"),
129            field("paths", "any", false, "the changed paths: names are chosen by whoever wrote the files"),
130            field("first", "text", false, "the first changed path"),
131        ]),
132        Some(event_source::WEBHOOK_LOCAL) => out.push(field("*", "any", false, "the JSON body: every field is outside text")),
133        Some(event_source::EXPECT) => out.extend([
134            field("expected", "id", true, "the job that was expected"),
135            field("within_minutes", "number", true, "how long it had"),
136            field("last_ok_ms", "number", true, "when it last ended well"),
137            field("job_found", "flag", true, "whether the job exists"),
138            field("last_seen.id", "id", true, "the newest run's id"),
139            field("last_seen.state", "choice", true, "the newest run's state"),
140            field("last_seen.outcome", "choice", true, "the newest run's outcome"),
141            field("last_seen.started_ms", "number", true, "when it started"),
142            field("last_seen.ended_ms", "number", true, "when it ended"),
143        ]),
144        // A timer has only the framing. A run started by hand or by another agent reads what that sender gave.
145        _ => out.push(field("*", "any", false, "what the sender gave: outside text")),
146    }
147    out
148}
149
150/// Whether `{{trigger.<path>}}` is outside text under `fields`: it is unless the path, or a parent of it, is a clean
151/// field. A path no field names is outside text (it can only come from the sender).
152pub fn is_tainted(fields: &[PayloadField], path: &str) -> bool {
153    let under = |p: &str, of: &str| p == of || p.strip_prefix(of).is_some_and(|rest| rest.starts_with('.'));
154    match fields.iter().filter(|f| f.path != "*" && under(path, &f.path)).max_by_key(|f| f.path.len()) {
155        Some(f) => !f.clean,
156        None => true,
157    }
158}
159
160#[cfg(test)]
161mod tests {
162    use super::*;
163    use serde_json::json;
164
165    fn filter(v: Value) -> Map<String, Value> {
166        v.as_object().cloned().unwrap_or_default()
167    }
168
169    fn clean_paths(fields: &[PayloadField]) -> Vec<&str> {
170        fields.iter().filter(|f| f.clean).map(|f| f.path.as_str()).collect()
171    }
172
173    #[test]
174    fn every_run_has_the_framing_fields_clean_but_the_job_name() {
175        let f = fields_of(None, &Map::new());
176        for p in ["kind", "run_id", "fired_at_ms", "scheduled_for_ms", "job.id"] {
177            assert!(!is_tainted(&f, p), "{p} is made by AgentMux");
178        }
179        assert!(is_tainted(&f, "job.name"));
180    }
181
182    #[test]
183    fn a_timer_reads_only_outside_text_besides_the_framing() {
184        let f = fields_of(None, &Map::new());
185        assert!(is_tainted(&f, "run"), "a field the sender chose");
186        assert!(is_tainted(&f, "run.conclusion"));
187    }
188
189    #[test]
190    fn a_hand_run_has_no_framing_a_caller_could_not_send_itself() {
191        let f = by_hand_fields();
192        for p in ["kind", "run_id", "job.id", "fired_at_ms", "anything"] {
193            assert!(is_tainted(&f, p), "{p}: a caller gives this text");
194        }
195    }
196
197    #[test]
198    fn an_app_event_describes_every_field_the_event_carries() {
199        for event in app_events::name::ALL {
200            let f = fields_of(Some(event_source::APP_EVENT), &filter(json!({ "event": event })));
201            for name in app_events::fields_of(event).expect("a listed event has fields") {
202                let found = f.iter().find(|x| x.path == *name).unwrap_or_else(|| panic!("{event}: {name} missing"));
203                assert_ne!(found.note, "not described yet", "{event}.{name} needs its own line");
204            }
205        }
206    }
207
208    #[test]
209    fn a_crash_reason_is_outside_text_and_the_agent_and_outcome_are_not() {
210        let f = fields_of(Some(event_source::APP_EVENT), &filter(json!({ "event": "agent.crashed" })));
211        assert!(is_tainted(&f, "reason"));
212        assert!(!is_tainted(&f, "agent"));
213        let t = fields_of(Some(event_source::APP_EVENT), &filter(json!({ "event": "agent.turn_ended" })));
214        assert!(!is_tainted(&t, "outcome") && !is_tainted(&t, "cost_usd"));
215    }
216
217    #[test]
218    fn a_task_poll_keeps_the_title_apart_from_the_number() {
219        let f = fields_of(Some(event_source::POLL), &filter(json!({ "query": "tasks" })));
220        assert!(!is_tainted(&f, "item.num") && !is_tainted(&f, "key"));
221        assert!(is_tainted(&f, "item.title"));
222        assert!(is_tainted(&f, "item"), "the item whole has the title in it");
223        assert!(is_tainted(&f, "item.other"), "a field nobody described");
224    }
225
226    #[test]
227    fn a_site_poll_is_all_outside_text_but_the_query() {
228        let f = fields_of(Some(event_source::POLL), &filter(json!({ "query": "api", "url": "https://x.test/a" })));
229        assert_eq!(clean_paths(&f).iter().filter(|p| !["kind", "run_id", "fired_at_ms", "scheduled_for_ms", "job.id"].contains(p)).collect::<Vec<_>>(), vec![&"query"]);
230        assert!(is_tainted(&f, "item.title") && is_tainted(&f, "key"));
231    }
232
233    #[test]
234    fn a_webhook_body_and_file_names_are_outside_text() {
235        let w = fields_of(Some(event_source::WEBHOOK_LOCAL), &Map::new());
236        assert!(is_tainted(&w, "anything"));
237        let fw = fields_of(Some(event_source::FILE_WATCH), &Map::new());
238        assert!(is_tainted(&fw, "paths") && is_tainted(&fw, "first"));
239        assert!(!is_tainted(&fw, "count") && !is_tainted(&fw, "change"));
240    }
241
242    #[test]
243    fn a_child_path_follows_the_nearest_field_that_names_it() {
244        let f = fields_of(Some(event_source::EXPECT), &Map::new());
245        assert!(!is_tainted(&f, "last_seen.outcome"));
246        assert!(is_tainted(&f, "last_seen"), "the whole object is not a clean field of its own");
247    }
248
249    #[test]
250    fn every_poll_query_has_a_schema() {
251        for q in poll::QUERIES {
252            let f = fields_of(Some(event_source::POLL), &filter(json!({ "query": q })));
253            assert!(f.iter().any(|x| x.path == "key"), "{q} has a key");
254        }
255    }
256}