Skip to main content

agentmux_srv_core/backend/jobs/
expect.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4//! A job on the `expect` source is a dead man's switch: it starts a run when a job it watches has **not** had a good
5//! run lately (docs/specs/SPEC_DRONE_REAL_WORLD_JOBS_2026_11_11.md ยง3.2). Silence is the event: "the nightly report
6//! did not come" is the failure nobody sees, and this is how someone does.
7//!
8//! The job's filter says what is expected:
9//!   * `job`             required: the name or id of the job whose runs are looked at.
10//!   * `within_minutes`  required: 1 to 43200 (30 days). The watched job should have a good run that ended within
11//!                       this long ago.
12//!   * `every_minutes`   how often to look, 1 to 1440, default 5.
13//!
14//! A good run is the newest run of the watched job that is a finished one whose outcome is `ok` or `findings` (it did its work). A run that failed, or ended
15//! with an unknown outcome, is not one. While a run of the watched job is still going, nothing fires: it may yet
16//! succeed in time.
17//!
18//! When the last good run is older than `within_minutes` (or there is none, or no job has that name), the job's
19//! run starts **once for that gap**: the event is keyed by the last good run, so a restart, or the next look, does not
20//! repeat it, and a good run followed by a new gap is a new event. The run reads `{{trigger.expected}}` (the watched
21//! job), `{{trigger.within_minutes}}`, `{{trigger.last_ok_ms}}` (null when there has never been one),
22//! `{{trigger.job_found}}` and `{{trigger.last_seen}}` (the newest run, if any).
23//!
24//! (The ledger is asked for the last good run on its own, so a long bad stretch does not hide it.)
25//!
26//! The local form checks this machine's run ledger, so it cannot fire while the machine is off; the cloud form that
27//! can is a later phase.
28
29use std::collections::HashMap;
30
31use serde_json::{json, Map, Value};
32
33use super::definition::{event_source, trigger_kind};
34use super::poll::Check;
35use crate::backend::cron::{CronScheduler, JobEvent};
36use crate::backend::storage::cron::CronJob;
37
38pub const MAX_WITHIN_MINUTES: u64 = 30 * 24 * 60;
39pub const DEFAULT_EVERY_MINUTES: u64 = 5;
40const MAX_EVERY_MINUTES: u64 = 24 * 60;
41const KEYS: [&str; 3] = ["job", "within_minutes", "every_minutes"];
42/// How many of the watched job's newest runs are read.
43const RUNS_READ: u64 = 100;
44
45/// An `expect` trigger's filter: the job, how recent a good run must be, and how often to look.
46pub fn validate_filter(filter: &Map<String, Value>) -> Result<(), String> {
47    if let Some(key) = filter.keys().find(|k| !KEYS.contains(&k.as_str())) {
48        return Err(format!("trigger: expect has no filter key {key:?}; it has {}", KEYS.join(", ")));
49    }
50    if !filter.get("job").and_then(Value::as_str).is_some_and(|j| !j.trim().is_empty()) {
51        return Err("trigger: an expect filter has job, the name or id of the job it watches".to_string());
52    }
53    match filter.get("within_minutes").and_then(Value::as_u64) {
54        Some(n) if (1..=MAX_WITHIN_MINUTES).contains(&n) => {}
55        _ => return Err(format!("trigger: an expect filter has within_minutes, a whole number of 1 to {MAX_WITHIN_MINUTES}")),
56    }
57    if filter.get("every_minutes").is_some_and(|v| !v.as_u64().is_some_and(|n| (1..=MAX_EVERY_MINUTES).contains(&n))) {
58        return Err(format!("trigger: expect every_minutes is a whole number of 1 to {MAX_EVERY_MINUTES}"));
59    }
60    Ok(())
61}
62
63/// What an expect job watches, read from its filter.
64#[derive(Debug, PartialEq)]
65struct Plan {
66    job: String,
67    within_ms: i64,
68    every_ms: i64,
69}
70
71fn plan_of(job: &CronJob) -> Option<Plan> {
72    if !job.enabled || job.trigger_kind != trigger_kind::EVENT {
73        return None;
74    }
75    let t = &job.trigger_event;
76    if t.get("source").and_then(Value::as_str) != Some(event_source::EXPECT) {
77        return None;
78    }
79    let filter = t.get("filter").and_then(Value::as_object)?;
80    validate_filter(filter).ok()?;
81    Some(Plan {
82        job: filter.get("job").and_then(Value::as_str)?.trim().to_string(),
83        within_ms: filter.get("within_minutes").and_then(Value::as_u64)? as i64 * 60_000,
84        every_ms: filter.get("every_minutes").and_then(Value::as_u64).unwrap_or(DEFAULT_EVERY_MINUTES) as i64 * 60_000,
85    })
86}
87
88/// A run that did its work.
89fn is_good(run: &Value) -> bool {
90    run.get("state").and_then(Value::as_str) == Some("finished") && matches!(run.get("outcome").and_then(Value::as_str), Some("ok" | "findings"))
91}
92
93fn is_open(run: &Value) -> bool {
94    matches!(run.get("state").and_then(Value::as_str), Some("scheduled" | "pending" | "running"))
95}
96
97fn ended_or_started(run: &Value) -> i64 {
98    run.get("ended_ms").or_else(|| run.get("started_ms")).and_then(Value::as_i64).unwrap_or(0)
99}
100
101/// What the watched job's runs say at `now`: nothing to do, or the event to start.
102#[derive(Debug, PartialEq)]
103pub(crate) enum Verdict {
104    /// A good run is recent enough, or one is still going.
105    Fine,
106    /// The gap: the event's id and input.
107    Missed { id: String, input: Value },
108}
109
110pub(crate) fn judge(plan_job: &str, within_minutes: u64, answer: &Value, now: i64) -> Verdict {
111    let found = answer.get("found").and_then(Value::as_bool).unwrap_or(false);
112    let runs: Vec<&Value> = answer.get("runs").and_then(Value::as_array).map(|r| r.iter().collect()).unwrap_or_default();
113    if answer.get("ambiguous").and_then(Value::as_bool).unwrap_or(false) {
114        // Two jobs share the name: it is not known which is meant, and a guess would be a false alarm.
115        return Verdict::Fine;
116    }
117    let within_ms = within_minutes as i64 * 60_000;
118    if runs.iter().any(|r| is_open(r) && now - r.get("started_ms").and_then(Value::as_i64).unwrap_or(now) < within_ms) {
119        return Verdict::Fine;
120    }
121    // The listing is the newest runs only: the last good run is also said on its own, found however many newer ones
122    // failed, so a long bad stretch does not hide it.
123    let said_ok = answer.get("last_ok").filter(|r| r.is_object()).map(ended_or_started);
124    let last_ok = runs.iter().filter(|r| is_good(r)).map(|r| ended_or_started(r)).chain(said_ok).max();
125    if last_ok.is_some_and(|ok| now - ok <= within_ms) {
126        return Verdict::Fine;
127    }
128    let newest = runs.iter().max_by_key(|r| r.get("started_ms").and_then(Value::as_i64).unwrap_or(0));
129    let last_seen = newest.map(|r| json!({ "id": r.get("id"), "state": r.get("state"), "outcome": r.get("outcome"), "started_ms": r.get("started_ms"), "ended_ms": r.get("ended_ms") })).unwrap_or(Value::Null);
130    let key = last_ok.map_or("never".to_string(), |ms| ms.to_string());
131    Verdict::Missed {
132        id: format!("expect:{plan_job}:{key}"),
133        input: json!({ "expected": plan_job, "within_minutes": within_minutes, "last_ok_ms": last_ok, "job_found": found, "last_seen": last_seen }),
134    }
135}
136
137/// The expect poller's memory: when each job looks next.
138#[derive(Default)]
139pub struct ExpectState {
140    next_due_ms: HashMap<String, i64>,
141}
142
143/// Looks at the watched job of every expect job that is due and starts a run for each gap. Returns how many runs it
144/// started or queued. `check` answers the App query's `jobs`.
145pub async fn expect_due(scheduler: &CronScheduler, all: &[CronJob], check: &Check, state: &mut ExpectState, now: i64) -> usize {
146    let watching: Vec<(&CronJob, Plan)> = all.iter().filter_map(|j| plan_of(j).map(|p| (j, p))).collect();
147    state.next_due_ms.retain(|id, _| watching.iter().any(|(j, _)| &j.id == id));
148    let mut started = 0;
149    for (job, plan) in &watching {
150        let due = state.next_due_ms.entry(job.id.clone()).or_insert(now);
151        if now < *due {
152            continue;
153        }
154        *due = now + plan.every_ms;
155        let mut ask = Map::new();
156        ask.insert("query".into(), json!("jobs"));
157        ask.insert("job".into(), json!(plan.job));
158        ask.insert("limit".into(), json!(RUNS_READ));
159        let answer = match check(ask).await {
160            Ok(answer) => answer,
161            Err(e) => {
162                tracing::warn!(job_id = %job.id, watched = %plan.job, error = %e, "jobs: an expect couldn't read the runs; looking again next time");
163                continue;
164            }
165        };
166        let within_minutes = (plan.within_ms / 60_000) as u64;
167        if let Verdict::Missed { id, input } = judge(&plan.job, within_minutes, &answer, now) {
168            let fired = scheduler.fire_event(job, JobEvent { id: id.clone(), source: event_source::EXPECT.to_string(), input }).await;
169            started += usize::from(fired.run_id.is_some());
170            // The gap's id is forgotten after a week like any event id, which would start the same gap's run again:
171            // each look while the gap lasts moves its time forward (the row's run is unchanged, so it is not a new event).
172            if let Some(ledger) = scheduler.runs() {
173                let _ = ledger.store().job_event_touch(&job.id, &id, now);
174            }
175        }
176    }
177    started
178}