Skip to main content

agentmux_srv_core/backend/jobs/
definition.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4//! The job definition (docs/specs/SPEC_JOBS_AND_TEMPLATES_2026_10_24.md
5//! §5.1): a trigger, an action, a policy and an owner, as JSON. Published as
6//! `schema/agentmux-job.v1.schema.json`; `definition_tests.rs` pins the two
7//! together.
8//!
9//! [`JobDefinition::parse`] is the strict reading, for definitions a caller
10//! sends: unknown fields are refused, and so are the kinds reserved for later
11//! phases (§6): any `policy.approval` but `none`. A stored row is read leniently
12//! (`storage::cron`), so a newer build's extra field doesn't lose the row.
13
14use serde::{Deserialize, Serialize};
15use serde_json::{Map, Value};
16
17use crate::backend::cron::schedule::{JobSchedule, DEFAULT_TZ};
18use crate::backend::storage::cron::CronJob;
19
20/// The only `jobVersion` this build reads.
21pub const JOB_VERSION: u32 = 1;
22
23/// The shortest interval between two fires of an unattended agent action
24/// (§5.1 "Triggers"), checked when a trigger or action is set.
25pub const MIN_UNATTENDED_INTERVAL_SECS: i64 = 15 * 60;
26
27/// The shortest `every` interval for any job.
28pub const MIN_EVERY_SECS: i64 = 60;
29
30/// What a kind reserved for a later phase answers (§6).
31pub const LATER: &str = "available in a later version";
32
33/// Trigger kinds (`trigger.kind`).
34pub mod trigger_kind {
35    pub const CRON: &str = "cron";
36    pub const EVERY: &str = "every";
37    pub const ONCE: &str = "once";
38    pub const MANUAL: &str = "manual";
39    /// Something that happened on this computer starts a drone run (Drone real-world jobs spec §3.2).
40    pub const EVENT: &str = "event";
41    #[cfg(test)]
42    pub const ALL: [&str; 5] = [CRON, EVERY, ONCE, MANUAL, EVENT];
43}
44
45/// The sources an `event` trigger may name (Drone real-world jobs spec §3.2).
46pub mod event_source {
47    /// Something inside AgentMux happened (an agent's turn ended, a job finished, a task changed).
48    pub const APP_EVENT: &str = "app_event";
49    /// A path in a workspace changed.
50    pub const FILE_WATCH: &str = "file_watch";
51    /// A POST arrived on this computer's loopback hook address.
52    pub const WEBHOOK_LOCAL: &str = "webhook_local";
53    /// AgentMux's own state is asked every so often and each new item starts a run.
54    pub const POLL: &str = "poll";
55    /// A job it watches has not had a good run lately (a dead man's switch).
56    pub const EXPECT: &str = "expect";
57    pub const ALL: [&str; 5] = [APP_EVENT, FILE_WATCH, WEBHOOK_LOCAL, POLL, EXPECT];
58}
59
60/// The most entries an event trigger's filter holds, and the longest a filter key or text value may be.
61pub const MAX_EVENT_FILTER: usize = 8;
62pub const MAX_EVENT_FILTER_TEXT: usize = 200;
63/// The longest an event's run may be held back by `delay`: a week.
64pub const MAX_EVENT_DELAY_MINUTES: u32 = 7 * 24 * 60;
65/// How many runs an event job starts in an hour when its trigger does not say.
66pub const DEFAULT_EVENT_RATE_PER_HOUR: u32 = 30;
67pub const MAX_EVENT_RATE_PER_HOUR: u32 = 1000;
68
69/// Action kinds (`action.kind`).
70pub mod action_kind {
71    pub const MESSAGE: &str = "message";
72    pub const TASK: &str = "task";
73    pub const SPAWN: &str = "spawn";
74    /// Reserved, P4.
75    pub const DRONE: &str = "drone";
76    #[cfg(test)]
77    pub const ALL: [&str; 4] = [MESSAGE, TASK, SPAWN, DRONE];
78}
79
80/// `policy.results` values.
81pub const RESULTS: [&str; 2] = ["ledger", "task_on_failure"];
82
83#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
84pub struct JobDefinition {
85    #[serde(rename = "jobVersion")]
86    pub job_version: u32,
87    #[serde(default)]
88    pub id: String,
89    pub name: String,
90    /// The owning agent's UID.
91    #[serde(default)]
92    pub owner: String,
93    /// An agent UID, or `operator`. Set by srv from the caller, never taken
94    /// from the request.
95    #[serde(default)]
96    pub created_by: String,
97    #[serde(default, skip_serializing_if = "Option::is_none")]
98    pub template: Option<TemplateRef>,
99    #[serde(default)]
100    pub params: Map<String, Value>,
101    pub trigger: Trigger,
102    pub action: Action,
103    #[serde(default)]
104    pub policy: Policy,
105    #[serde(default)]
106    pub outputs: Vec<String>,
107    #[serde(default)]
108    pub secrets: Vec<SecretRef>,
109    #[serde(default = "yes")]
110    pub enabled: bool,
111}
112
113fn yes() -> bool {
114    true
115}
116
117#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
118#[serde(tag = "kind", rename_all = "snake_case")]
119pub enum Trigger {
120    Cron {
121        cron: String,
122        #[serde(default = "default_tz")]
123        tz: String,
124    },
125    Every { seconds: i64 },
126    /// ms epoch.
127    Once { at: i64 },
128    Manual,
129    /// A source's event: what fires, and a small filter on it (each source says which keys it reads).
130    Event(EventTrigger),
131}
132
133/// What an `event` trigger waits for: the source, and a filter of plain values (text, numbers, true or false) the
134/// source matches an event against. A filter value is never an expression and never read as one.
135#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
136pub struct EventTrigger {
137    pub source: String,
138    #[serde(default)]
139    pub filter: Map<String, Value>,
140    /// Minutes between the event and the run: the run is a `scheduled` row due at event time + delay, so a restart
141    /// does not lose it. 0 starts the run at once.
142    #[serde(default, skip_serializing_if = "is_zero")]
143    pub delay: u32,
144    /// The most runs the trigger starts in any hour: a stuck source or a loop of events cannot run away. The events
145    /// beyond it are one collapsed `skipped (rate)` row, and the first raises the cap alert.
146    #[serde(default = "default_rate", skip_serializing_if = "is_default_rate")]
147    pub max_per_hour: u32,
148}
149
150fn default_rate() -> u32 {
151    DEFAULT_EVENT_RATE_PER_HOUR
152}
153
154fn is_default_rate(n: &u32) -> bool {
155    *n == DEFAULT_EVENT_RATE_PER_HOUR
156}
157
158fn is_zero(n: &u32) -> bool {
159    *n == 0
160}
161
162impl EventTrigger {
163    /// The source is one this build has, and the filter is small and plain.
164    pub fn validate(&self) -> Result<(), String> {
165        if !event_source::ALL.contains(&self.source.as_str()) {
166            return Err(format!("trigger: event source {:?} is not one of {}", self.source, event_source::ALL.join(", ")));
167        }
168        if self.delay > MAX_EVENT_DELAY_MINUTES {
169            return Err(format!("trigger: delay is at most {MAX_EVENT_DELAY_MINUTES} minutes (a week)"));
170        }
171        if !(1..=MAX_EVENT_RATE_PER_HOUR).contains(&self.max_per_hour) {
172            return Err(format!("trigger: max_per_hour is 1 to {MAX_EVENT_RATE_PER_HOUR}"));
173        }
174        if self.filter.len() > MAX_EVENT_FILTER {
175            return Err(format!("trigger: an event filter has at most {MAX_EVENT_FILTER} entries"));
176        }
177        for (key, value) in &self.filter {
178            if key.is_empty() || key.chars().count() > MAX_EVENT_FILTER_TEXT {
179                return Err(format!("trigger: an event filter key is 1 to {MAX_EVENT_FILTER_TEXT} characters"));
180            }
181            let plain = match value {
182                Value::String(text) => text.chars().count() <= MAX_EVENT_FILTER_TEXT,
183                Value::Number(_) | Value::Bool(_) => true,
184                _ => false,
185            };
186            if !plain {
187                return Err(format!("trigger: event filter {key:?} is text of at most {MAX_EVENT_FILTER_TEXT} characters, a number, or true or false"));
188            }
189        }
190        if self.source == event_source::APP_EVENT {
191            super::app_events::validate_filter(&self.filter)?;
192        }
193        if self.source == event_source::FILE_WATCH {
194            super::file_watch::validate_filter(&self.filter)?;
195        }
196        if self.source == event_source::WEBHOOK_LOCAL {
197            super::webhook_local::validate_filter(&self.filter)?;
198        }
199        if self.source == event_source::POLL {
200            super::poll::validate_filter(&self.filter)?;
201        }
202        if self.source == event_source::EXPECT {
203            super::expect::validate_filter(&self.filter)?;
204        }
205        Ok(())
206    }
207}
208
209impl Trigger {
210    pub fn kind(&self) -> &'static str {
211        match self {
212            Trigger::Cron { .. } => trigger_kind::CRON,
213            Trigger::Every { .. } => trigger_kind::EVERY,
214            Trigger::Once { .. } => trigger_kind::ONCE,
215            Trigger::Manual => trigger_kind::MANUAL,
216            Trigger::Event(_) => trigger_kind::EVENT,
217        }
218    }
219}
220
221fn default_tz() -> String {
222    DEFAULT_TZ.to_string()
223}
224
225#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
226#[serde(tag = "kind", rename_all = "snake_case")]
227pub enum Action {
228    /// `to` is an agent UID, or a name for a job created by name.
229    Message { to: String, brief: String },
230    Task {
231        title: String,
232        #[serde(default)]
233        payload: String,
234        #[serde(default)]
235        target: String,
236    },
237    Spawn {
238        leader: String,
239        brief: String,
240        #[serde(default)]
241        model: String,
242        #[serde(default)]
243        account: String,
244        #[serde(default)]
245        keep_worker: bool,
246    },
247    /// Runs the Drone `drone_id`: the run's input is what fired the job
248    /// (`{{trigger.*}}`).
249    Drone {
250        #[serde(default)]
251        drone_id: String,
252    },
253}
254
255impl Action {
256    pub fn kind(&self) -> &'static str {
257        match self {
258            Action::Message { .. } => action_kind::MESSAGE,
259            Action::Task { .. } => action_kind::TASK,
260            Action::Spawn { .. } => action_kind::SPAWN,
261            Action::Drone { .. } => action_kind::DRONE,
262        }
263    }
264
265    /// Whether a run of it is an agent working unattended: a message starts
266    /// a turn, a spawn starts a worker, a drone can run Agent blocks. Filing a
267    /// task starts nothing.
268    pub fn starts_an_agent(&self) -> bool {
269        matches!(self, Action::Message { .. } | Action::Spawn { .. } | Action::Drone { .. })
270    }
271}
272
273#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
274#[serde(rename_all = "snake_case")]
275pub enum Overlap {
276    #[default]
277    Skip,
278    BufferOne,
279    CancelOther,
280}
281
282#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
283#[serde(rename_all = "snake_case")]
284pub enum CatchUp {
285    #[default]
286    Skip,
287    Latest,
288}
289
290impl CatchUp {
291    pub fn as_str(self) -> &'static str {
292        match self {
293            CatchUp::Skip => super::CATCH_UP_SKIP,
294            CatchUp::Latest => super::CATCH_UP_LATEST,
295        }
296    }
297
298    pub fn from_column(s: &str) -> Self {
299        if s == super::CATCH_UP_LATEST { CatchUp::Latest } else { CatchUp::Skip }
300    }
301}
302
303#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
304pub struct Policy {
305    #[serde(default)]
306    pub overlap: Overlap,
307    #[serde(default)]
308    pub catch_up: CatchUp,
309    #[serde(default, skip_serializing_if = "Option::is_none")]
310    pub timeout_minutes: Option<u32>,
311    /// Retries for infrastructure failures only, at most 3.
312    #[serde(default)]
313    pub retries: u32,
314    #[serde(default, skip_serializing_if = "Option::is_none")]
315    pub max_turns: Option<u32>,
316    #[serde(default, skip_serializing_if = "Option::is_none")]
317    pub group: Option<String>,
318    #[serde(default, skip_serializing_if = "Option::is_none")]
319    pub caps: Option<Caps>,
320    /// `none` only, until P4.
321    #[serde(default = "approval_none")]
322    pub approval: String,
323    #[serde(default = "default_results")]
324    pub results: Vec<String>,
325}
326
327fn approval_none() -> String {
328    "none".to_string()
329}
330
331fn default_results() -> Vec<String> {
332    RESULTS.iter().map(|s| s.to_string()).collect()
333}
334
335impl Default for Policy {
336    fn default() -> Self {
337        Policy {
338            overlap: Overlap::default(),
339            catch_up: CatchUp::default(),
340            timeout_minutes: None,
341            retries: 0,
342            max_turns: None,
343            group: None,
344            caps: None,
345            approval: approval_none(),
346            results: default_results(),
347        }
348    }
349}
350
351#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
352pub struct Caps {
353    #[serde(default, skip_serializing_if = "Option::is_none")]
354    pub run_usd: Option<f64>,
355    #[serde(default, skip_serializing_if = "Option::is_none")]
356    pub day_usd: Option<f64>,
357    #[serde(default, skip_serializing_if = "Option::is_none")]
358    pub messages_per_day: Option<u32>,
359}
360
361#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
362pub struct TemplateRef {
363    pub id: String,
364    pub version: String,
365    #[serde(default)]
366    pub hash: String,
367}
368
369/// A secret the job's runs use, by Vault entry: never a value (§7).
370#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
371pub struct SecretRef {
372    pub name: String,
373    pub vault: String,
374}
375
376/// The fields each object may have, for [`JobDefinition::parse`].
377const TOP_KEYS: &[&str] = &[
378    "jobVersion", "id", "name", "owner", "created_by", "template", "params", "trigger", "action", "policy", "outputs",
379    "secrets", "enabled",
380];
381const POLICY_KEYS: &[&str] =
382    &["overlap", "catch_up", "timeout_minutes", "retries", "max_turns", "group", "caps", "approval", "results"];
383const CAPS_KEYS: &[&str] = &["run_usd", "day_usd", "messages_per_day"];
384const TEMPLATE_KEYS: &[&str] = &["id", "version", "hash"];
385const SECRET_KEYS: &[&str] = &["name", "vault"];
386
387fn trigger_keys(kind: &str) -> &'static [&'static str] {
388    match kind {
389        trigger_kind::CRON => &["kind", "cron", "tz"],
390        trigger_kind::EVERY => &["kind", "seconds"],
391        trigger_kind::ONCE => &["kind", "at"],
392        trigger_kind::EVENT => &["kind", "source", "filter", "delay", "max_per_hour"],
393        _ => &["kind"],
394    }
395}
396
397fn action_keys(kind: &str) -> &'static [&'static str] {
398    match kind {
399        action_kind::MESSAGE => &["kind", "to", "brief"],
400        action_kind::TASK => &["kind", "title", "payload", "target"],
401        action_kind::SPAWN => &["kind", "leader", "brief", "model", "account", "keep_worker"],
402        action_kind::DRONE => &["kind", "drone_id"],
403        _ => &["kind"],
404    }
405}
406
407/// Refuse a field `obj` may not have, naming it with its place (`at`).
408fn known_keys(obj: Option<&Value>, allowed: &[&str], at: &str) -> Result<(), String> {
409    let Some(Value::Object(map)) = obj else { return Ok(()) };
410    match map.keys().find(|k| !allowed.contains(&k.as_str())) {
411        Some(k) => Err(format!("unknown field {at}{k}")),
412        None => Ok(()),
413    }
414}
415
416/// How [`JobDefinition::validate`] reads the definition.
417#[derive(Debug, Clone, Copy)]
418pub struct Check {
419    /// The trigger or the action is being set now (a create, or an edit
420    /// that changes either): the minimum interval applies and a `once` time
421    /// must be ahead. A job kept as it was, a migrated one-minute job
422    /// included, isn't refused for them.
423    pub fresh: bool,
424    pub now_ms: i64,
425}
426
427impl JobDefinition {
428    /// Read a definition a caller sent: refuse unknown fields and the kinds
429    /// reserved for later, then [`Self::validate`] it.
430    pub fn parse(value: &Value, check: Check) -> Result<JobDefinition, String> {
431        if !value.is_object() {
432            return Err("a job definition is a JSON object".to_string());
433        }
434        known_keys(Some(value), TOP_KEYS, "")?;
435        let kind = |field: &str| value.get(field).and_then(|v| v.get("kind")).and_then(Value::as_str).unwrap_or("");
436        let (trigger, action) = (kind("trigger"), kind("action"));
437        known_keys(value.get("trigger"), trigger_keys(trigger), "trigger.")?;
438        known_keys(value.get("action"), action_keys(action), "action.")?;
439        known_keys(value.get("policy"), POLICY_KEYS, "policy.")?;
440        known_keys(value.get("policy").and_then(|p| p.get("caps")), CAPS_KEYS, "policy.caps.")?;
441        known_keys(value.get("template"), TEMPLATE_KEYS, "template.")?;
442        for s in value.get("secrets").and_then(Value::as_array).into_iter().flatten() {
443            known_keys(Some(s), SECRET_KEYS, "secrets[].")?;
444        }
445        let def: JobDefinition = serde_json::from_value(value.clone()).map_err(|e| format!("invalid job definition: {e}"))?;
446        def.validate(check)?;
447        Ok(def)
448    }
449
450    /// Check what the types can't: values, bounds and the reserved kinds.
451    pub fn validate(&self, check: Check) -> Result<(), String> {
452        if self.job_version != JOB_VERSION {
453            return Err(format!("jobVersion {} isn't supported (use {JOB_VERSION})", self.job_version));
454        }
455        let name = self.name.trim();
456        if name.is_empty() || name.chars().count() > 200 {
457            return Err("name is required, at most 200 characters".to_string());
458        }
459        if let Some(t) = &self.template {
460            if t.id.trim().is_empty() || t.version.trim().is_empty() {
461                return Err("template: id and version are required".to_string());
462            }
463        }
464        if serde_json::to_string(&self.params).map_or(0, |s| s.len()) > 16 * 1024 {
465            return Err("params are at most 16 KB".to_string());
466        }
467        self.validate_trigger(check)?;
468        self.validate_action()?;
469        self.policy.validate()?;
470        self.validate_drone_policy()?;
471        validate_outputs(&self.outputs)?;
472        validate_secrets(&self.secrets)
473    }
474
475    /// A Drone run is not run again yet, so a drone job can't ask for
476    /// retries. A timeout or `cancel_other` stops the run through the engine's
477    /// cancel (`stop_run`). Its spending is held by admission, as an agent
478    /// job's is (`policy::starts_an_agent`): a run that would pass the day's
479    /// cap does not start.
480    fn validate_drone_policy(&self) -> Result<(), String> {
481        if !matches!(self.action, Action::Drone { .. }) {
482            return Ok(());
483        }
484        let p = &self.policy;
485        if p.retries > 0 {
486            return Err(format!("policy.retries: a failed drone run is not run again yet; leave retries at 0 and run it again by hand (retries are {LATER})"));
487        }
488        Ok(())
489    }
490
491    fn validate_trigger(&self, check: Check) -> Result<(), String> {
492        let interval = match &self.trigger {
493            Trigger::Cron { cron, tz } => {
494                let schedule = JobSchedule::cron(cron, tz).map_err(|e| format!("trigger: invalid cron '{cron}': {e}"))?;
495                schedule.min_gap_secs(check.now_ms, 500)
496            }
497            &Trigger::Every { seconds } => {
498                if seconds < MIN_EVERY_SECS {
499                    return Err(format!("trigger: every runs at most once a minute (seconds >= {MIN_EVERY_SECS})"));
500                }
501                Some(seconds)
502            }
503            &Trigger::Once { at } => {
504                if at <= 0 || (check.fresh && at <= check.now_ms) {
505                    return Err("trigger: once needs a time ahead, `at` in ms epoch".to_string());
506                }
507                None
508            }
509            Trigger::Manual => None,
510            Trigger::Event(event) => {
511                event.validate()?;
512                if !matches!(self.action, Action::Drone { .. }) {
513                    return Err("trigger: an event starts a drone run with the event as its input, so the action is a drone".to_string());
514                }
515                None
516            }
517        };
518        match interval {
519            Some(secs) if check.fresh && self.action.starts_an_agent() && secs < MIN_UNATTENDED_INTERVAL_SECS => Err(format!(
520                "trigger: an unattended agent job runs at most every {} minutes; this one would run {} apart",
521                MIN_UNATTENDED_INTERVAL_SECS / 60,
522                span(secs)
523            )),
524            _ => Ok(()),
525        }
526    }
527
528    fn validate_action(&self) -> Result<(), String> {
529        let blank = |s: &str| s.trim().is_empty();
530        match &self.action {
531            Action::Message { to, brief } if blank(to) || blank(brief) => Err("action: message needs to and brief".to_string()),
532            Action::Task { title, .. } if blank(title) => Err("action: task needs a title".to_string()),
533            Action::Spawn { leader, brief, .. } if blank(leader) || blank(brief) => {
534                Err("action: spawn needs leader and brief".to_string())
535            }
536            Action::Drone { drone_id } if blank(drone_id) => Err("action: drone needs a drone_id".to_string()),
537            _ => Ok(()),
538        }
539    }
540
541    /// The definition of a stored job.
542    pub fn from_job(job: &CronJob) -> JobDefinition {
543        let trigger = match job.trigger_kind.as_str() {
544            trigger_kind::EVERY => Trigger::Every { seconds: job.every_secs.unwrap_or(0) },
545            trigger_kind::ONCE => Trigger::Once { at: job.once_at_ms.unwrap_or(0) },
546            trigger_kind::MANUAL => Trigger::Manual,
547            trigger_kind::EVENT => match serde_json::from_value::<EventTrigger>(job.trigger_event.clone()) {
548                Ok(event) => Trigger::Event(event),
549                // A row this build can't read as an event trigger runs nothing: manual is the trigger that fires only when asked.
550                Err(_) => Trigger::Manual,
551            },
552            _ => Trigger::Cron { cron: job.expression.clone(), tz: if job.tz.is_empty() { default_tz() } else { job.tz.clone() } },
553        };
554        let message = || Action::Message {
555            to: if job.target_uid.is_empty() { job.target.clone() } else { job.target_uid.clone() },
556            brief: job.prompt.clone(),
557        };
558        let action = match job.action_kind.as_str() {
559            "" | action_kind::MESSAGE => message(),
560            _ => serde_json::from_value(job.action.clone()).unwrap_or_else(|_| message()),
561        };
562        let mut policy = job.policy.clone();
563        policy.catch_up = CatchUp::from_column(&job.catch_up);
564        JobDefinition {
565            job_version: JOB_VERSION,
566            id: job.id.clone(),
567            name: job.name.clone(),
568            owner: job.owner_uid().to_string(),
569            created_by: if job.created_by_uid.is_empty() { job.created_by.clone() } else { job.created_by_uid.clone() },
570            template: job.template.clone(),
571            params: job.params.clone(),
572            trigger,
573            action,
574            policy,
575            outputs: job.outputs.clone(),
576            secrets: job.secrets.clone(),
577            enabled: job.enabled,
578        }
579    }
580
581    /// Write this definition into `job`, leaving its id, creator, fires and
582    /// misses alone. A message's `to` becomes the job's target through
583    /// `target_of`: `(name, uid)`.
584    pub fn apply_to(&self, job: &mut CronJob, target_of: &dyn Fn(&str) -> (String, String)) {
585        job.name = self.name.trim().to_string();
586        job.owner = self.owner.clone();
587        job.template = self.template.clone();
588        job.params = self.params.clone();
589        job.enabled = self.enabled;
590        (job.expression, job.tz, job.every_secs, job.once_at_ms) = (String::new(), String::new(), None, None);
591        job.trigger_event = Value::Null;
592        job.trigger_kind = match &self.trigger {
593            Trigger::Cron { cron, tz } => {
594                (job.expression, job.tz) = (cron.trim().to_string(), if tz.trim().is_empty() { default_tz() } else { tz.trim().to_string() });
595                trigger_kind::CRON
596            }
597            &Trigger::Every { seconds } => {
598                job.every_secs = Some(seconds);
599                trigger_kind::EVERY
600            }
601            &Trigger::Once { at } => {
602                job.once_at_ms = Some(at);
603                trigger_kind::ONCE
604            }
605            Trigger::Manual => trigger_kind::MANUAL,
606            Trigger::Event(event) => {
607                job.trigger_event = serde_json::to_value(event).unwrap_or(Value::Null);
608                trigger_kind::EVENT
609            }
610        }
611        .to_string();
612        job.action_kind = self.action.kind().to_string();
613        match &self.action {
614            Action::Message { to, brief } => {
615                (job.target, job.target_uid) = target_of(to.trim());
616                job.prompt = brief.clone();
617                job.action = Value::Null;
618            }
619            other => {
620                (job.target, job.target_uid, job.prompt) = (String::new(), String::new(), String::new());
621                job.action = serde_json::to_value(other).unwrap_or(Value::Null);
622            }
623        }
624        job.catch_up = self.policy.catch_up.as_str().to_string();
625        job.policy = self.policy.clone();
626        job.outputs = self.outputs.clone();
627        job.secrets = self.secrets.clone();
628    }
629}
630
631impl Policy {
632    fn validate(&self) -> Result<(), String> {
633        if self.approval != "none" {
634            return Err(format!("policy.approval: only none for now; approvals are {LATER}"));
635        }
636        if self.retries > 3 {
637            return Err("policy.retries: at most 3".to_string());
638        }
639        if self.timeout_minutes.is_some_and(|t| !(1..=1440).contains(&t)) {
640            return Err("policy.timeout_minutes: 1 to 1440".to_string());
641        }
642        if self.max_turns.is_some_and(|t| !(1..=10_000).contains(&t)) {
643            return Err("policy.max_turns: 1 to 10000".to_string());
644        }
645        if let Some(group) = &self.group {
646            let ok = (1..=40).contains(&group.len())
647                && group.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
648                && !group.starts_with('-');
649            if !ok {
650                return Err("policy.group: lowercase letters, digits and -, at most 40".to_string());
651            }
652        }
653        if let Some(caps) = &self.caps {
654            if [caps.run_usd, caps.day_usd].into_iter().flatten().any(|c| !c.is_finite() || c < 0.0) {
655                return Err("policy.caps: dollar figures are 0 or more".to_string());
656            }
657        }
658        match self.results.iter().find(|r| !RESULTS.contains(&r.as_str())) {
659            Some(r) => Err(format!("policy.results: unknown '{r}' (use {})", RESULTS.join(", "))),
660            None => Ok(()),
661        }
662    }
663}
664
665/// `report_file`, `kanban_task`, `message:owner`, `pull_request`…: a word,
666/// and an optional `:qualifier`. Declared, not enforced, until P4.
667fn validate_outputs(outputs: &[String]) -> Result<(), String> {
668    if outputs.len() > 20 {
669        return Err("outputs: at most 20".to_string());
670    }
671    let word = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_lowercase() || b == b'_');
672    let qualifier = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_alphanumeric() || b"_.-".contains(&b));
673    for o in outputs {
674        let ok = match o.split_once(':') {
675            Some((w, q)) => word(w) && qualifier(q),
676            None => word(o),
677        };
678        if !ok {
679            return Err(format!("outputs: '{o}' isn't an output name (report_file, kanban_task, message:owner, …)"));
680        }
681    }
682    Ok(())
683}
684
685/// Names an environment variable can have, never `AGENTMUX_…` (srv's own,
686/// `shell_secrets.rs` refuses them too), each once, each with its Vault entry.
687fn validate_secrets(secrets: &[SecretRef]) -> Result<(), String> {
688    if secrets.len() > 20 {
689        return Err("secrets: at most 20".to_string());
690    }
691    let mut seen = std::collections::BTreeSet::new();
692    for s in secrets {
693        let ok = (1..=64).contains(&s.name.len())
694            && s.name.starts_with(|c: char| c.is_ascii_uppercase())
695            && s.name.bytes().all(|b| b.is_ascii_uppercase() || b.is_ascii_digit() || b == b'_');
696        if !ok || s.name.starts_with("AGENTMUX_") {
697            return Err(format!("secrets: '{}' isn't a usable name (A-Z, 0-9 and _, not AGENTMUX_…)", s.name));
698        }
699        if s.vault.trim().is_empty() {
700            return Err(format!("secrets: '{}' needs its Vault entry id", s.name));
701        }
702        if !seen.insert(s.name.as_str()) {
703            return Err(format!("secrets: '{}' is listed twice", s.name));
704        }
705    }
706    Ok(())
707}
708
709/// A span of seconds in words: "5 min", "40 s".
710fn span(secs: i64) -> String {
711    if secs >= 60 { format!("{} min", secs / 60) } else { format!("{secs} s") }
712}
713
714#[cfg(test)]
715#[path = "definition_tests.rs"]
716mod tests;