Skip to main content

agentmux_srv_core/backend/storage/
cron.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Persistent job storage: CRUD on `db_jobs`
5//! (docs/specs/SPEC_JOBS_AND_TEMPLATES_2026_10_24.md §5.1), in the same store
6//! as the `db_cron_jobs` it replaced: the shared store (`store.db`), which
7//! is per channel under isolated auth. `db_cron_jobs` stays as it was for
8//! older builds; `m0040_cron_jobs_to_db_jobs` copied its rows here, keeping
9//! their ids. See also `SPEC_CRON_LOOP_ROBUSTNESS_2026_06_25.md`.
10//!
11//! A row is a job definition (`backend::jobs::definition`) plus its runtime
12//! state (fires, misses, limits). The cron trigger and the `message` action
13//! keep the columns `db_cron_jobs` had (`expression`, `prompt`, `target`,
14//! `target_uid`), so the slug migration and older readers see the same
15//! shape; the other kinds' fields are in `action`.
16
17use rusqlite::params;
18use serde::{Deserialize, Serialize};
19use serde_json::{Map, Value};
20
21use super::error::StoreError;
22use super::store::Store;
23use crate::backend::jobs::definition::{Policy, SecretRef, TemplateRef};
24
25#[derive(Debug, Clone, Default, Serialize, Deserialize)]
26pub struct CronJob {
27    pub id: String,
28    pub name: String,
29    /// Standard 5-field cron expression, read in `tz`. Empty for a job
30    /// whose trigger isn't cron.
31    pub expression: String,
32    /// What a `message` job sends (its brief).
33    pub prompt: String,
34    /// Target agent id for injection.
35    pub target: String,
36    /// Identity M1b/M3 (SPEC_AGENT_IDENTITY_CARRIED_NOT_DERIVED_2026_09_23.md
37    /// §9.1): the UID (`db_agents.id`) of `target`, resolved once at the
38    /// authoring boundary and carried in — spec §5.4, a job firing at 03:00
39    /// must never resolve a name. Since M3 a job with a `target_uid` fires
40    /// by it; empty = none was carried, and the job fires by `target`.
41    #[serde(default)]
42    pub target_uid: String,
43    pub created_by: String,
44    /// Identity M4c-1 (SPEC_AGENT_IDENTITY_CARRIED_NOT_DERIVED_2026_09_23.md
45    /// §6.5.9): the creator's UID, taken from the create request's `Caller`
46    /// — its `X-Agent-Token` — never from a body field. Empty = the create
47    /// was Unattributed; never guessed.
48    #[serde(default)]
49    pub created_by_uid: String,
50    /// Who last wrote the definition (its prompt, target or trigger), as the request that wrote it proved: an agent's
51    /// UID from its token, [`WRITER_OPERATOR`] for the app's own window, [`WRITER_UNKNOWN`] for a caller nothing
52    /// identified. Empty: not recorded yet (a job from before this), so the creator stands.
53    #[serde(default)]
54    pub last_written_by: String,
55    pub enabled: bool,
56    pub last_fired: Option<i64>,
57    pub fire_count: i64,
58    /// `None` = unlimited.
59    pub max_fires: Option<i64>,
60    pub created_at: i64,
61    /// Hard expiry bound in seconds since `created_at`. `None` = no expiry
62    /// (the default — existing jobs created before this field are
63    /// unaffected). See
64    /// docs/specs/SPEC_AGENT_POLLING_AND_WAKEUP_HARDENING_2026_08_04.md Phase 0.
65    pub max_age_secs: Option<i64>,
66    /// What an undelivered fire leaves (SPEC_JOBS_AND_TEMPLATES_2026_10_24.md
67    /// §5.2): `skip` (a missed run) or `latest` (one coalesced pending fire,
68    /// delivered when the agent is back). The job's `policy.catch_up`; kept
69    /// in its own column, which is the one read.
70    #[serde(default = "default_catch_up")]
71    pub catch_up: String,
72    /// Scheduled fires that reached no one at their time (the target wasn't
73    /// running, or names no agent). They don't count in `fire_count` or
74    /// toward `max_fires`. A `latest` job's pending fire delivered later
75    /// counts then, as a fire.
76    #[serde(default)]
77    pub missed_count: i64,
78    #[serde(default)]
79    pub last_missed_at: Option<i64>,
80    /// Why the last miss happened: `target_stopped`, `target_missing` or
81    /// `failed: <error>` (`FireOutcome::miss_reason`). Empty = never missed.
82    #[serde(default)]
83    pub last_miss_reason: String,
84    /// The agent responsible for the job, whose leader its failures go to
85    /// (§3.4). Empty: its creator ([`Self::owner_uid`]).
86    #[serde(default)]
87    pub owner: String,
88    /// `cron` (also when empty), `every`, `once`, `manual` or `event`.
89    #[serde(default)]
90    pub trigger_kind: String,
91    /// The cron trigger's IANA zone; empty is UTC.
92    #[serde(default)]
93    pub tz: String,
94    #[serde(default)]
95    pub every_secs: Option<i64>,
96    #[serde(default)]
97    pub once_at_ms: Option<i64>,
98    /// An `event` trigger's source and filter (`definition::EventTrigger`); null for any other trigger.
99    #[serde(default)]
100    pub trigger_event: Value,
101    /// `message` (also when empty), `task` or `spawn`.
102    #[serde(default)]
103    pub action_kind: String,
104    /// A `task` or `spawn` action's fields; null for `message`, whose fields
105    /// are `prompt`, `target` and `target_uid`.
106    #[serde(default)]
107    pub action: Value,
108    #[serde(default)]
109    pub policy: Policy,
110    #[serde(default)]
111    pub template: Option<TemplateRef>,
112    #[serde(default)]
113    pub params: Map<String, Value>,
114    #[serde(default)]
115    pub outputs: Vec<String>,
116    #[serde(default)]
117    pub secrets: Vec<SecretRef>,
118}
119
120/// The app's own window wrote the definition.
121pub const WRITER_OPERATOR: &str = "operator";
122/// The definition was written by a caller nothing identified (no agent token, not the app's own window).
123pub const WRITER_UNKNOWN: &str = "unknown";
124
125/// Who stands behind a job's current definition, when a fire of it can be proven.
126#[derive(Debug, Clone, PartialEq, Eq)]
127pub enum FireProof {
128    /// The app's own window wrote it.
129    Operator,
130    /// This agent's token wrote it (its UID).
131    Agent(String),
132}
133
134impl CronJob {
135    /// Who stands behind the job's definition as it is now, or `None` when nothing identified its writer: a job that
136    /// was created or last edited by a caller without an agent token or the app's own proof fires unproven.
137    pub fn fire_proof(&self) -> Option<FireProof> {
138        let writer = match self.last_written_by.trim() {
139            "" => self.created_by_uid.trim(),
140            writer => writer,
141        };
142        match writer {
143            "" | WRITER_UNKNOWN => None,
144            WRITER_OPERATOR => Some(FireProof::Operator),
145            uid => Some(FireProof::Agent(uid.to_string())),
146        }
147    }
148
149    /// The owner's UID: the definition's `owner`, else the creator's.
150    pub fn owner_uid(&self) -> &str {
151        match self.owner.trim() {
152            "" => self.created_by_uid.trim(),
153            owner => owner,
154        }
155    }
156}
157
158fn default_catch_up() -> String {
159    "skip".to_string()
160}
161
162/// What both stores' ALTER loops run after their CREATE batch
163/// (`run_shared_store_schema`, `run_identity_store_schema` in
164/// `migrations.rs`), beside `db_cron_jobs`: first the columns that table
165/// gained after it was created, then `db_jobs`, then any column `db_jobs`
166/// gains later. None needs a schema version bump: an older build never reads
167/// them, and a bump would lock older builds out (`check_schema_compat`).
168/// "duplicate column" is the column already being there.
169///
170/// `db_cron_jobs.catch_up` defaults to `latest` so every job from before it
171/// keeps the startup catch-up. `db_cron_jobs` is no longer written; older
172/// builds still use it.
173pub(super) const JOB_TABLES: [&str; 7] = [
174    "ALTER TABLE db_cron_jobs ADD COLUMN catch_up TEXT NOT NULL DEFAULT 'latest'",
175    // The miss record (`CronJob::missed_count`).
176    "ALTER TABLE db_cron_jobs ADD COLUMN missed_count INTEGER NOT NULL DEFAULT 0",
177    "ALTER TABLE db_cron_jobs ADD COLUMN last_missed_at INTEGER",
178    "ALTER TABLE db_cron_jobs ADD COLUMN last_miss_reason TEXT NOT NULL DEFAULT ''",
179    JOBS_SCHEMA,
180    // An event trigger's source and filter (`CronJob::trigger_event`).
181    "ALTER TABLE db_jobs ADD COLUMN trigger_event TEXT NOT NULL DEFAULT ''",
182    // Who last wrote the definition (`CronJob::last_written_by`).
183    "ALTER TABLE db_jobs ADD COLUMN last_written_by TEXT NOT NULL DEFAULT ''",
184];
185
186/// `db_jobs` and its index. Columns added later go after it in
187/// [`JOB_TABLES`], as `ALTER TABLE db_jobs ADD COLUMN …`.
188const JOBS_SCHEMA: &str = "
189    CREATE TABLE IF NOT EXISTS db_jobs (
190        id               TEXT PRIMARY KEY,
191        job_version      INTEGER NOT NULL DEFAULT 1,
192        name             TEXT NOT NULL,
193        owner            TEXT NOT NULL DEFAULT '',
194        created_by       TEXT NOT NULL DEFAULT '',
195        created_by_uid   TEXT NOT NULL DEFAULT '',
196        template         TEXT NOT NULL DEFAULT '',
197        params           TEXT NOT NULL DEFAULT '{}',
198        trigger_kind     TEXT NOT NULL DEFAULT 'cron',
199        expression       TEXT NOT NULL DEFAULT '',
200        tz               TEXT NOT NULL DEFAULT 'UTC',
201        every_secs       INTEGER,
202        once_at_ms       INTEGER,
203        action_kind      TEXT NOT NULL DEFAULT 'message',
204        prompt           TEXT NOT NULL DEFAULT '',
205        target           TEXT NOT NULL DEFAULT '',
206        target_uid       TEXT NOT NULL DEFAULT '',
207        action           TEXT NOT NULL DEFAULT 'null',
208        policy           TEXT NOT NULL DEFAULT '{}',
209        outputs          TEXT NOT NULL DEFAULT '[]',
210        secrets          TEXT NOT NULL DEFAULT '[]',
211        enabled          INTEGER NOT NULL DEFAULT 1,
212        last_fired       INTEGER,
213        fire_count       INTEGER NOT NULL DEFAULT 0,
214        max_fires        INTEGER,
215        created_at       INTEGER NOT NULL DEFAULT 0,
216        max_age_secs     INTEGER,
217        catch_up         TEXT NOT NULL DEFAULT 'skip',
218        missed_count     INTEGER NOT NULL DEFAULT 0,
219        last_missed_at   INTEGER,
220        last_miss_reason TEXT NOT NULL DEFAULT '',
221        trigger_event    TEXT NOT NULL DEFAULT ''
222    );
223    CREATE INDEX IF NOT EXISTS idx_jobs_enabled ON db_jobs(enabled);
224";
225
226const COLS: &str = "id, name, expression, prompt, target, created_by, enabled, last_fired, fire_count, max_fires, \
227     created_at, max_age_secs, target_uid, created_by_uid, catch_up, missed_count, last_missed_at, last_miss_reason, \
228     owner, trigger_kind, tz, every_secs, once_at_ms, action_kind, action, policy, template, params, outputs, secrets, trigger_event, \
229     last_written_by";
230
231fn json_text<T: Serialize>(v: &T) -> String {
232    serde_json::to_string(v).unwrap_or_else(|_| "null".to_string())
233}
234
235impl Store {
236    pub fn cron_create(&self, job: &CronJob) -> Result<(), StoreError> {
237        let conn = self.conn.lock().unwrap();
238        conn.execute(
239            &format!(
240                "INSERT INTO db_jobs ({COLS}) VALUES \
241                 (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,?12,?13,?14,?15,?16,?17,?18,?19,?20,?21,?22,?23,?24,?25,?26,?27,?28,?29,?30,?31,?32)"
242            ),
243            params![
244                job.id,
245                job.name,
246                job.expression,
247                job.prompt,
248                job.target,
249                job.created_by,
250                job.enabled as i64,
251                job.last_fired,
252                job.fire_count,
253                job.max_fires,
254                job.created_at,
255                job.max_age_secs,
256                job.target_uid,
257                job.created_by_uid,
258                job.catch_up,
259                job.missed_count,
260                job.last_missed_at,
261                job.last_miss_reason,
262                job.owner,
263                job.trigger_kind,
264                job.tz,
265                job.every_secs,
266                job.once_at_ms,
267                job.action_kind,
268                json_text(&job.action),
269                json_text(&job.policy),
270                job.template.as_ref().map(json_text).unwrap_or_default(),
271                json_text(&job.params),
272                json_text(&job.outputs),
273                json_text(&job.secrets),
274                json_text(&job.trigger_event),
275                job.last_written_by,
276            ],
277        )?;
278        Ok(())
279    }
280
281    /// Replace a job's definition (an edit), leaving its fires, misses and
282    /// creation alone. `Ok(false)` when there is no such job.
283    pub fn cron_update_definition(&self, job: &CronJob) -> Result<bool, StoreError> {
284        let conn = self.conn.lock().unwrap();
285        let n = conn.execute(
286            "UPDATE db_jobs SET name = ?2, expression = ?3, prompt = ?4, target = ?5, target_uid = ?6, enabled = ?7,
287                catch_up = ?8, owner = ?9, trigger_kind = ?10, tz = ?11, every_secs = ?12, once_at_ms = ?13,
288                action_kind = ?14, action = ?15, policy = ?16, template = ?17, params = ?18, outputs = ?19, secrets = ?20, trigger_event = ?21,
289                last_written_by = ?22
290             WHERE id = ?1",
291            params![
292                job.id,
293                job.name,
294                job.expression,
295                job.prompt,
296                job.target,
297                job.target_uid,
298                job.enabled as i64,
299                job.catch_up,
300                job.owner,
301                job.trigger_kind,
302                job.tz,
303                job.every_secs,
304                job.once_at_ms,
305                job.action_kind,
306                json_text(&job.action),
307                json_text(&job.policy),
308                job.template.as_ref().map(json_text).unwrap_or_default(),
309                json_text(&job.params),
310                json_text(&job.outputs),
311                json_text(&job.secrets),
312                json_text(&job.trigger_event),
313                job.last_written_by,
314            ],
315        )?;
316        Ok(n > 0)
317    }
318
319    pub fn cron_list(&self) -> Result<Vec<CronJob>, StoreError> {
320        let conn = self.conn.lock().unwrap();
321        let mut stmt = conn.prepare(&format!("SELECT {COLS} FROM db_jobs ORDER BY created_at ASC"))?;
322        let iter = stmt.query_map([], map_row)?;
323        iter.collect::<Result<Vec<_>, _>>().map_err(Into::into)
324    }
325
326    pub fn cron_list_enabled(&self) -> Result<Vec<CronJob>, StoreError> {
327        let conn = self.conn.lock().unwrap();
328        let mut stmt = conn.prepare(&format!("SELECT {COLS} FROM db_jobs WHERE enabled = 1 ORDER BY created_at ASC"))?;
329        let iter = stmt.query_map([], map_row)?;
330        iter.collect::<Result<Vec<_>, _>>().map_err(Into::into)
331    }
332
333    pub fn cron_get(&self, id: &str) -> Result<Option<CronJob>, StoreError> {
334        let conn = self.conn.lock().unwrap();
335        let mut stmt = conn.prepare(&format!("SELECT {COLS} FROM db_jobs WHERE id = ?1"))?;
336        let mut rows = stmt.query_map(params![id], map_row)?;
337        match rows.next() {
338            Some(r) => Ok(Some(r?)),
339            None => Ok(None),
340        }
341    }
342
343    pub fn cron_set_enabled(&self, id: &str, enabled: bool) -> Result<bool, StoreError> {
344        let conn = self.conn.lock().unwrap();
345        let rows = conn.execute(
346            "UPDATE db_jobs SET enabled = ?1 WHERE id = ?2",
347            params![enabled as i64, id],
348        )?;
349        Ok(rows > 0)
350    }
351
352    pub fn cron_record_fire(&self, id: &str, now: i64) -> Result<(), StoreError> {
353        let conn = self.conn.lock().unwrap();
354        conn.execute(
355            "UPDATE db_jobs
356             SET last_fired = ?1,
357                 fire_count = fire_count + 1,
358                 enabled    = CASE
359                     WHEN max_fires IS NOT NULL AND fire_count + 1 >= max_fires THEN 0
360                     ELSE enabled
361                 END
362             WHERE id = ?2",
363            params![now, id],
364        )?;
365        Ok(())
366    }
367
368    /// A scheduled fire that reached no one: count the miss and say why,
369    /// leaving `last_fired`, `fire_count` and `max_fires` alone.
370    pub fn cron_record_miss(&self, id: &str, now: i64, reason: &str) -> Result<(), StoreError> {
371        let conn = self.conn.lock().unwrap();
372        conn.execute(
373            "UPDATE db_jobs
374             SET missed_count = missed_count + 1, last_missed_at = ?1, last_miss_reason = ?2
375             WHERE id = ?3",
376            params![now, reason, id],
377        )?;
378        Ok(())
379    }
380
381    pub fn cron_delete(&self, id: &str) -> Result<bool, StoreError> {
382        let conn = self.conn.lock().unwrap();
383        let rows = conn.execute("DELETE FROM db_jobs WHERE id = ?1", params![id])?;
384        Ok(rows > 0)
385    }
386}
387
388/// A JSON column, or the type's default when it doesn't parse (a row an
389/// older or newer build wrote).
390fn json_col<T: serde::de::DeserializeOwned + Default>(row: &rusqlite::Row<'_>, i: usize) -> rusqlite::Result<T> {
391    let text: String = row.get(i)?;
392    Ok(serde_json::from_str(&text).unwrap_or_default())
393}
394
395fn map_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<CronJob> {
396    let template: String = row.get(26)?;
397    Ok(CronJob {
398        id:            row.get(0)?,
399        name:          row.get(1)?,
400        expression:    row.get(2)?,
401        prompt:        row.get(3)?,
402        target:        row.get(4)?,
403        created_by:    row.get(5)?,
404        enabled:       row.get::<_, i64>(6)? != 0,
405        last_fired:    row.get(7)?,
406        fire_count:    row.get(8)?,
407        max_fires:     row.get(9)?,
408        created_at:    row.get(10)?,
409        max_age_secs:  row.get(11)?,
410        target_uid:    row.get(12)?,
411        created_by_uid: row.get(13)?,
412        catch_up:      row.get(14)?,
413        missed_count:  row.get(15)?,
414        last_missed_at: row.get(16)?,
415        last_miss_reason: row.get(17)?,
416        owner:         row.get(18)?,
417        trigger_kind:  row.get(19)?,
418        tz:            row.get(20)?,
419        every_secs:    row.get(21)?,
420        once_at_ms:    row.get(22)?,
421        action_kind:   row.get(23)?,
422        action:        json_col(row, 24)?,
423        policy:        json_col(row, 25)?,
424        template:      serde_json::from_str(&template).ok(),
425        params:        json_col(row, 27)?,
426        outputs:       json_col(row, 28)?,
427        secrets:       json_col(row, 29)?,
428        trigger_event: json_col(row, 30)?,
429        last_written_by: row.get(31)?,
430    })
431}