Skip to main content

agentmux_srv_core/backend/jobs/
cloud_events.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Cloud jobs report in: the signed run event (docs/specs/SPEC_JOBS_AND_TEMPLATES_2026_10_24.md §4.1, §4.2).
5//!
6//! A cloud job posts a small event when a run starts, while it runs, and when it finishes. Each arrives as an
7//! envelope: the event's JSON body as the reporter wrote it, the reporter's public key, and an Ed25519 signature
8//! over `agentmux-job-event-v1\0<job_id>\0<run_id>\0<event_id>\0<hex SHA-256 of the body>`. An event counts only if
9//! its key is one the operator pinned ([`super::reporters`]), its signature holds, and an approved cloud job
10//! manifest names that job with that key. Anything else is dropped and counted ([`drops`]), never shown as a run.
11//!
12//! The text in an event (`summary`, link labels) is data: it is clipped here and shown as text, never an
13//! instruction.
14
15use std::collections::BTreeMap;
16use std::sync::Mutex;
17
18use base64::Engine;
19use ed25519_dalek::{Signature, Verifier, VerifyingKey};
20use serde::{Deserialize, Serialize};
21use sha2::{Digest, Sha256};
22
23use super::reporters::Reporters;
24use super::RunLedger;
25use crate::backend::storage::job_cloud::{cloud_run_id, CloudFinish, CloudStart, EventMark};
26use crate::backend::storage::job_runs::{clip_summary, infra, state, JobRun, SUMMARY_MAX_CHARS};
27
28/// The schema name every event carries.
29pub const SCHEMA: &str = "agentmux.job-event/1";
30/// The bytes an Ed25519 signature over an event starts with, so it can't pass as a widget's or a template's.
31pub const SIGNED_PREFIX: &[u8] = b"agentmux-job-event-v1\0";
32/// The most a body may be.
33pub const MAX_BODY_BYTES: usize = 8 * 1024;
34/// Events older than this are refused (§4.2).
35pub const MAX_AGE_MS: i64 = 7 * 24 * 3600 * 1000;
36/// How far ahead of this computer's clock an event may claim to be, for a reporter whose clock runs fast.
37pub const MAX_AHEAD_MS: i64 = 3600 * 1000;
38const MAX_LINKS: usize = 5;
39
40/// One event as it arrives: the body exactly as the reporter signed it, the key, the signature.
41#[derive(Debug, Clone, Default, Deserialize, Serialize)]
42pub struct SignedJobEvent {
43    pub body: String,
44    /// The reporter's public key, base64.
45    pub public_key: String,
46    /// The Ed25519 signature, base64.
47    pub signature: String,
48}
49
50#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
51#[serde(rename_all = "snake_case")]
52pub enum Phase {
53    Started,
54    Finished,
55    Heartbeat,
56}
57
58#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
59#[serde(rename_all = "snake_case")]
60pub enum Trigger {
61    Schedule,
62    Event,
63    Manual,
64    Retry,
65}
66
67impl Trigger {
68    fn as_str(self) -> &'static str {
69        match self {
70            Trigger::Schedule => "schedule",
71            Trigger::Event => "event",
72            Trigger::Manual => "manual",
73            Trigger::Retry => "retry",
74        }
75    }
76}
77
78#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
79#[serde(rename_all = "snake_case")]
80pub enum Infra {
81    Ok,
82    Error,
83    Timeout,
84}
85
86impl Infra {
87    fn as_str(self) -> &'static str {
88        match self {
89            Infra::Ok => infra::OK,
90            Infra::Error => infra::ERROR,
91            Infra::Timeout => infra::TIMEOUT,
92        }
93    }
94}
95
96#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
97#[serde(rename_all = "snake_case")]
98pub enum Outcome {
99    Ok,
100    Findings,
101    Failed,
102    Unknown,
103}
104
105impl Outcome {
106    fn as_str(self) -> &'static str {
107        match self {
108            Outcome::Ok => "ok",
109            Outcome::Findings => "findings",
110            Outcome::Failed => "failed",
111            Outcome::Unknown => "unknown",
112        }
113    }
114}
115
116#[derive(Debug, Clone, Deserialize)]
117#[serde(deny_unknown_fields)]
118pub struct Tokens {
119    pub input: i64,
120    pub output: i64,
121}
122
123#[derive(Debug, Clone, Deserialize)]
124#[serde(deny_unknown_fields)]
125pub struct EventLink {
126    pub label: String,
127    pub url: String,
128}
129
130/// The event body (`schema/agentmux-job-event.v1.schema.json`).
131#[derive(Debug, Clone, Deserialize)]
132#[serde(deny_unknown_fields)]
133pub struct JobEvent {
134    pub schema: String,
135    pub event_id: String,
136    pub job_id: String,
137    pub run_id: String,
138    pub phase: Phase,
139    pub at: i64,
140    #[serde(default)]
141    pub scheduled_for: Option<i64>,
142    #[serde(default)]
143    pub trigger: Option<Trigger>,
144    #[serde(default)]
145    pub attempt: Option<i64>,
146    #[serde(default)]
147    pub infra: Option<Infra>,
148    #[serde(default)]
149    pub outcome: Option<Outcome>,
150    #[serde(default)]
151    pub summary: Option<String>,
152    #[serde(default)]
153    pub duration_ms: Option<i64>,
154    #[serde(default)]
155    pub cost_usd: Option<f64>,
156    #[serde(default)]
157    pub tokens: Option<Tokens>,
158    #[serde(default)]
159    pub findings: Option<i64>,
160    #[serde(default)]
161    pub links: Option<Vec<EventLink>>,
162}
163
164/// Why an event was not written. The label is what the Jobs tab's diagnostic line says ("3 events dropped:
165/// unknown job").
166#[derive(Debug, Clone, PartialEq, Eq)]
167pub enum Dropped {
168    TooBig,
169    Malformed(String),
170    TooOld,
171    FromTheFuture,
172    UnknownReporter,
173    BadSignature,
174    UnknownJob,
175    WrongReporter,
176    /// The event is genuine but this machine couldn't write it; sending it again can work.
177    LedgerError,
178}
179
180impl Dropped {
181    pub fn label(&self) -> &'static str {
182        match self {
183            Dropped::TooBig => "too big",
184            Dropped::Malformed(_) => "malformed",
185            Dropped::TooOld => "too old",
186            Dropped::FromTheFuture => "clock ahead",
187            Dropped::UnknownReporter => "unknown reporter",
188            Dropped::BadSignature => "bad signature",
189            Dropped::UnknownJob => "unknown job",
190            Dropped::WrongReporter => "reporter not allowed for this job",
191            Dropped::LedgerError => "ledger error",
192        }
193    }
194}
195
196/// What a valid event did.
197#[derive(Debug, Clone, Copy, PartialEq, Eq)]
198pub enum Applied {
199    Started(CloudStart),
200    Finished(CloudFinish),
201    /// The run's lost deadline moved back.
202    Heartbeat,
203    /// A heartbeat for a run that isn't running: nothing to push back.
204    Ignored,
205    /// This event id was written already.
206    Repeat,
207}
208
209/// An approved cloud job (§4.3): which key may report for it, and its name for the ledger.
210#[derive(Debug, Clone, PartialEq, Eq)]
211pub struct CloudJob {
212    pub id: String,
213    pub name: String,
214    /// The public key (base64) whose events count for this job.
215    pub reporter_key: String,
216}
217
218/// Where approved cloud jobs are found.
219pub trait CloudJobs {
220    fn cloud_job(&self, job_id: &str) -> Option<CloudJob>;
221}
222
223static DROPS: Mutex<BTreeMap<&'static str, u64>> = Mutex::new(BTreeMap::new());
224
225fn count_drop(why: &Dropped) {
226    *DROPS.lock().unwrap_or_else(|e| e.into_inner()).entry(why.label()).or_default() += 1;
227}
228
229/// How many events were dropped since this AgentMux started, by label.
230pub fn drops() -> Vec<(&'static str, u64)> {
231    DROPS.lock().unwrap_or_else(|e| e.into_inner()).iter().map(|(k, v)| (*k, *v)).collect()
232}
233
234fn word(s: &str, max: usize, extra: &str) -> bool {
235    !s.is_empty() && s.len() <= max && s.bytes().all(|b| b.is_ascii_alphanumeric() || extra.as_bytes().contains(&b))
236}
237
238/// `publisher.name`: lowercase letters, digits and `-`, one dot.
239fn is_job_id(s: &str) -> bool {
240    let ok = |p: &str| !p.is_empty() && p.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-');
241    s.len() <= 80 && s.split_once('.').is_some_and(|(a, b)| ok(a) && ok(b))
242}
243
244/// Parse and check one event body.
245pub fn parse(body: &str) -> Result<JobEvent, Dropped> {
246    if body.len() > MAX_BODY_BYTES {
247        return Err(Dropped::TooBig);
248    }
249    let ev: JobEvent = serde_json::from_str(body).map_err(|e| Dropped::Malformed(e.to_string()))?;
250    let bad = |why: &str| Err(Dropped::Malformed(why.to_string()));
251    if ev.schema != SCHEMA {
252        return bad("schema");
253    }
254    if !word(&ev.event_id, 64, "-_") {
255        return bad("event_id");
256    }
257    if !is_job_id(&ev.job_id) {
258        return bad("job_id");
259    }
260    if !word(&ev.run_id, 128, "._:-") {
261        return bad("run_id");
262    }
263    if ev.at <= 0 || ev.scheduled_for.is_some_and(|s| s <= 0) || ev.attempt.is_some_and(|a| !(1..=1000).contains(&a)) {
264        return bad("at, scheduled_for or attempt");
265    }
266    if ev.phase == Phase::Finished && (ev.infra.is_none() || ev.outcome.is_none()) {
267        return bad("a finished event needs infra and outcome");
268    }
269    if ev.summary.as_deref().is_some_and(|s| s.chars().count() > SUMMARY_MAX_CHARS) {
270        return bad("summary is over 300 characters");
271    }
272    if ev.duration_ms.is_some_and(|d| d < 0) || ev.findings.is_some_and(|f| f < 0) || ev.tokens.as_ref().is_some_and(|t| t.input < 0 || t.output < 0) {
273        return bad("a negative figure");
274    }
275    if ev.cost_usd.is_some_and(|c| !c.is_finite() || c < 0.0) {
276        return bad("cost_usd");
277    }
278    if let Some(links) = &ev.links {
279        let https = |u: &str| u.len() <= 500 && u.strip_prefix("https://").is_some_and(|rest| !rest.is_empty() && !rest.contains(char::is_whitespace));
280        if links.len() > MAX_LINKS || links.iter().any(|l| l.label.chars().count() > 80 || !https(&l.url)) {
281            return bad("links: at most 5, https only");
282        }
283    }
284    Ok(ev)
285}
286
287/// The bytes the reporter signed for `ev`'s `body`.
288pub fn signed_bytes(ev: &JobEvent, body: &str) -> Vec<u8> {
289    let mut m = SIGNED_PREFIX.to_vec();
290    for part in [ev.job_id.as_str(), ev.run_id.as_str(), ev.event_id.as_str()] {
291        m.extend_from_slice(part.as_bytes());
292        m.push(0);
293    }
294    m.extend_from_slice(hex(&Sha256::digest(body.as_bytes())).as_bytes());
295    m
296}
297
298fn hex(bytes: &[u8]) -> String {
299    bytes.iter().map(|b| format!("{b:02x}")).collect()
300}
301
302fn verify(envelope: &SignedJobEvent, ev: &JobEvent) -> Result<(), Dropped> {
303    let b64 = base64::engine::general_purpose::STANDARD;
304    let key: [u8; 32] = b64.decode(envelope.public_key.trim()).ok().and_then(|k| k.try_into().ok()).ok_or(Dropped::BadSignature)?;
305    let signature: [u8; 64] = b64.decode(envelope.signature.trim()).ok().and_then(|s| s.try_into().ok()).ok_or(Dropped::BadSignature)?;
306    let key = VerifyingKey::from_bytes(&key).map_err(|_| Dropped::BadSignature)?;
307    key.verify(&signed_bytes(ev, &envelope.body), &Signature::from_bytes(&signature)).map_err(|_| Dropped::BadSignature)
308}
309
310/// The ledger row an event describes: `running` for a start, `finished` for a finish.
311fn row_for(ev: &JobEvent, job: &CloudJob, reporter: &str, recorded_by: &str) -> JobRun {
312    let finished = ev.phase == Phase::Finished;
313    let mut run = JobRun::new(
314        &cloud_run_id(&ev.job_id, &ev.run_id),
315        &ev.job_id,
316        "cloud",
317        &job.name,
318        ev.trigger.map_or("schedule", Trigger::as_str),
319        if finished { state::FINISHED } else { state::RUNNING },
320        ev.at,
321    );
322    run.attempt = ev.attempt.unwrap_or(1);
323    run.reporter = reporter.to_string();
324    run.recorded_by = recorded_by.to_string();
325    let mut links = serde_json::json!({ "run_id": ev.run_id });
326    if let Some(slot) = ev.scheduled_for {
327        links["scheduled_for_ms"] = slot.into();
328    }
329    if finished {
330        run.infra = ev.infra.map_or("", Infra::as_str).to_string();
331        run.outcome = ev.outcome.map_or("unknown", Outcome::as_str).to_string();
332        run.summary = clip_summary(ev.summary.as_deref().unwrap_or(""));
333        run.ended_at_ms = Some(ev.at);
334        // A closed row whose `started` never arrived starts as long before it ended as the run says it lasted.
335        run.started_at_ms = ev.at - ev.duration_ms.unwrap_or(0).max(0);
336        if let Some(cost) = ev.cost_usd {
337            run.cost_usd = cost;
338            run.cost_known = true;
339        }
340        if let Some(t) = &ev.tokens {
341            run.output_tokens = t.output;
342            links["input_tokens"] = t.input.into();
343        }
344        if let Some(f) = ev.findings {
345            links["findings"] = f.into();
346        }
347        if let Some(d) = ev.duration_ms {
348            links["duration_ms"] = d.into();
349        }
350        if let Some(l) = &ev.links {
351            links["reported"] = l.iter().map(|l| serde_json::json!({ "label": l.label, "url": l.url })).collect();
352        }
353    }
354    run.links = links;
355    run
356}
357
358impl RunLedger {
359    /// Write one cloud event into the ledger, if it is genuine: its key pinned, its signature good, its job approved
360    /// with that key, and not seen before. A refused event is counted ([`drops`]) and logged, not shown as a run.
361    pub fn ingest_cloud_event(
362        &self,
363        envelope: &SignedJobEvent,
364        reporters: &Reporters,
365        jobs: &dyn CloudJobs,
366        now_ms: i64,
367    ) -> Result<Applied, Dropped> {
368        let result = self.apply_cloud_event(envelope, reporters, jobs, now_ms);
369        if let Err(why) = &result {
370            count_drop(why);
371            tracing::info!(target: "jobs", reason = why.label(), detail = ?why, "jobs: a cloud job event was dropped");
372        }
373        result
374    }
375
376    fn apply_cloud_event(&self, envelope: &SignedJobEvent, reporters: &Reporters, jobs: &dyn CloudJobs, now_ms: i64) -> Result<Applied, Dropped> {
377        let ev = parse(&envelope.body)?;
378        if now_ms - ev.at > MAX_AGE_MS {
379            return Err(Dropped::TooOld);
380        }
381        if ev.at - now_ms > MAX_AHEAD_MS {
382            return Err(Dropped::FromTheFuture);
383        }
384        let fingerprint = reporters.fingerprint_of_pinned(&envelope.public_key).ok_or(Dropped::UnknownReporter)?;
385        verify(envelope, &ev)?;
386        let job = jobs.cloud_job(&ev.job_id).ok_or(Dropped::UnknownJob)?;
387        if job.reporter_key != envelope.public_key {
388            return Err(Dropped::WrongReporter);
389        }
390        let store = self.store();
391        let log = |e: crate::backend::storage::StoreError| {
392            tracing::warn!(target: "jobs", error = %e, job = %ev.job_id, "jobs: couldn't write a cloud job event");
393            Dropped::LedgerError
394        };
395        let run = row_for(&ev, &job, &fingerprint, &self.recorded_by);
396        let mark = EventMark { run_id: &ev.run_id, event_id: &ev.event_id, now_ms };
397        let applied = match ev.phase {
398            Phase::Started => store.job_cloud_start(&run, ev.scheduled_for, &mark).map_err(log)?.map(Applied::Started),
399            Phase::Finished => store.job_cloud_finish(&run, ev.scheduled_for, &mark).map_err(log)?.map(Applied::Finished),
400            Phase::Heartbeat => store.job_cloud_heartbeat(&ev.job_id, &run.id, ev.at, &mark).map_err(log)?.map(|moved| {
401                if moved {
402                    Applied::Heartbeat
403                } else {
404                    Applied::Ignored
405                }
406            }),
407        };
408        let Some(applied) = applied else {
409            return Ok(Applied::Repeat);
410        };
411        if applied != Applied::Ignored {
412            self.changed(&ev.job_id);
413        }
414        Ok(applied)
415    }
416}
417
418#[cfg(test)]
419#[path = "cloud_events_tests.rs"]
420mod tests;