Skip to main content

agentmux_srv_core/backend/jobs/
from_template.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4//! A job made from a template, and a template's update diff
5//! (docs/specs/SPEC_JOBS_AND_TEMPLATES_2026_10_24.md §5.4).
6//!
7//! [`apply`] works on the definition as JSON, before it is parsed: it pins the
8//! job to the approved template (id, version, hash), checks the parameters
9//! against the template's schema, renders the brief from them, and sets the
10//! outputs and secrets the template declares. A template that isn't approved,
11//! or changed since it was, can't make a job (`resolve_approved`). On a create
12//! it also fills in what the request left out from the template's defaults
13//! (name, trigger, action, policy).
14//!
15//! A job keeps the version it was made from. A newer one is offered with
16//! [`update_diff`]; accepting it is an edit that names the new version, which
17//! [`apply`] reads as an update and lays the template's policy defaults over
18//! the job's.
19
20use serde::Serialize;
21use serde_json::{json, Map, Value};
22
23use crate::backend::job_templates::{self as jt, ApprovedTemplate, JobTemplateState, JobTemplates};
24use crate::backend::jobs::definition::{JobDefinition, TemplateRef};
25
26/// Whether an edit (`fields` laid over `before`) changes what a template's
27/// render depends on: its pin or parameters, or the brief itself. An action
28/// edit that leaves the brief as it was (a new target) needs none. One that
29/// leaves the brief out, or writes another, is rendered again, so the
30/// template stays the brief's only author.
31pub fn edit_needs_render(fields: &Map<String, Value>, before: &JobDefinition) -> bool {
32    if fields.contains_key("template") || fields.contains_key("params") {
33        return true;
34    }
35    let before = serde_json::to_value(before).unwrap_or_default();
36    fields.get("action").is_some_and(|action| {
37        let sent = Value::Object(Map::from_iter([("action".to_string(), action.clone())]));
38        brief_of(&sent) != brief_of(&before)
39    })
40}
41
42fn text<'a>(v: &'a Value, key: &str) -> &'a str {
43    v.get(key).and_then(Value::as_str).unwrap_or("")
44}
45
46fn service() -> Result<&'static std::sync::Arc<JobTemplates>, String> {
47    jt::service().ok_or_else(|| "job templates aren't available on this AgentMux".to_string())
48}
49
50/// The template reference `def` carries, if any.
51fn reference(def: &Value) -> Option<&Value> {
52    def.get("template").filter(|t| !t.is_null())
53}
54
55/// Lay the approved template under `def`, a job definition as JSON. Does
56/// nothing when `def` names no template.
57///
58/// `previous` is the pin the job has now, on an edit; `None` on a create. A
59/// create takes the template's defaults for what `def` leaves out. An edit
60/// that names a different version or content than `previous` also takes the
61/// template's policy defaults over the job's (what [`update_diff`] showed).
62pub fn apply(def: &mut Value, previous: Option<&TemplateRef>) -> Result<(), String> {
63    if reference(def).is_none() {
64        return Ok(());
65    }
66    apply_with(def, previous, service()?)
67}
68
69pub(crate) fn apply_with(def: &mut Value, previous: Option<&TemplateRef>, svc: &JobTemplates) -> Result<(), String> {
70    let Some(asked) = reference(def).cloned() else { return Ok(()) };
71    let id = text(&asked, "id").trim().to_string();
72    if id.is_empty() {
73        return Err("template.id is required".to_string());
74    }
75    let version = match text(&asked, "version").trim() {
76        "" => svc
77            .get(&id)
78            .and_then(|(info, _)| info.manifest.map(|m| m.version))
79            .ok_or_else(|| format!("no job template {id}"))?,
80        v => v.to_string(),
81    };
82    let approved = svc.resolve_approved(&id, &version).map_err(|e| {
83        if previous.is_some() && e.contains(" is at version ") {
84            format!("{e}: this job is pinned to {version}; accept the template's update first")
85        } else {
86            e
87        }
88    })?;
89    let hash = text(&asked, "hash");
90    if !hash.is_empty() && hash != approved.hash {
91        return Err(format!("{id} changed since the job's template pin was recorded; it needs the operator's approval again"));
92    }
93    let Some(obj) = def.as_object_mut() else { return Err("a job definition is a JSON object".to_string()) };
94    let given = obj.get("params").and_then(Value::as_object).cloned().unwrap_or_default();
95    let rendered = approved.render(&given)?;
96    let moved = previous.is_some_and(|p| p.id != approved.id || p.version != approved.version || p.hash != approved.hash);
97    obj.insert("params".into(), Value::Object(rendered.params.clone()));
98    obj.insert("template".into(), json!({ "id": approved.id, "version": approved.version, "hash": approved.hash }));
99    obj.insert("outputs".into(), json!(approved.manifest.outputs));
100    obj.insert("secrets".into(), secrets_of(&approved, &rendered.params));
101    if approved.manifest.kind == jt::manifest::JobTemplateKind::Drone {
102        drone_action(obj, &approved.id)?;
103    } else {
104        set_brief(obj, &approved, &rendered.brief);
105    }
106    if previous.is_none() {
107        fill_defaults(obj, &approved, &rendered.params)?;
108    } else if moved {
109        let overlay = overlay_policy(obj.get("policy"), template_policy(&approved).as_ref());
110        obj.insert("policy".into(), overlay);
111    }
112    Ok(())
113}
114
115/// The template's secrets as the definition's: its declared environment names
116/// and the Vault entries the credential parameters name. A credential the
117/// parameters leave out (an optional one) is not a secret of this job.
118fn secrets_of(t: &ApprovedTemplate, params: &Map<String, Value>) -> Value {
119    let list: Vec<Value> = t
120        .manifest
121        .secrets
122        .iter()
123        .filter_map(|s| params.get(&s.param).and_then(Value::as_str).map(|vault| json!({ "name": s.name, "vault": vault })))
124        .collect();
125    Value::Array(list)
126}
127
128/// A job made from a Drone template runs a drone made from it
129/// (`jobs.templates.make_drone`): the action names that drone, and carries no brief.
130fn drone_action(obj: &Map<String, Value>, id: &str) -> Result<(), String> {
131    let action = obj.get("action").unwrap_or(&Value::Null);
132    if text(action, "kind") == "drone" && !text(action, "drone_id").trim().is_empty() {
133        return Ok(());
134    }
135    Err(format!("{id} is a Drone template: make its drone first (jobs.templates.make_drone), then give the job the action {{\"kind\": \"drone\", \"drone_id\": …}}"))
136}
137
138/// The action with the rendered brief in it: a task's payload, else the brief.
139fn set_brief(obj: &mut Map<String, Value>, t: &ApprovedTemplate, brief: &str) {
140    let mut action = obj.get("action").and_then(Value::as_object).cloned().unwrap_or_default();
141    if text(&Value::Object(action.clone()), "kind").is_empty() {
142        if let Some(kind) = t.manifest.action.as_ref().and_then(|a| a.get("kind")) {
143            action.insert("kind".into(), kind.clone());
144        }
145    }
146    let field = if action.get("kind").and_then(Value::as_str) == Some("task") { "payload" } else { "brief" };
147    action.insert(field.into(), Value::String(brief.to_string()));
148    obj.insert("action".into(), Value::Object(action));
149}
150
151/// What a create leaves out, from the template: the name, the trigger and the
152/// policy. The request's own fields win.
153fn fill_defaults(obj: &mut Map<String, Value>, t: &ApprovedTemplate, params: &Map<String, Value>) -> Result<(), String> {
154    if obj.get("name").and_then(Value::as_str).is_none_or(|n| n.trim().is_empty()) {
155        obj.insert("name".into(), Value::String(t.manifest.name.clone()));
156    }
157    if obj.get("trigger").is_none_or(Value::is_null) {
158        // A Drone template's trigger may name its parameters (the repository a poll asks about is the one the graph's calls name).
159        let mut trigger = t.manifest.trigger.clone().unwrap_or_else(|| json!({ "kind": "manual" }));
160        jt::graph::render_value(&mut trigger, params)?;
161        obj.insert("trigger".into(), trigger);
162    }
163    if let Some(defaults) = template_policy(t) {
164        let own = obj.get("policy").cloned();
165        obj.insert("policy".into(), overlay_policy(Some(&defaults), own.as_ref()));
166    }
167    // The action's own fields (a target) win over the template's kind.
168    if let Some(base) = t.manifest.action.as_ref().and_then(Value::as_object) {
169        let mut action = base.clone();
170        for (k, v) in obj.get("action").and_then(Value::as_object).cloned().unwrap_or_default() {
171            action.insert(k, v);
172        }
173        obj.insert("action".into(), Value::Object(action));
174    }
175    Ok(())
176}
177
178/// Policy settings this build can't run yet (`cron::runnable_yet`). A
179/// template's default for one is left out, so it doesn't refuse every job
180/// made from the template.
181const NOT_RUNNABLE_YET: [&str; 1] = ["max_turns"];
182
183/// The template's policy defaults a job can take.
184fn template_policy(t: &ApprovedTemplate) -> Option<Value> {
185    let mut policy = t.manifest.policy.clone()?;
186    if let Some(obj) = policy.as_object_mut() {
187        NOT_RUNNABLE_YET.iter().for_each(|k| {
188            obj.remove(*k);
189        });
190    }
191    Some(policy)
192}
193
194/// `base` with `top` laid over it, key by key, and `caps` key by key.
195fn overlay_policy(base: Option<&Value>, top: Option<&Value>) -> Value {
196    let mut out = base.and_then(Value::as_object).cloned().unwrap_or_default();
197    for (key, value) in top.and_then(Value::as_object).into_iter().flatten() {
198        match (key.as_str(), out.get(key).and_then(Value::as_object), value.as_object()) {
199            ("caps", Some(have), Some(over)) => {
200                let mut caps = have.clone();
201                caps.extend(over.iter().map(|(k, v)| (k.clone(), v.clone())));
202                out.insert(key.clone(), Value::Object(caps));
203            }
204            _ => {
205                out.insert(key.clone(), value.clone());
206            }
207        }
208    }
209    Value::Object(out)
210}
211
212// ── The Jobs tab's view of a pin ────────────────────────────────────────────
213
214/// A newer version of a job's template, installed.
215#[derive(Debug, Clone, PartialEq, Serialize, ts_rs::TS)]
216#[ts(export, export_to = "../../../frontend/types/rpc/")]
217pub struct TemplateUpdateView {
218    pub version: String,
219    /// The operator approved it: accepting is possible. If not, the tab
220    /// sends them to approve it first.
221    pub approved: bool,
222}
223
224/// The template a job was made from, as the tab's row shows it.
225#[derive(Debug, Clone, PartialEq, Serialize, ts_rs::TS)]
226#[ts(export, export_to = "../../../frontend/types/rpc/")]
227pub struct TemplatePinView {
228    pub id: String,
229    pub version: String,
230    pub update: Option<TemplateUpdateView>,
231}
232
233/// What the installed template is, for the pins that name it.
234pub type Latest = std::collections::HashMap<String, Option<(String, String, bool)>>;
235
236/// `pin` as the row shows it. `latest` remembers each template read, so a
237/// list of jobs made from one reads it once.
238pub fn pin_view(pin: &TemplateRef, latest: &mut Latest) -> TemplatePinView {
239    let newest = latest
240        .entry(pin.id.clone())
241        .or_insert_with(|| {
242            let (info, _) = jt::service()?.get(&pin.id)?;
243            Some((info.manifest?.version, info.hash, info.state == JobTemplateState::Approved))
244        })
245        .clone();
246    let update = newest
247        .filter(|(version, hash, _)| *version != pin.version || *hash != pin.hash)
248        .map(|(version, _, approved)| TemplateUpdateView { version, approved });
249    TemplatePinView { id: pin.id.clone(), version: pin.version.clone(), update }
250}
251
252// ── The update diff ─────────────────────────────────────────────────────────
253
254/// What `jobs.templates.update_diff` says about a job's template.
255#[derive(Debug, Clone, PartialEq, Serialize, ts_rs::TS)]
256#[serde(rename_all = "snake_case")]
257#[ts(export, export_to = "../../../frontend/types/rpc/")]
258pub enum UpdateStatus {
259    /// The job isn't made from a template, or is at the template's version.
260    None,
261    /// A newer version is installed and approved: the diff is what accepting does.
262    Available,
263    /// A newer version is installed, but the operator hasn't approved it.
264    NeedsApproval,
265    /// The template is gone or invalid, so there is nothing to update to.
266    Unavailable,
267}
268
269/// A text before and after.
270#[derive(Debug, Clone, PartialEq, Serialize, ts_rs::TS)]
271#[ts(export, export_to = "../../../frontend/types/rpc/")]
272pub struct TextChange {
273    pub before: String,
274    pub after: String,
275}
276
277/// A list's difference.
278#[derive(Debug, Clone, Default, PartialEq, Serialize, ts_rs::TS)]
279#[ts(export, export_to = "../../../frontend/types/rpc/")]
280pub struct ListChange {
281    pub added: Vec<String>,
282    pub removed: Vec<String>,
283}
284
285impl ListChange {
286    fn between(before: &[String], after: &[String]) -> Option<ListChange> {
287        let added: Vec<String> = after.iter().filter(|a| !before.contains(a)).cloned().collect();
288        let removed: Vec<String> = before.iter().filter(|b| !after.contains(b)).cloned().collect();
289        (!added.is_empty() || !removed.is_empty()).then_some(ListChange { added, removed })
290    }
291}
292
293/// One policy setting that accepting the update changes.
294#[derive(Debug, Clone, PartialEq, Serialize, ts_rs::TS)]
295#[ts(export, export_to = "../../../frontend/types/rpc/")]
296pub struct PolicyChange {
297    /// `timeout_minutes`, `caps.run_usd`…
298    pub field: String,
299    /// The job's value now, in words (`—` when it has none).
300    pub before: String,
301    pub after: String,
302}
303
304#[derive(Debug, Clone, PartialEq, Serialize, ts_rs::TS)]
305#[ts(export, export_to = "../../../frontend/types/rpc/")]
306pub struct TemplateUpdateDiff {
307    pub job_id: String,
308    pub template_id: String,
309    pub status: UpdateStatus,
310    /// Why there is no update to accept, in words.
311    pub reason: Option<String>,
312    pub from_version: String,
313    pub to_version: String,
314    /// What the update's pin would be: the content the operator sees.
315    pub to_hash: String,
316    pub brief: Option<TextChange>,
317    pub outputs: Option<ListChange>,
318    pub secrets: Option<ListChange>,
319    pub policy: Vec<PolicyChange>,
320    /// The new version can't take the job's parameters as they are.
321    pub params_error: Option<String>,
322}
323
324impl TemplateUpdateDiff {
325    fn without_update(job: &JobDefinition, status: UpdateStatus, reason: Option<String>) -> Self {
326        let pin = job.template.clone().unwrap_or(TemplateRef { id: String::new(), version: String::new(), hash: String::new() });
327        TemplateUpdateDiff {
328            job_id: job.id.clone(),
329            template_id: pin.id,
330            status,
331            reason,
332            from_version: pin.version.clone(),
333            to_version: pin.version,
334            to_hash: String::new(),
335            brief: None,
336            outputs: None,
337            secrets: None,
338            policy: Vec::new(),
339            params_error: None,
340        }
341    }
342}
343
344fn show(v: Option<&Value>) -> String {
345    match v {
346        None | Some(Value::Null) => "—".to_string(),
347        Some(Value::String(s)) => s.clone(),
348        Some(Value::Number(n)) => match n.as_f64() {
349            Some(f) if f.fract() == 0.0 && f.abs() < 1e15 => format!("{}", f as i64),
350            _ => n.to_string(),
351        },
352        Some(other) => other.to_string(),
353    }
354}
355
356/// Equal as settings: `1` and `1.0` are the same figure.
357fn same(a: Option<&Value>, b: Option<&Value>) -> bool {
358    match (a, b) {
359        (Some(Value::Number(x)), Some(Value::Number(y))) => x.as_f64() == y.as_f64(),
360        _ => a == b,
361    }
362}
363
364/// The settings of `after` that differ from `before`'s, caps one by one.
365fn policy_changes(before: &Value, after: &Value) -> Vec<PolicyChange> {
366    let mut out = Vec::new();
367    let mut keys: Vec<&String> = after.as_object().into_iter().flat_map(|m| m.keys()).collect();
368    keys.sort();
369    for key in keys {
370        let (b, a) = (before.get(key), after.get(key));
371        if same(b, a) {
372            continue;
373        }
374        if key == "caps" {
375            let caps = |v: Option<&Value>| v.and_then(Value::as_object).cloned().unwrap_or_default();
376            let (bc, ac) = (caps(b), caps(a));
377            let mut names: Vec<&String> = ac.keys().collect();
378            names.sort();
379            for name in names.into_iter().filter(|n| !same(bc.get(*n), ac.get(*n))) {
380                out.push(PolicyChange { field: format!("caps.{name}"), before: show(bc.get(name)), after: show(ac.get(name)) });
381            }
382            continue;
383        }
384        out.push(PolicyChange { field: key.clone(), before: show(b), after: show(a) });
385    }
386    out
387}
388
389/// Compare `job`'s pinned template with the one installed now, as a job
390/// edit that accepts it would make it.
391pub fn update_diff(job: &JobDefinition) -> TemplateUpdateDiff {
392    match service() {
393        Ok(svc) => update_diff_with(job, svc),
394        Err(e) => TemplateUpdateDiff::without_update(job, UpdateStatus::Unavailable, Some(e)),
395    }
396}
397
398pub(crate) fn update_diff_with(job: &JobDefinition, svc: &JobTemplates) -> TemplateUpdateDiff {
399    let Some(pin) = &job.template else { return TemplateUpdateDiff::without_update(job, UpdateStatus::None, None) };
400    let Some((info, _)) = svc.get(&pin.id) else {
401        let why = format!("{} isn't installed any more", pin.id);
402        return TemplateUpdateDiff::without_update(job, UpdateStatus::Unavailable, Some(why));
403    };
404    let Some(manifest) = info.manifest.clone() else {
405        let why = info.error.unwrap_or_else(|| format!("{} isn't a valid template", pin.id));
406        return TemplateUpdateDiff::without_update(job, UpdateStatus::Unavailable, Some(why));
407    };
408    if manifest.version == pin.version && info.hash == pin.hash {
409        return TemplateUpdateDiff::without_update(job, UpdateStatus::None, None);
410    }
411    let mut diff = TemplateUpdateDiff::without_update(job, UpdateStatus::Available, None);
412    diff.to_version = manifest.version.clone();
413    diff.to_hash = info.hash.clone();
414    if info.state != JobTemplateState::Approved {
415        diff.status = UpdateStatus::NeedsApproval;
416        diff.reason = Some(format!("{} {} hasn't been approved yet: approve it to update this job", pin.id, manifest.version));
417        return diff;
418    }
419    // What accepting does: the same edit `apply` makes.
420    let mut after = serde_json::to_value(job).unwrap_or_default();
421    after["template"] = json!({ "id": pin.id, "version": manifest.version, "hash": info.hash });
422    match apply_with(&mut after, job.template.as_ref(), svc) {
423        Err(e) => diff.params_error = Some(e),
424        Ok(()) => {
425            let new_brief = brief_of(&after);
426            let old_brief = brief_of(&serde_json::to_value(job).unwrap_or_default());
427            if old_brief != new_brief {
428                diff.brief = Some(TextChange { before: old_brief, after: new_brief });
429            }
430            let list = |v: &Value, key: &str, pick: fn(&Value) -> Option<String>| -> Vec<String> {
431                v.get(key).and_then(Value::as_array).into_iter().flatten().filter_map(pick).collect()
432            };
433            let name = |s: &Value| s.get("name").and_then(Value::as_str).map(str::to_string);
434            let plain = |s: &Value| s.as_str().map(str::to_string);
435            diff.outputs = ListChange::between(&job.outputs, &list(&after, "outputs", plain));
436            let old_secrets: Vec<String> = job.secrets.iter().map(|s| s.name.clone()).collect();
437            diff.secrets = ListChange::between(&old_secrets, &list(&after, "secrets", name));
438            let old_policy = serde_json::to_value(&job.policy).unwrap_or_default();
439            diff.policy = policy_changes(&old_policy, after.get("policy").unwrap_or(&Value::Null));
440        }
441    }
442    diff
443}
444
445/// The text an action carries: a task's payload, else the brief.
446pub fn brief_of(def: &Value) -> String {
447    let action = def.get("action").unwrap_or(&Value::Null);
448    let key = if text(action, "kind") == "task" { "payload" } else { "brief" };
449    text(action, key).to_string()
450}
451
452#[cfg(test)]
453#[path = "from_template_tests.rs"]
454mod tests;