Skip to main content

agentmux_srv_core/backend/job_templates/
manifest.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `template.json` and `brief.md`: what a job template declares, its checks,
5//! the Rule of Two, and the brief it renders from parameters
6//! (docs/specs/SPEC_JOBS_AND_TEMPLATES_2026_10_24.md §5.4, §6).
7//!
8//! The trigger, action and policy are defaults for a job made from the
9//! template. Only what this module needs is checked here (the trigger's and
10//! the action's kind, the policy's `approval`); the job definition checks the
11//! rest when a job is created.
12
13use std::collections::{BTreeMap, HashSet};
14
15use serde::{Deserialize, Serialize};
16use serde_json::{Map, Value};
17
18use super::cloud::{CloudExpect, CloudReporter, CloudRunNow};
19use crate::backend::widget::packages as wp;
20
21pub const TEMPLATE_VERSION: u32 = 1;
22const MAX_PARAMS: usize = 32;
23const MAX_STRING_CHARS: usize = 4000;
24const MAX_LIST_ITEMS: usize = 100;
25const MAX_SECRETS: usize = 16;
26
27/// The trigger kinds a job has (§5.1). `event` is accepted in a template, so
28/// the Rule of Two can see it; a job can't use it before P5.
29const TRIGGER_KINDS: &[&str] = &["cron", "every", "once", "manual", "event"];
30const ACTION_KINDS: &[&str] = &["message", "task", "spawn"];
31
32/// Outputs that stay inside AgentMux or with the job's owner.
33const INSIDE_OUTPUTS: &[&str] = &["report_file", "kanban_task", "message:owner"];
34/// Outputs that write outside: to a repository, another agent, or a deployment.
35pub const OUTSIDE_OUTPUTS: &[&str] = &["pull_request", "comment", "message:others", "deploy", "ci_rerun"];
36
37#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, ts_rs::TS)]
38#[serde(rename_all = "lowercase")]
39#[ts(export, export_to = "../../../frontend/types/rpc/")]
40pub enum JobTemplateKind {
41    Job,
42    Cloud,
43    /// A Drone graph (`graph.json`) the job runs, instead of a brief.
44    Drone,
45}
46
47/// One parameter, as a JSON Schema subset: `string` (with `enum`, or
48/// `format: "credential"` for a Vault entry reference), `number`, `boolean`,
49/// and `array` of strings.
50#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, ts_rs::TS)]
51#[serde(rename_all = "camelCase", deny_unknown_fields)]
52#[ts(export, export_to = "../../../frontend/types/rpc/")]
53pub struct JobTemplateParam {
54    #[serde(rename = "type")]
55    pub ty: String,
56    #[serde(default, skip_serializing_if = "Option::is_none")]
57    pub title: Option<String>,
58    #[serde(default, skip_serializing_if = "Option::is_none")]
59    pub description: Option<String>,
60    #[serde(default, skip_serializing_if = "Option::is_none")]
61    #[ts(type = "unknown")]
62    pub default: Option<Value>,
63    #[serde(default, rename = "enum", skip_serializing_if = "Option::is_none")]
64    pub enum_values: Option<Vec<String>>,
65    #[serde(default, skip_serializing_if = "Option::is_none")]
66    pub format: Option<String>,
67    #[serde(default, skip_serializing_if = "Option::is_none")]
68    pub items: Option<JobTemplateParamItems>,
69}
70
71#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, ts_rs::TS)]
72#[serde(deny_unknown_fields)]
73#[ts(export, export_to = "../../../frontend/types/rpc/")]
74pub struct JobTemplateParamItems {
75    #[serde(rename = "type")]
76    pub ty: String,
77}
78
79/// `params`: a JSON Schema object of parameters.
80#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, ts_rs::TS)]
81#[serde(deny_unknown_fields)]
82#[ts(export, export_to = "../../../frontend/types/rpc/")]
83pub struct JobTemplateParams {
84    #[serde(default, rename = "type", skip_serializing_if = "Option::is_none")]
85    pub ty: Option<String>,
86    #[serde(default)]
87    pub properties: BTreeMap<String, JobTemplateParam>,
88    #[serde(default)]
89    pub required: Vec<String>,
90}
91
92/// A secret the job's agent uses through Vault: an environment name and
93/// the `credential` parameter naming the Vault entry.
94#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, ts_rs::TS)]
95#[serde(deny_unknown_fields)]
96#[ts(export, export_to = "../../../frontend/types/rpc/")]
97pub struct JobTemplateSecret {
98    pub name: String,
99    pub param: String,
100    #[serde(default, skip_serializing_if = "Option::is_none")]
101    pub description: Option<String>,
102}
103
104#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, ts_rs::TS)]
105#[serde(rename_all = "camelCase", deny_unknown_fields)]
106#[ts(export, export_to = "../../../frontend/types/rpc/")]
107pub struct JobTemplateManifest {
108    pub template_version: u32,
109    pub id: String,
110    pub name: String,
111    pub version: String,
112    pub kind: JobTemplateKind,
113    pub description: String,
114    #[serde(default)]
115    pub params: JobTemplateParams,
116    #[serde(default, skip_serializing_if = "Option::is_none")]
117    #[ts(type = "Record<string, unknown> | null")]
118    pub trigger: Option<Value>,
119    #[serde(default, skip_serializing_if = "Option::is_none")]
120    #[ts(type = "Record<string, unknown> | null")]
121    pub action: Option<Value>,
122    #[serde(default, skip_serializing_if = "Option::is_none")]
123    #[ts(type = "Record<string, unknown> | null")]
124    pub policy: Option<Value>,
125    #[serde(default)]
126    pub outputs: Vec<String>,
127    #[serde(default)]
128    pub secrets: Vec<JobTemplateSecret>,
129    /// The job reads text nobody vouches for (a pull request's, an inbound
130    /// message's), whatever its trigger.
131    #[serde(default)]
132    pub reads_untrusted: bool,
133    /// A cloud template's fields (§4.3); a job template carries none of them.
134    #[serde(default, skip_serializing_if = "Option::is_none")]
135    pub owner: Option<String>,
136    #[serde(default, skip_serializing_if = "Option::is_none")]
137    pub reporter: Option<CloudReporter>,
138    #[serde(default, skip_serializing_if = "Option::is_none")]
139    pub expect: Option<CloudExpect>,
140    #[serde(default, skip_serializing_if = "Option::is_none")]
141    pub max_duration_minutes: Option<u32>,
142    #[serde(default, skip_serializing_if = "Option::is_none")]
143    pub run_now: Option<CloudRunNow>,
144    /// The job reports a summary (runs per day, failures) instead of each run.
145    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
146    pub aggregate: bool,
147}
148
149/// A parameter's type, from its schema.
150#[derive(Debug, Clone, PartialEq)]
151pub enum ParamKind {
152    String,
153    Number,
154    Boolean,
155    Enum(Vec<String>),
156    StringList,
157    Credential,
158}
159
160pub(super) fn valid_param_name(n: &str) -> bool {
161    n.len() <= 40 && n.starts_with(|c: char| c.is_ascii_lowercase()) && n.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_')
162}
163
164pub fn param_kind(name: &str, p: &JobTemplateParam) -> Result<ParamKind, String> {
165    let kind = match (p.ty.as_str(), &p.enum_values, p.format.as_deref(), &p.items) {
166        ("string", None, None, None) => ParamKind::String,
167        ("string", Some(values), None, None) => {
168            if values.is_empty() || values.len() > 50 || values.iter().collect::<HashSet<_>>().len() != values.len() {
169                return Err(format!("parameter {name:?}: enum needs 1–50 different values"));
170            }
171            ParamKind::Enum(values.clone())
172        }
173        ("string", None, Some("credential"), None) => ParamKind::Credential,
174        ("number", None, None, None) => ParamKind::Number,
175        ("boolean", None, None, None) => ParamKind::Boolean,
176        ("array", None, None, Some(items)) if items.ty == "string" => ParamKind::StringList,
177        _ => {
178            return Err(format!(
179                "parameter {name:?} must be a string (with enum, or format \"credential\"), a number, a boolean, or an array of strings"
180            ))
181        }
182    };
183    Ok(kind)
184}
185
186/// `value` checked as a value of `kind`.
187fn check_value(name: &str, kind: &ParamKind, value: &Value) -> Result<(), String> {
188    let ok = match (kind, value) {
189        (ParamKind::String, Value::String(s)) => s.chars().count() <= MAX_STRING_CHARS,
190        (ParamKind::Number, Value::Number(_)) => true,
191        (ParamKind::Boolean, Value::Bool(_)) => true,
192        (ParamKind::Enum(values), Value::String(s)) => values.contains(s),
193        (ParamKind::StringList, Value::Array(items)) => {
194            items.len() <= MAX_LIST_ITEMS && items.iter().all(|i| i.as_str().is_some_and(|s| s.chars().count() <= MAX_STRING_CHARS))
195        }
196        // A Vault entry's id: one short token, never a value.
197        (ParamKind::Credential, Value::String(s)) => {
198            !s.is_empty() && s.len() <= 200 && s.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_' || b == b'.' || b == b':')
199        }
200        _ => false,
201    };
202    if ok {
203        Ok(())
204    } else {
205        Err(format!("parameter {name:?} isn't a valid {}", kind_name(kind)))
206    }
207}
208
209fn kind_name(kind: &ParamKind) -> &'static str {
210    match kind {
211        ParamKind::String => "string",
212        ParamKind::Number => "number",
213        ParamKind::Boolean => "boolean",
214        ParamKind::Enum(_) => "choice",
215        ParamKind::StringList => "list of strings",
216        ParamKind::Credential => "Vault entry reference",
217    }
218}
219
220/// A `kind` field of a JSON object, if it is one.
221fn kind_of(v: &Value) -> Option<&str> {
222    v.get("kind").and_then(Value::as_str)
223}
224
225impl JobTemplateManifest {
226    /// Whether a run reads untrusted input: declared, or an event trigger.
227    pub fn reads_untrusted_input(&self) -> bool {
228        self.reads_untrusted || self.trigger.as_ref().and_then(kind_of) == Some("event")
229    }
230
231    /// Whether a run holds secrets: a declared secret or a credential parameter.
232    pub fn holds_secrets(&self) -> bool {
233        !self.secrets.is_empty() || self.params.properties.iter().any(|(n, p)| param_kind(n, p) == Ok(ParamKind::Credential))
234    }
235
236    pub fn outside_writes(&self) -> Vec<&str> {
237        self.outputs.iter().map(String::as_str).filter(|o| OUTSIDE_OUTPUTS.contains(o)).collect()
238    }
239
240    /// `policy.approval` is `required`.
241    pub fn requires_approval(&self) -> bool {
242        self.policy.as_ref().and_then(|p| p.get("approval")).and_then(Value::as_str) == Some("required")
243    }
244}
245
246/// The Rule of Two (§6): a run that reads untrusted input can't also hold
247/// secrets and write outside, unless each run waits for the operator's
248/// approval.
249pub fn rule_of_two(m: &JobTemplateManifest) -> Result<(), String> {
250    rule_of_two_with(m, false, false)
251}
252
253/// [`rule_of_two`], where `graph_credential` says the template's graph or trigger reads a credential
254/// from the Vault (`auth.vault`): that counts as holding secrets whatever `secrets` declares, which
255/// a Drone template cannot declare at all. `graph_approval` says an Approval block stands on every path to each write
256/// outside the graph makes (`graph::approval_guards_every_write`): a person is in between, as the policy would put one.
257pub fn rule_of_two_with(m: &JobTemplateManifest, graph_credential: bool, graph_approval: bool) -> Result<(), String> {
258    let outside = m.outside_writes();
259    let holds = m.holds_secrets() || graph_credential;
260    if m.reads_untrusted_input() && holds && !outside.is_empty() && !m.requires_approval() && !graph_approval {
261        let credential = if m.holds_secrets() { "holds secrets" } else { "uses a credential (an auth.vault in its graph or trigger)" };
262        return Err(format!(
263            "it reads untrusted input, {credential} and writes outside ({}): remove one of the three (read only trusted input, drop the credential, or make the outside write an inside one, such as a message or a task that says what to do), or its policy must say \"approval\": \"required\"",
264            outside.join(", ")
265        ));
266    }
267    Ok(())
268}
269
270/// Check a manifest and its brief; the first problem, in words the author
271/// can act on. `folder` is the package's folder name.
272pub fn validate(m: &JobTemplateManifest, folder: &str, brief: Option<&str>) -> Result<(), String> {
273    if m.template_version != TEMPLATE_VERSION {
274        return Err(format!("templateVersion {} isn't one this AgentMux reads (it reads {TEMPLATE_VERSION})", m.template_version));
275    }
276    if !wp::valid_id(&m.id) {
277        return Err(format!("id {:?} must look like publisher.name (lowercase letters, digits, -)", m.id));
278    }
279    if m.id != folder {
280        return Err(format!("id {:?} must match its folder name {:?}", m.id, folder));
281    }
282    if m.name.trim().is_empty() || m.name.chars().count() > 60 {
283        return Err("name must be 1–60 characters".to_string());
284    }
285    if !wp::valid_semver(&m.version) {
286        return Err(format!("version {:?} isn't semver (like 1.2.0)", m.version));
287    }
288    if m.description.trim().is_empty() || m.description.chars().count() > 500 {
289        return Err("description must be 1–500 characters".to_string());
290    }
291    let kinds = validate_params(m)?;
292    validate_defaults(m)?;
293    validate_outputs_and_secrets(m, &kinds)?;
294    if m.kind == JobTemplateKind::Drone && !m.secrets.is_empty() {
295        return Err("a Drone template can't declare secrets in this version of AgentMux".to_string());
296    }
297    super::cloud::validate(m)?;
298    match (m.kind, brief) {
299        (JobTemplateKind::Job, None) => return Err("a job template needs its brief in brief.md".to_string()),
300        (JobTemplateKind::Drone, Some(_)) => return Err("a Drone template has no brief.md: its graph is graph.json".to_string()),
301        (_, Some(b)) => {
302            for name in placeholders(b)? {
303                if !kinds.contains_key(name) {
304                    return Err(format!("brief.md uses {{{{{name}}}}}, which isn't one of its parameters"));
305                }
306            }
307        }
308        (JobTemplateKind::Cloud | JobTemplateKind::Drone, None) => {}
309    }
310    rule_of_two(m)
311}
312
313fn validate_params(m: &JobTemplateManifest) -> Result<BTreeMap<String, ParamKind>, String> {
314    let p = &m.params;
315    if p.ty.as_deref().is_some_and(|t| t != "object") {
316        return Err("params must be a JSON Schema object".to_string());
317    }
318    if p.properties.len() > MAX_PARAMS {
319        return Err(format!("a template takes at most {MAX_PARAMS} parameters"));
320    }
321    let mut kinds = BTreeMap::new();
322    for (name, param) in &p.properties {
323        if !valid_param_name(name) {
324            return Err(format!("parameter name {name:?} must be lowercase letters, digits and _, starting with a letter"));
325        }
326        let kind = param_kind(name, param)?;
327        if param.title.as_deref().is_some_and(|t| t.chars().count() > 80) || param.description.as_deref().is_some_and(|d| d.chars().count() > 500) {
328            return Err(format!("parameter {name:?}: title is at most 80 characters, description 500"));
329        }
330        if let Some(d) = &param.default {
331            if kind == ParamKind::Credential {
332                return Err(format!("parameter {name:?} names a Vault entry, which has no default"));
333            }
334            check_value(name, &kind, d).map_err(|e| format!("{e} as its default"))?;
335        }
336        kinds.insert(name.clone(), kind);
337    }
338    if let Some(r) = p.required.iter().find(|r| !kinds.contains_key(r.as_str())) {
339        return Err(format!("params.required names {r:?}, which isn't a parameter"));
340    }
341    Ok(kinds)
342}
343
344fn validate_defaults(m: &JobTemplateManifest) -> Result<(), String> {
345    if let Some(t) = &m.trigger {
346        match kind_of(t) {
347            Some(k) if TRIGGER_KINDS.contains(&k) => {}
348            _ => return Err(format!("trigger.kind must be one of {}", TRIGGER_KINDS.join(", "))),
349        }
350    }
351    match (m.kind, &m.action) {
352        (JobTemplateKind::Job, None) => return Err("a job template needs an action".to_string()),
353        (JobTemplateKind::Cloud, Some(_)) => return Err("a cloud template runs elsewhere and has no action".to_string()),
354        (JobTemplateKind::Drone, Some(_)) => return Err("a Drone template has no action: its graph is the action".to_string()),
355        (_, Some(a)) => match kind_of(a) {
356            Some("drone") => return Err("a Drone action needs a later version of AgentMux".to_string()),
357            Some(k) if ACTION_KINDS.contains(&k) => {
358                if a.get("brief").is_some() {
359                    return Err("the action's brief goes in brief.md, not in template.json".to_string());
360                }
361            }
362            _ => return Err(format!("action.kind must be one of {}", ACTION_KINDS.join(", "))),
363        },
364        (JobTemplateKind::Cloud | JobTemplateKind::Drone, None) => {}
365    }
366    if let Some(p) = &m.policy {
367        if !p.is_object() {
368            return Err("policy must be an object".to_string());
369        }
370        match p.get("approval") {
371            None => {}
372            Some(Value::String(a)) if a == "none" || a == "required" => {}
373            Some(_) => return Err("policy.approval must be \"none\" or \"required\"".to_string()),
374        }
375    }
376    Ok(())
377}
378
379fn validate_outputs_and_secrets(m: &JobTemplateManifest, kinds: &BTreeMap<String, ParamKind>) -> Result<(), String> {
380    let mut seen = HashSet::new();
381    for o in &m.outputs {
382        if !INSIDE_OUTPUTS.contains(&o.as_str()) && !OUTSIDE_OUTPUTS.contains(&o.as_str()) {
383            return Err(format!(
384                "unknown output {o:?} (outputs are {}, {})",
385                INSIDE_OUTPUTS.join(", "),
386                OUTSIDE_OUTPUTS.join(", ")
387            ));
388        }
389        if !seen.insert(o.as_str()) {
390            return Err(format!("output {o:?} is listed twice"));
391        }
392    }
393    if m.secrets.len() > MAX_SECRETS {
394        return Err(format!("a template declares at most {MAX_SECRETS} secrets"));
395    }
396    let mut names = HashSet::new();
397    for s in &m.secrets {
398        let well_formed = s.name.len() <= 64
399            && s.name.starts_with(|c: char| c.is_ascii_uppercase())
400            && s.name.bytes().all(|b| b.is_ascii_uppercase() || b.is_ascii_digit() || b == b'_');
401        if !well_formed || s.name.starts_with("AGENTMUX_") {
402            return Err(format!("secret name {:?} must be uppercase letters, digits and _, and not start with AGENTMUX_", s.name));
403        }
404        if !names.insert(s.name.as_str()) {
405            return Err(format!("secret {:?} is declared twice", s.name));
406        }
407        if kinds.get(&s.param) != Some(&ParamKind::Credential) {
408            return Err(format!("secret {:?} must name a parameter with format \"credential\"", s.name));
409        }
410    }
411    Ok(())
412}
413
414// ── The brief ───────────────────────────────────────────────────────────────
415
416enum Segment<'a> {
417    Text(&'a str),
418    Param(&'a str),
419}
420
421/// `brief` split into text and `{{name}}` placeholders. Any other `{{` is an
422/// error, so a typo can't pass as text.
423fn segments(brief: &str) -> Result<Vec<Segment<'_>>, String> {
424    let mut out = Vec::new();
425    let mut rest = brief;
426    while let Some(start) = rest.find("{{") {
427        out.push(Segment::Text(&rest[..start]));
428        let after = &rest[start + 2..];
429        let name = after.find("}}").map(|end| &after[..end]).filter(|n| valid_param_name(n));
430        let Some(name) = name else {
431            let line = brief[..brief.len() - rest.len() + start].matches('\n').count() + 1;
432            return Err(format!("brief.md line {line}: {{{{ must open a placeholder like {{{{repo}}}}"));
433        };
434        out.push(Segment::Param(name));
435        rest = &after[name.len() + 2..];
436    }
437    out.push(Segment::Text(rest));
438    Ok(out)
439}
440
441/// The parameter names `brief` uses.
442pub fn placeholders(brief: &str) -> Result<Vec<&str>, String> {
443    Ok(segments(brief)?
444        .into_iter()
445        .filter_map(|s| match s {
446            Segment::Param(n) => Some(n),
447            Segment::Text(_) => None,
448        })
449        .collect())
450}
451
452/// A brief rendered from parameters, and the parameters it used (the given
453/// ones and the defaults).
454#[derive(Debug, Clone, PartialEq)]
455pub struct RenderedBrief {
456    pub brief: String,
457    pub params: Map<String, Value>,
458}
459
460/// The values for `m`'s parameters: each given one checked, defaults for
461/// the rest. An unknown or missing parameter is an error.
462pub fn resolve_params(m: &JobTemplateManifest, given: &Map<String, Value>) -> Result<Map<String, Value>, String> {
463    if let Some(unknown) = given.keys().find(|k| !m.params.properties.contains_key(k.as_str())) {
464        return Err(format!("{} takes no parameter {unknown:?}", m.id));
465    }
466    let mut out = Map::new();
467    for (name, p) in &m.params.properties {
468        let kind = param_kind(name, p)?;
469        match given.get(name).or(p.default.as_ref()) {
470            Some(v) => {
471                check_value(name, &kind, v)?;
472                out.insert(name.clone(), v.clone());
473            }
474            None if m.params.required.contains(name) => return Err(format!("parameter {name:?} is required")),
475            None => {}
476        }
477    }
478    Ok(out)
479}
480
481/// A value as it reads in a brief.
482pub(super) fn as_text(v: &Value) -> String {
483    match v {
484        Value::String(s) => s.clone(),
485        Value::Array(items) => items.iter().filter_map(Value::as_str).collect::<Vec<_>>().join(", "),
486        other => other.to_string(),
487    }
488}
489
490/// `brief` with each placeholder replaced by its parameter's value, in one
491/// pass: a value is inserted as data and never read for placeholders.
492pub fn render(m: &JobTemplateManifest, brief: &str, given: &Map<String, Value>) -> Result<RenderedBrief, String> {
493    let params = resolve_params(m, given)?;
494    let mut out = String::with_capacity(brief.len());
495    for seg in segments(brief)? {
496        match seg {
497            Segment::Text(t) => out.push_str(t),
498            Segment::Param(name) => {
499                if !m.params.properties.contains_key(name) {
500                    return Err(format!("brief.md uses {{{{{name}}}}}, which isn't one of its parameters"));
501                }
502                out.push_str(&params.get(name).map(as_text).unwrap_or_default());
503            }
504        }
505    }
506    Ok(RenderedBrief { brief: out, params })
507}