1pub 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
41pub const BUILTIN_PUBLISHER: &str = "agentmux";
44
45#[derive(Clone, Copy)]
47pub struct Builtin {
48 pub id: &'static str,
49 pub files: &'static [(&'static str, &'static [u8])],
50}
51
52macro_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
65macro_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
79pub 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
91fn 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
97pub 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 Changed,
128 Invalid,
129}
130
131#[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 pub hash: String,
141 pub manifest: Option<JobTemplateManifest>,
142 #[serde(default, skip_serializing_if = "Option::is_none")]
144 #[ts(optional)]
145 pub drone: Option<graph::DroneSummary>,
146 #[serde(default, skip_serializing_if = "Option::is_none")]
148 #[ts(optional)]
149 pub reporter: Option<cloud::ReporterNote>,
150 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#[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 pub graph: Option<crate::backend::storage::drone_types::DroneGraph>,
176 pub approved_at_ms: i64,
178}
179
180impl ApprovedTemplate {
181 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
187struct 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
208pub struct JobTemplates {
211 pub templates_dir: PathBuf,
212 approvals_path: PathBuf,
213 pins_path: PathBuf,
214 catalogs_path: PathBuf,
215 builtins: &'static [Builtin],
216 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
234pub fn templates_dir() -> PathBuf {
236 wp::widgets_dir().with_file_name("job-templates")
237}
238
239pub 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 #[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 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 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 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 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 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 pub fn resolve_approved(&self, id: &str, version: &str) -> Result<ApprovedTemplate, String> {
426 self.approved(id, Some(version))
427 }
428
429 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 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 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 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 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 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 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;