Skip to main content

agentmux_srv_core/backend/job_templates/
mod.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Job templates: signed data a job is made from
5//! (docs/specs/SPEC_JOBS_AND_TEMPLATES_2026_10_24.md §5.4, §5.5).
6//!
7//! A template comes compiled in (`templates/jobs/`, published by AgentMux),
8//! installed from a folder or a zip, or from a private catalog. Installed
9//! templates live in `~/.agentmux/job-templates/`, beside the widgets. Every
10//! template waits for the operator's approval, which only the host carries,
11//! like a widget's; a template that isn't approved, or changed since, can't
12//! make a job ([`JobTemplates::resolve_approved`]). Publisher keys are pinned
13//! on first approval, in `job-template-publishers.json` beside the widgets'
14//! pins. Approving a template runs nothing.
15
16pub mod catalog;
17pub mod cloud;
18pub mod graph;
19pub mod manifest;
20pub mod package;
21
22use std::collections::BTreeMap;
23use std::path::{Path, PathBuf};
24use std::sync::{Arc, Mutex, OnceLock};
25
26use serde::{Deserialize, Serialize};
27use serde_json::{Map, Value};
28
29use manifest::JobTemplateKind;
30pub use manifest::{JobTemplateManifest, RenderedBrief};
31use package::Package;
32
33use crate::backend::jobs::reporters::{Reporters, REPORTERS_FILE};
34use crate::backend::widget::packages as wp;
35use crate::backend::widget::signature::{self as sig, Pins, WidgetPublisherPin, WidgetSignatureInfo};
36
37const APPROVALS_FILE: &str = "job-template-approvals.json";
38const PUBLISHERS_FILE: &str = "job-template-publishers.json";
39const CATALOGS_FILE: &str = "job-template-catalogs.json";
40
41/// The publisher of the templates AgentMux ships; no other template may
42/// use it.
43pub const BUILTIN_PUBLISHER: &str = "agentmux";
44
45/// A template compiled into srv from `templates/jobs/<id>/` or `templates/drones/<id>/`.
46#[derive(Clone, Copy)]
47pub struct Builtin {
48    pub id: &'static str,
49    pub files: &'static [(&'static str, &'static [u8])],
50}
51
52/// A built-in template: its id, and its two files from `templates/jobs/<id>/`.
53macro_rules! builtin {
54    ($name:literal) => {
55        Builtin {
56            id: concat!("agentmux.", $name),
57            files: &[
58                ("template.json", include_bytes!(concat!("../../../../../templates/jobs/agentmux.", $name, "/template.json"))),
59                ("brief.md", include_bytes!(concat!("../../../../../templates/jobs/agentmux.", $name, "/brief.md"))),
60            ],
61        }
62    };
63}
64
65/// A built-in Drone template: its id, and its three files from `templates/drones/<id>/`.
66macro_rules! builtin_drone {
67    ($name:literal) => {
68        Builtin {
69            id: concat!("agentmux.", $name),
70            files: &[
71                ("template.json", include_bytes!(concat!("../../../../../templates/drones/agentmux.", $name, "/template.json"))),
72                ("graph.json", include_bytes!(concat!("../../../../../templates/drones/agentmux.", $name, "/graph.json"))),
73                ("README.md", include_bytes!(concat!("../../../../../templates/drones/agentmux.", $name, "/README.md"))),
74            ],
75        }
76    };
77}
78
79/// The Drone templates AgentMux ships: graphs that run on the blocks this build has, each easy to build off.
80pub static DRONE_BUILTINS: &[Builtin] = &[
81    builtin_drone!("scheduled-report"),
82    builtin_drone!("check-and-file-task"),
83    builtin_drone!("two-agent-handoff"),
84    builtin_drone!("after-upgrade-check"),
85    builtin_drone!("triage-failed-nightly"),
86    builtin_drone!("rerun-flaky-job"),
87    builtin_drone!("merged-pr-still-claimed"),
88    builtin_drone!("verify-release"),
89];
90
91/// Every template AgentMux ships: the job templates, then the Drone ones.
92fn all_builtins() -> &'static [Builtin] {
93    static ALL: OnceLock<Vec<Builtin>> = OnceLock::new();
94    ALL.get_or_init(|| BUILTINS.iter().chain(DRONE_BUILTINS).copied().collect())
95}
96
97/// The templates AgentMux ships (§5.5, §5.6). Each still needs the
98/// operator's approval once, so they see its outputs.
99pub static BUILTINS: &[Builtin] = &[
100    builtin!("weekly-report"),
101    builtin!("pr-review"),
102    builtin!("nightly-build"),
103    builtin!("daily-digest"),
104    builtin!("dependency-scan"),
105    builtin!("docs-drift"),
106    builtin!("stale-sweep"),
107    builtin!("backup-verify"),
108    builtin!("on-event"),
109    builtin!("weekly-status"),
110];
111
112#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, ts_rs::TS)]
113#[serde(rename_all = "snake_case")]
114#[ts(export, export_to = "../../../frontend/types/rpc/")]
115pub enum JobTemplateSource {
116    Builtin,
117    Installed,
118}
119
120#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, ts_rs::TS)]
121#[serde(rename_all = "snake_case")]
122#[ts(export, export_to = "../../../frontend/types/rpc/")]
123pub enum JobTemplateState {
124    Approved,
125    NeedsApproval,
126    /// Its files or its signer changed since the operator approved it.
127    Changed,
128    Invalid,
129}
130
131/// A template as the UI lists it.
132#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, ts_rs::TS)]
133#[ts(export, export_to = "../../../frontend/types/rpc/")]
134pub struct JobTemplateInfo {
135    pub id: String,
136    pub source: JobTemplateSource,
137    pub state: JobTemplateState,
138    pub error: Option<String>,
139    /// The current content hash (empty when invalid).
140    pub hash: String,
141    pub manifest: Option<JobTemplateManifest>,
142    /// A Drone template's graph, as the approval prompt shows it.
143    #[serde(default, skip_serializing_if = "Option::is_none")]
144    #[ts(optional)]
145    pub drone: Option<graph::DroneSummary>,
146    /// A cloud template's reporter, and whether approving pins it, refuses, or finds it pinned already.
147    #[serde(default, skip_serializing_if = "Option::is_none")]
148    #[ts(optional)]
149    pub reporter: Option<cloud::ReporterNote>,
150    /// Who signed it, against the pinned publishers. A built-in one is
151    /// unsigned and published by AgentMux.
152    pub signature: WidgetSignatureInfo,
153    pub folder: Option<String>,
154}
155
156#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
157struct Approval {
158    hash: String,
159    version: String,
160    signer: Option<String>,
161    source: JobTemplateSource,
162    approved_at: i64,
163}
164
165/// A template the operator approved, exactly as approved: what a job is
166/// made from. A job records its id, version and hash.
167#[derive(Debug, Clone)]
168pub struct ApprovedTemplate {
169    pub id: String,
170    pub version: String,
171    pub hash: String,
172    pub manifest: JobTemplateManifest,
173    pub brief: Option<String>,
174    /// A Drone template's graph, exactly as approved.
175    pub graph: Option<crate::backend::storage::drone_types::DroneGraph>,
176    /// When the operator approved it, in ms.
177    pub approved_at_ms: i64,
178}
179
180impl ApprovedTemplate {
181    /// Its brief with `params` filled in.
182    pub fn render(&self, params: &Map<String, Value>) -> Result<RenderedBrief, String> {
183        manifest::render(&self.manifest, self.brief.as_deref().unwrap_or(""), params)
184    }
185}
186
187/// A template found, before approval is applied.
188struct Found {
189    id: String,
190    source: JobTemplateSource,
191    dir: Option<PathBuf>,
192    package: Result<Package, String>,
193}
194
195fn read_json<T: serde::de::DeserializeOwned + Default>(path: &Path) -> T {
196    std::fs::read_to_string(path).ok().and_then(|s| serde_json::from_str(&s).ok()).unwrap_or_default()
197}
198
199fn write_json<T: Serialize>(path: &Path, value: &T) -> Result<(), String> {
200    if let Some(dir) = path.parent() {
201        std::fs::create_dir_all(dir).map_err(|e| e.to_string())?;
202    }
203    let tmp = path.with_extension("json.tmp");
204    std::fs::write(&tmp, serde_json::to_vec_pretty(value).map_err(|e| e.to_string())?).map_err(|e| e.to_string())?;
205    std::fs::rename(&tmp, path).map_err(|e| e.to_string())
206}
207
208// ── The service ─────────────────────────────────────────────────────────────
209
210pub struct JobTemplates {
211    pub templates_dir: PathBuf,
212    approvals_path: PathBuf,
213    pins_path: PathBuf,
214    catalogs_path: PathBuf,
215    builtins: &'static [Builtin],
216    /// The cloud reporters the operator pinned. Approving a cloud template pins its reporter here.
217    reporters: Arc<Reporters>,
218    inner: Mutex<Inner>,
219}
220
221#[derive(Default)]
222struct Inner {
223    approvals: BTreeMap<String, Approval>,
224    pins: Pins,
225    catalogs: Vec<catalog::Catalog>,
226}
227
228static SERVICE: OnceLock<Arc<JobTemplates>> = OnceLock::new();
229
230pub fn service() -> Option<&'static Arc<JobTemplates>> {
231    SERVICE.get()
232}
233
234/// `~/.agentmux/job-templates`, beside the widgets folder.
235pub fn templates_dir() -> PathBuf {
236    wp::widgets_dir().with_file_name("job-templates")
237}
238
239/// Start the service: this instance's approvals, pins and catalogs, from
240/// `data_dir` beside the widgets'.
241pub fn start(data_dir: &Path) {
242    let data_dir = if data_dir.as_os_str().is_empty() { super::base::get_mux_data_dir() } else { data_dir.to_path_buf() };
243    JobTemplates::new(templates_dir(), &data_dir, all_builtins()).install_global();
244}
245
246impl JobTemplates {
247    pub fn new(templates_dir: PathBuf, data_dir: &Path, builtins: &'static [Builtin]) -> Self {
248        let (approvals_path, pins_path, catalogs_path) =
249            (data_dir.join(APPROVALS_FILE), data_dir.join(PUBLISHERS_FILE), data_dir.join(CATALOGS_FILE));
250        let inner = Inner { approvals: read_json(&approvals_path), pins: sig::read_pins(&pins_path), catalogs: read_json(&catalogs_path) };
251        let reporters = Arc::new(Reporters::open(&data_dir.join(REPORTERS_FILE)));
252        Self { templates_dir, approvals_path, pins_path, catalogs_path, builtins, reporters, inner: Mutex::new(inner) }
253    }
254
255    pub fn reporters(&self) -> &Arc<Reporters> {
256        &self.reporters
257    }
258
259    pub fn install_global(self) -> &'static Arc<JobTemplates> {
260        SERVICE.get_or_init(|| Arc::new(self))
261    }
262
263    /// The process-wide service for tests, in a temp folder that lives as
264    /// long as the process; each test uses its own template ids.
265    #[cfg(any(test, feature = "test-support"))]
266    pub fn for_tests() -> &'static Arc<JobTemplates> {
267        static DIR: OnceLock<tempfile::TempDir> = OnceLock::new();
268        let dir = DIR.get_or_init(|| tempfile::tempdir().unwrap());
269        JobTemplates::new(dir.path().join("job-templates"), &dir.path().join("data"), &[]).install_global()
270    }
271
272    fn lock(&self) -> std::sync::MutexGuard<'_, Inner> {
273        self.inner.lock().unwrap_or_else(|p| p.into_inner())
274    }
275
276    /// Every template: the built-in ones, then each folder in the templates
277    /// folder that holds a `template.json`, read now.
278    fn scan(&self) -> Vec<Found> {
279        let mut out: Vec<Found> = self
280            .builtins
281            .iter()
282            .map(|b| Found {
283                id: b.id.to_string(),
284                source: JobTemplateSource::Builtin,
285                dir: None,
286                package: package::load_embedded(b.id, b.files),
287            })
288            .collect();
289        let mut installed = Vec::new();
290        for entry in std::fs::read_dir(&self.templates_dir).into_iter().flatten().flatten() {
291            let dir = entry.path();
292            if !entry.file_type().is_ok_and(|t| t.is_dir()) || !dir.join(package::TEMPLATE_FILE).exists() {
293                continue;
294            }
295            let id = entry.file_name().to_string_lossy().into_owned();
296            let package = if sig::publisher_of(&id) == BUILTIN_PUBLISHER {
297                Err(format!("the publisher {BUILTIN_PUBLISHER:?} is kept for the templates AgentMux ships"))
298            } else {
299                package::load_dir(&dir, &id)
300            };
301            installed.push(Found { id, source: JobTemplateSource::Installed, dir: Some(dir), package });
302        }
303        installed.sort_by(|a, b| a.id.cmp(&b.id));
304        out.extend(installed);
305        out
306    }
307
308    fn find(&self, id: &str) -> Option<Found> {
309        if let Some(b) = self.builtins.iter().find(|b| b.id == id) {
310            return Some(Found {
311                id: id.to_string(),
312                source: JobTemplateSource::Builtin,
313                dir: None,
314                package: package::load_embedded(b.id, b.files),
315            });
316        }
317        if !wp::valid_id(id) || sig::publisher_of(id) == BUILTIN_PUBLISHER {
318            return None;
319        }
320        let dir = self.templates_dir.join(id);
321        dir.join(package::TEMPLATE_FILE).exists().then(|| Found {
322            id: id.to_string(),
323            source: JobTemplateSource::Installed,
324            package: package::load_dir(&dir, id),
325            dir: Some(dir),
326        })
327    }
328
329    fn describe(&self, f: &Found, inner: &Inner) -> JobTemplateInfo {
330        let folder = f.dir.as_ref().map(|d| d.display().to_string());
331        let pkg = match &f.package {
332            Ok(p) => p,
333            Err(e) => {
334                return JobTemplateInfo {
335                    id: f.id.clone(),
336                    source: f.source,
337                    state: JobTemplateState::Invalid,
338                    error: Some(e.clone()),
339                    hash: String::new(),
340                    manifest: None,
341                    drone: None,
342                    reporter: None,
343                    signature: sig::describe(&f.id, None, &inner.pins),
344                    folder,
345                }
346            }
347        };
348        let state = match inner.approvals.get(&f.id) {
349            None => JobTemplateState::NeedsApproval,
350            Some(a) if a.hash != pkg.hash || a.signer != pkg.signer || a.source != f.source => JobTemplateState::Changed,
351            Some(_) => JobTemplateState::Approved,
352        };
353        JobTemplateInfo {
354            id: f.id.clone(),
355            source: f.source,
356            state,
357            error: None,
358            hash: pkg.hash.clone(),
359            manifest: Some(pkg.manifest.clone()),
360            drone: pkg.graph.as_ref().map(|g| graph::DroneSummary { credentials: graph::credentials(g, pkg.manifest.trigger.as_ref()), ..graph::summarize(g) }),
361            reporter: pkg.manifest.reporter.as_ref().filter(|_| pkg.manifest.kind == JobTemplateKind::Cloud).map(|r| cloud::ReporterNote {
362                name: r.name.clone(),
363                fingerprint: sig::fingerprint(&r.key),
364                state: self.reporters.state_of(&r.name, &r.key),
365            }),
366            signature: sig::describe(&f.id, pkg.signer.as_deref(), &inner.pins),
367            folder,
368        }
369    }
370
371    pub fn list(&self) -> Vec<JobTemplateInfo> {
372        let found = self.scan();
373        let inner = self.lock();
374        found.iter().map(|f| self.describe(f, &inner)).collect()
375    }
376
377    /// One template, and its brief when it is valid.
378    pub fn get(&self, id: &str) -> Option<(JobTemplateInfo, Option<Package>)> {
379        let f = self.find(id)?;
380        let info = self.describe(&f, &self.lock());
381        Some((info, f.package.ok()))
382    }
383
384    /// Record the operator's approval of exactly `hash`, signed by the key
385    /// whose fingerprint their prompt showed (`shown_signer`, "" for
386    /// unsigned); only the host route calls this. Fails if the template or
387    /// its signature changed since the prompt was shown.
388    pub fn approve(&self, id: &str, hash: &str, shown_signer: &str) -> Result<(), String> {
389        let f = self.find(id).ok_or("no such job template")?;
390        let pkg = f.package?;
391        if pkg.hash != hash {
392            return Err("the template changed since you were asked; review it again".to_string());
393        }
394        if pkg.signer.as_deref().map(sig::fingerprint).unwrap_or_default() != shown_signer {
395            return Err("the template's signature changed since you were asked; review it again".to_string());
396        }
397        // A cloud template's reporter is pinned with it, so its events count from the moment it is approved. A name
398        // already pinned to another key stops the approval: the operator forgets that key first.
399        if let Some(r) = pkg.manifest.reporter.as_ref().filter(|_| pkg.manifest.kind == JobTemplateKind::Cloud) {
400            self.reporters.add(&r.name, &r.key).map_err(|e| format!("the reporter can't be pinned: {e}"))?;
401        }
402        let mut inner = self.lock();
403        // The first signed template of a publisher pins it to its key; a
404        // later one signed otherwise doesn't move the pin, and shows as
405        // `key_changed` in its prompt.
406        let publisher = sig::publisher_of(id).to_string();
407        if let Some(key) = pkg.signer.clone().filter(|_| !inner.pins.contains_key(&publisher)) {
408            inner.pins.insert(publisher, key);
409            sig::write_pins(&self.pins_path, &inner.pins)?;
410        }
411        let approval = Approval {
412            hash: pkg.hash,
413            version: pkg.manifest.version,
414            signer: pkg.signer,
415            source: f.source,
416            approved_at: chrono::Utc::now().timestamp(),
417        };
418        inner.approvals.insert(id.to_string(), approval);
419        write_json(&self.approvals_path, &inner.approvals)
420    }
421
422    /// The approved template `id` at `version`, read from disk now: an
423    /// error if it isn't installed at that version, isn't approved, or
424    /// changed since the operator approved it.
425    pub fn resolve_approved(&self, id: &str, version: &str) -> Result<ApprovedTemplate, String> {
426        self.approved(id, Some(version))
427    }
428
429    /// The approved cloud template `id`, read from disk now: what the events of a cloud job are matched to. `None`
430    /// if it isn't installed, isn't a cloud template, isn't approved, or changed since the operator approved it.
431    pub fn approved_cloud(&self, id: &str) -> Option<ApprovedTemplate> {
432        self.approved(id, None).ok().filter(|t| t.manifest.kind == JobTemplateKind::Cloud)
433    }
434
435    /// Every approved cloud template, read from disk now: the cloud jobs the watchdog looks after.
436    pub fn approved_clouds(&self) -> Vec<ApprovedTemplate> {
437        let cloud = |t: &JobTemplateInfo| t.state == JobTemplateState::Approved && t.manifest.as_ref().is_some_and(|m| m.kind == JobTemplateKind::Cloud);
438        self.list().iter().filter(|t| cloud(t)).filter_map(|t| self.approved_cloud(&t.id)).collect()
439    }
440
441    fn approved(&self, id: &str, version: Option<&str>) -> Result<ApprovedTemplate, String> {
442        let f = self.find(id).ok_or_else(|| format!("no job template {id}"))?;
443        let pkg = f.package.map_err(|e| format!("{id} isn't a valid template: {e}"))?;
444        if let Some(version) = version.filter(|v| *v != pkg.manifest.version) {
445            return Err(format!("{id} is at version {}, not {version}", pkg.manifest.version));
446        }
447        let approved_at_ms = match self.lock().approvals.get(id) {
448            None => return Err(format!("{id} isn't approved: the operator approves a template before a job can use it")),
449            Some(a) if a.hash != pkg.hash || a.signer != pkg.signer || a.source != f.source => {
450                return Err(format!("{id} changed since the operator approved it; it needs their approval again"))
451            }
452            Some(a) => a.approved_at.saturating_mul(1000),
453        };
454        Ok(ApprovedTemplate {
455            approved_at_ms,
456            id: id.to_string(),
457            version: pkg.manifest.version.clone(),
458            hash: pkg.hash,
459            manifest: pkg.manifest,
460            brief: pkg.brief,
461            graph: pkg.graph,
462        })
463    }
464
465    /// Copy the template at `source` (a folder, its `template.json`, or a
466    /// `.zip`) into the templates folder, waiting for approval.
467    pub fn install(&self, source: &Path, replace: bool) -> Result<String, String> {
468        wp::install_package(&self.templates_dir, source, replace, package::TEMPLATE_FILE, |root| {
469            let raw = std::fs::read(root.join(package::TEMPLATE_FILE)).map_err(|e| format!("can't read template.json: {e}"))?;
470            let m: JobTemplateManifest = serde_json::from_slice(&raw).map_err(|e| format!("template.json: {e}"))?;
471            if sig::publisher_of(&m.id) == BUILTIN_PUBLISHER {
472                return Err(format!("the publisher {BUILTIN_PUBLISHER:?} is kept for the templates AgentMux ships"));
473            }
474            package::load_dir(root, &m.id).map(|p| p.manifest.id)
475        })
476    }
477
478    /// Delete an installed template's folder and its approval.
479    pub fn uninstall(&self, id: &str) -> Result<(), String> {
480        let f = self.find(id).ok_or("no such job template")?;
481        let dir = f.dir.ok_or("a built-in template can't be uninstalled")?;
482        std::fs::remove_dir_all(&dir).map_err(|e| format!("can't remove it: {e}"))?;
483        let mut inner = self.lock();
484        inner.approvals.remove(id);
485        write_json(&self.approvals_path, &inner.approvals)
486    }
487
488    /// The publishers pinned to a key, for Settings.
489    pub fn publishers(&self) -> Vec<WidgetPublisherPin> {
490        let inner = self.lock();
491        inner.pins.iter().map(|(publisher, key)| WidgetPublisherPin { publisher: publisher.clone(), fingerprint: sig::fingerprint(key) }).collect()
492    }
493
494    /// Forget a publisher's key (the operator's, through the host route).
495    pub fn forget_publisher(&self, publisher: &str) -> Result<(), String> {
496        let mut inner = self.lock();
497        if inner.pins.remove(publisher).is_none() {
498            return Err(format!("no key is kept for {publisher:?}"));
499        }
500        sig::write_pins(&self.pins_path, &inner.pins)
501    }
502
503    pub fn catalogs(&self) -> Vec<catalog::Catalog> {
504        self.lock().catalogs.clone()
505    }
506
507    /// Add a private catalog, or change its key (the operator's, through the
508    /// host route).
509    pub fn add_catalog(&self, url: &str, public_key: &str) -> Result<(), String> {
510        let c = catalog::Catalog::new(url, public_key)?;
511        let mut inner = self.lock();
512        inner.catalogs.retain(|x| x.url != c.url);
513        inner.catalogs.push(c);
514        write_json(&self.catalogs_path, &inner.catalogs)
515    }
516
517    pub fn remove_catalog(&self, url: &str) -> Result<(), String> {
518        let mut inner = self.lock();
519        let before = inner.catalogs.len();
520        inner.catalogs.retain(|x| x.url != url);
521        if inner.catalogs.len() == before {
522            return Err(format!("no catalog at {url}"));
523        }
524        write_json(&self.catalogs_path, &inner.catalogs)
525    }
526}
527
528#[cfg(test)]
529mod cloud_tests;
530#[cfg(test)]
531mod drone_tests;
532#[cfg(test)]
533mod starters_tests;
534#[cfg(test)]
535mod tests;