Skip to main content

agentmux_srv_core/backend/jobs/
incidents.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4//! When a job's run fails: one incident per job, not one per run
5//! (docs/specs/SPEC_JOBS_AND_TEMPLATES_2026_10_24.md §3.4).
6//!
7//! After each change to a job's runs the ledger nudges [`Incidents`], and a
8//! sweep looks at every job every [`SWEEP_MS`]. The keeper walks the job's
9//! decisive runs in the order they ended, from where it last stopped (its
10//! cursor, `storage::job_incidents`), judging each with the Jobs tab's own
11//! rule (`verdict::run_failed`):
12//!
13//! - **A failure with no incident open** opens one, files a Kanban task for
14//!   the job's owning leader (`kind: job-failure`, no review), sends that
15//!   leader an `[AgentMux]` note and the operator one notification
16//!   (`NotifyKind::JobFailed`).
17//! - **Another failure while it is open** is counted, and adds a line to the
18//!   task's history (fewer as a streak grows, [`worth_a_line`]), and nothing
19//!   else.
20//! - **The next success** recovers it: the task gets a "recovered" line and
21//!   stays open for its owner (§10, decision 6); the notification is taken
22//!   down.
23//! - **A task its owner finished or cancelled** while the job still failed
24//!   ends the incident; the job's next failure opens a new one, and the next
25//!   success still takes its notification down.
26//! - **A late report that changes a run's outcome** moves the cursor back to
27//!   it (`job_run_report`), so it is judged again: a success reported failed
28//!   reopens the incident it recovered, or opens one.
29//!
30//! Only the instance that has the cron job (its shared store lists it) moves
31//! an incident: the owner is resolved from the job, and the notification is
32//! on that instance. Another channel that followed a run (#1988) only says
33//! the job changed. Skips (paused, Pause all) are never decisive, so they
34//! neither fail nor recover a job; a cap skip has its own once-a-day alert
35//! (`cap_alert.rs`), and a run stopped at its cap (`over_budget`) is a failure
36//! like any other. Cron jobs only: a Drone graph is run by hand, from a pane that
37//! shows its failure already.
38
39use std::collections::BTreeSet;
40use std::sync::{Arc, Weak};
41
42use agentmux_common::time::now_ms;
43use serde_json::json;
44
45use super::verdict::run_failed;
46use crate::backend::mps::Broker;
47use crate::backend::reactive::sanitize::quote_in_system_note;
48use crate::backend::storage::cron::CronJob;
49use crate::backend::storage::job_incidents::{IncidentCursor, JobIncident};
50use crate::backend::storage::job_runs::{infra, reason, state, JobRun};
51use crate::backend::storage::store::Store;
52use crate::backend::storage::work_board::{requested, NewCard, WorkEvent};
53use crate::backend::storage::work_queue::{work_state, WorkItem};
54
55/// The task's `kind`, and who files it (`created_by`, `filed_by`, the
56/// history's actor).
57pub const TASK_KIND: &str = "job-failure";
58pub const FILED_BY: &str = "jobs";
59
60/// The most runs one look at a job walks; the rest wait for the next.
61pub const PASS_MAX: i64 = 500;
62
63/// How often every job is looked at even without a nudge: a run another
64/// channel closed, or reported, reaches the owner this way at the latest.
65pub const SWEEP_MS: u64 = 5 * 60 * 1000;
66
67/// The notification's group: one per job.
68pub fn notify_key(job_id: &str) -> String {
69    format!("job:{job_id}")
70}
71
72/// Who an incident's alerts go to (§3.4): the owning leader, resolved when
73/// the incident opens. `None` when no agent resolves: the operator alone is
74/// told, and the task waits in the backlog for anyone.
75#[derive(Debug, Clone, PartialEq, Eq)]
76pub struct Leader {
77    pub uid: String,
78    pub name: String,
79}
80
81/// What one decisive run did to the job's incident.
82#[derive(Debug, Clone, PartialEq)]
83pub enum Step {
84    /// The first failure: an incident, its task, and the alert.
85    Opened { incident: JobIncident, leader: Option<Leader>, note: String, notify_body: String },
86    /// Another failure of the open incident: `count` in a row.
87    FailedAgain { count: i64 },
88    /// The job succeeded again after failing.
89    Recovered,
90    /// A run judged a success, which recovered `incident`, was reported
91    /// failed later: the incident is open again, its notification back up.
92    Reopened { incident: JobIncident, count: i64 },
93}
94
95/// What one walk over a job's runs did: the steps it took, whether it
96/// stopped at [`PASS_MAX`] with more to take, and the error it stopped at.
97#[derive(Default)]
98struct Walked {
99    steps: Vec<Step>,
100    more: bool,
101    error: Option<crate::backend::storage::StoreError>,
102}
103
104/// The incident keeper: one per instance, beside the run ledger.
105pub struct Incidents {
106    /// The identity store: the ledger, its incidents and the work queue.
107    store: Arc<Store>,
108    /// The channel's object store: agent definitions, to resolve the owning
109    /// leader and name it.
110    mstore: Option<Arc<Store>>,
111    /// Where jobs are (`db_jobs`, the shared store): which jobs this
112    /// instance has, and their owners.
113    jobs: Option<Arc<Store>>,
114    broker: Arc<Broker>,
115    queue: std::sync::OnceLock<tokio::sync::mpsc::UnboundedSender<String>>,
116    /// Tests: applying this run fails, as a store error would.
117    #[cfg(any(test, feature = "test-support"))]
118    fail_on: std::sync::Mutex<Option<String>>,
119    /// Tests: run once when this run is applied, after the walk read it.
120    #[cfg(any(test, feature = "test-support"))]
121    on_apply: std::sync::Mutex<Option<(String, Box<dyn FnOnce() + Send>)>>,
122    /// Tests: the notification router, once there is one: what it was sent.
123    #[cfg(any(test, feature = "test-support"))]
124    router: std::sync::Mutex<Option<Vec<(String, String, String)>>>,
125}
126
127impl Incidents {
128    /// A keeper that acts only when [`Self::assess`] is called.
129    pub fn new(store: Arc<Store>, mstore: Option<Arc<Store>>, jobs: Option<Arc<Store>>, broker: Arc<Broker>) -> Arc<Self> {
130        Arc::new(Incidents {
131            store,
132            mstore,
133            jobs,
134            broker,
135            queue: std::sync::OnceLock::new(),
136            #[cfg(any(test, feature = "test-support"))]
137            fail_on: std::sync::Mutex::new(None),
138            #[cfg(any(test, feature = "test-support"))]
139            on_apply: std::sync::Mutex::new(None),
140            #[cfg(any(test, feature = "test-support"))]
141            router: std::sync::Mutex::new(None),
142        })
143    }
144
145    /// Look at each nudged job, and every job each [`SWEEP_MS`], on a task
146    /// of its own, one at a time, off the caller's thread: a nudge comes from
147    /// inside the ledger's writes. Needs a tokio runtime; without one,
148    /// nudges do nothing.
149    pub fn start(self: &Arc<Self>) {
150        let Ok(rt) = tokio::runtime::Handle::try_current() else { return };
151        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<String>();
152        if self.queue.set(tx).is_err() {
153            return;
154        }
155        let weak: Weak<Incidents> = Arc::downgrade(self);
156        rt.spawn(async move {
157            let mut sweep = tokio::time::interval(std::time::Duration::from_millis(SWEEP_MS));
158            sweep.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
159            loop {
160                let mut due = BTreeSet::new();
161                tokio::select! {
162                    got = rx.recv() => match got {
163                        Some(job_id) => {
164                            due.insert(job_id);
165                        }
166                        None => return,
167                    },
168                    _ = sweep.tick() => {
169                        let Some(me) = weak.upgrade() else { return };
170                        due.extend(tokio::task::spawn_blocking(move || me.owned_jobs()).await.unwrap_or_default());
171                    }
172                }
173                while let Ok(more) = rx.try_recv() {
174                    due.insert(more);
175                }
176                for job_id in due {
177                    let Some(me) = weak.upgrade() else { return };
178                    let _ = tokio::task::spawn_blocking(move || me.assess(&job_id)).await;
179                }
180            }
181        });
182    }
183
184    /// Job `job_id`'s runs changed: look at it soon.
185    pub fn nudge(&self, job_id: &str) {
186        if let Some(tx) = self.queue.get() {
187            let _ = tx.send(job_id.to_string());
188        }
189    }
190
191    /// The cron jobs this instance has, and the cloud jobs the operator approved.
192    fn owned_jobs(&self) -> Vec<String> {
193        let cloud = crate::backend::job_templates::service().map(|t| t.approved_clouds()).unwrap_or_default().into_iter().map(|t| t.id);
194        self.jobs.as_ref().and_then(|s| s.cron_list().ok()).unwrap_or_default().into_iter().map(|j| j.id).chain(cloud).collect()
195    }
196
197    /// An approved cloud job as the keeper reads a job: its id, its name and its owner (an agent's name or id in the
198    /// manifest, resolved here), which is all an incident needs of it.
199    fn cloud_job(&self, job_id: &str) -> Option<CronJob> {
200        let template = crate::backend::job_templates::service()?.approved_cloud(job_id)?;
201        let owner = template
202            .manifest
203            .owner
204            .as_deref()
205            .and_then(|o| self.mstore.as_ref().and_then(|m| crate::backend::agent_resolve::resolve_agent_id(m, o).ok()))
206            .unwrap_or_default();
207        Some(CronJob { id: template.id, name: template.manifest.name, owner, ..Default::default() })
208    }
209
210    /// Look at job `job_id` now: walk its decisive runs since the last look,
211    /// and act on each. Blocking. A job this instance doesn't have is left
212    /// to the one that has it.
213    pub fn assess(&self, job_id: &str) -> Vec<Step> {
214        let cron = self.jobs.as_ref().and_then(|s| s.cron_get(job_id).ok().flatten());
215        let Some(job) = cron.or_else(|| self.cloud_job(job_id)) else {
216            return Vec::new();
217        };
218        let walked = self.walk(&job);
219        for step in &walked.steps {
220            match step {
221                Step::Opened { incident, leader: Some(leader), note, .. } => self.note_leader(incident, leader, note),
222                Step::Opened { .. } | Step::FailedAgain { .. } | Step::Reopened { .. } => {}
223                Step::Recovered => {
224                    if let Some(router) = crate::backend::notify::router::get(&self.broker) {
225                        router.resolve(&notify_key(job_id), crate::backend::notify::policy::Family::Job);
226                    }
227                }
228            }
229        }
230        // An incident opened, or reopened, while no router existed (srv
231        // starting, no window yet) is notified at a later look.
232        self.notify_pending(job_id);
233        if let Some(e) = &walked.error {
234            // The run it stopped at is taken again at the next look.
235            tracing::warn!(job_id, error = %e, "jobs: couldn't judge an incident");
236        }
237        if !walked.steps.is_empty() {
238            self.changed(job_id);
239        }
240        if walked.more {
241            self.nudge(job_id);
242        }
243        walked.steps
244    }
245
246    /// Apply the job's decisive runs after its cursor, one at a time, moving
247    /// the cursor past each only once it is applied: an error stops the walk
248    /// at that run, for the next look to take again, and the steps already
249    /// taken are kept. Applying a run twice changes nothing
250    /// (`db_job_incident_runs`), so two keepers, or a report that moved the
251    /// cursor back, are safe. With no cursor yet, only the newest run
252    /// counts, so a job's history from before this build opens nothing.
253    fn walk(&self, job: &CronJob) -> Walked {
254        let mut walked = Walked::default();
255        let now = now_ms();
256        let started = self.end_if_task_closed(&job.id, now).and_then(|_| {
257            let cursor = self.store.job_incident_cursor(&job.id)?;
258            let after = cursor.as_ref().map(|c| (c.ended_at_ms, c.run_id.as_str()));
259            let runs = self.store.job_runs_decisive_after(&job.id, after, PASS_MAX)?;
260            Ok((cursor, runs))
261        });
262        let (mut cursor, runs) = match started {
263            Ok(got) => got,
264            Err(e) => {
265                walked.error = Some(e);
266                return walked;
267            }
268        };
269        walked.more = runs.len() as i64 >= PASS_MAX;
270        for run in runs {
271            if run.job_source == super::SOURCE_CRON || run.job_source == super::SOURCE_CLOUD {
272                match self.apply(job, &run, now) {
273                    Ok(step) => walked.steps.extend(step),
274                    Err(e) => {
275                        walked.error = Some(e);
276                        walked.more = false;
277                        return walked;
278                    }
279                }
280            }
281            let next = IncidentCursor { ended_at_ms: run.ended_at_ms.unwrap_or_default(), run_id: run.id.clone() };
282            match self.store.job_incident_cursor_advance(&job.id, cursor.as_ref(), &next, &run.outcome) {
283                Ok(true) => cursor = Some(next),
284                // Another keeper moved it, a report moved it back, or a
285                // report changed this run while it was applied: the next
286                // look reads it again.
287                Ok(false) => {
288                    walked.more = false;
289                    return walked;
290                }
291                Err(e) => {
292                    walked.error = Some(e);
293                    walked.more = false;
294                    return walked;
295                }
296            }
297        }
298        walked
299    }
300
301    /// End the job's open incident when its task was finished or cancelled.
302    /// `true` when it did.
303    fn end_if_task_closed(&self, job_id: &str, now: i64) -> Result<bool, crate::backend::storage::StoreError> {
304        match self.store.job_incident_open_for(job_id)? {
305            Some(open) if self.task_closed(&open.work_id) => self.store.job_incident_end_task_closed(&open.id, now),
306            _ => Ok(false),
307        }
308    }
309
310    /// What one decisive run does to the job's incident.
311    fn apply(&self, job: &CronJob, run: &JobRun, now: i64) -> Result<Option<Step>, crate::backend::storage::StoreError> {
312        #[cfg(any(test, feature = "test-support"))]
313        {
314            if self.fail_on.lock().unwrap().as_deref() == Some(run.id.as_str()) {
315                return Err(crate::backend::storage::StoreError::NotFound);
316            }
317            let hook = {
318                let mut slot = self.on_apply.lock().unwrap();
319                if slot.as_ref().is_some_and(|(id, _)| *id == run.id) { slot.take() } else { None }
320            };
321            if let Some((_, f)) = hook {
322                f();
323            }
324        }
325        if !run_failed(run) {
326            let recovered = self.store.job_incidents_recover(&job.id, &run.id, now)?;
327            if recovered.is_empty() {
328                return Ok(None);
329            }
330            let at = run.ended_at_ms.unwrap_or(now);
331            for inc in &recovered {
332                let streak = if inc.failures == 1 { "1 failure".to_string() } else { format!("{} failures in a row", inc.failures) };
333                self.history(&inc.work_id, &format!("recovered at {}: the job's last run succeeded, after {streak}", clock(at)));
334            }
335            return Ok(Some(Step::Recovered));
336        }
337        if self.store.job_incident_run_counted(&run.id)? {
338            return Ok(None);
339        }
340        // Judged a success before, it recovered an incident: a report says it
341        // failed after all, so that incident goes on, unless its task was
342        // finished or cancelled since: then this failure opens a new one,
343        // with a task someone can act on.
344        if let Some(inc) = self.store.job_incident_recovered_by(&job.id, &run.id)? {
345            if !self.task_closed(&inc.work_id) {
346                if let Some(count) = self.store.job_incident_reopen(&inc.id, &run.id, now)? {
347                    self.link_run(&run.id, &inc);
348                    let line = format!("failed after all: the run of {} reported it failed, {count} in a row", clock(failed_at(run)));
349                    self.history(&inc.work_id, &line);
350                    return Ok(Some(Step::Reopened { incident: inc, count }));
351                }
352            }
353        }
354        self.end_if_task_closed(&job.id, now)?;
355        let Some(inc) = self.store.job_incident_open_for(&job.id)? else { return self.open(job, run, now) };
356        let Some(count) = self.store.job_incident_fail_again(&inc.id, &inc.last_run_id, &run.id, now)? else {
357            return Ok(None);
358        };
359        self.link_run(&run.id, &inc);
360        if worth_a_line(count) {
361            let line = format!("failed again at {} ({}), {count} in a row", clock(failed_at(run)), failure_words(run));
362            self.history(&inc.work_id, &line);
363        }
364        Ok(Some(Step::FailedAgain { count }))
365    }
366
367    fn open(&self, job: &CronJob, run: &JobRun, now: i64) -> Result<Option<Step>, crate::backend::storage::StoreError> {
368        let leader = self.leader(job);
369        let mut incident = JobIncident {
370            id: uuid::Uuid::new_v4().to_string(),
371            job_id: run.job_id.clone(),
372            job_source: run.job_source.clone(),
373            job_name: run.job_name.clone(),
374            owner_uid: leader.as_ref().map(|l| l.uid.clone()).unwrap_or_default(),
375            first_run_id: run.id.clone(),
376            last_run_id: run.id.clone(),
377            failures: 1,
378            opened_at_ms: now,
379            last_failed_at_ms: now,
380            notified: false,
381            ..Default::default()
382        };
383        if !self.store.job_incident_open(&incident)? {
384            return Ok(None);
385        }
386        match self.file_task(run, leader.as_ref(), now) {
387            Ok((work_id, num)) => {
388                self.store.job_incident_set_task(&incident.id, &work_id, num)?;
389                incident.work_id = work_id;
390                incident.task_num = Some(num);
391                self.link_run(&run.id, &incident);
392            }
393            Err(e) => tracing::warn!(job_id = %run.job_id, error = %e, "jobs: couldn't file an incident's task"),
394        }
395        let note = note_text(run, incident.task_num);
396        let notify_body = notify_body(run, incident.task_num);
397        Ok(Some(Step::Opened { incident, leader, note, notify_body }))
398    }
399
400    /// The owning leader of `job` (§3.4): its owner (the cron job's
401    /// creator), that owner's lead when it has a seat with one or is a
402    /// spawned worker, else the owner itself.
403    fn leader(&self, job: &CronJob) -> Option<Leader> {
404        owning_leader(self.mstore.as_ref(), job)
405    }
406
407    /// File the incident's task, as `kanban.act` `create` does: the queue
408    /// row, its card, and its first history line.
409    fn file_task(&self, run: &JobRun, leader: Option<&Leader>, now: i64) -> Result<(String, i64), crate::backend::storage::StoreError> {
410        let item = WorkItem {
411            id: uuid::Uuid::new_v4().to_string(),
412            title: task_title(run),
413            payload: task_body(run),
414            kind: TASK_KIND.to_string(),
415            target_agent: leader.map(|l| l.name.clone()).unwrap_or_default(),
416            target_group: String::new(),
417            priority: 0,
418            state: String::new(),
419            claimed_by: String::new(),
420            target_agent_uid: leader.map(|l| l.uid.clone()).unwrap_or_default(),
421            claimed_by_uid: String::new(),
422            claim_expires: None,
423            attempts: 0,
424            max_attempts: 3,
425            created_by: FILED_BY.to_string(),
426            created_by_uid: String::new(),
427            created_at: now,
428            updated_at: now,
429            not_before: None,
430            result: String::new(),
431        };
432        self.store.work_queue_enqueue(&item)?;
433        let card = NewCard {
434            review_required: false,
435            requested_by: FILED_BY.to_string(),
436            requested_by_kind: requested::OTHER.to_string(),
437            filed_by: FILED_BY.to_string(),
438            ..Default::default()
439        };
440        let num = self.store.work_card_create(&item.id, &card, now)?;
441        let event = WorkEvent {
442            work_id: item.id.clone(),
443            at: now,
444            actor: FILED_BY.to_string(),
445            actor_kind: "system".to_string(),
446            kind: "created".to_string(),
447            to_state: work_state::OPEN.to_string(),
448            ..Default::default()
449        };
450        self.store.work_event_add(&event)?;
451        Ok((item.id, num))
452    }
453
454    /// Whether the incident's task was finished or cancelled (or is gone).
455    fn task_closed(&self, work_id: &str) -> bool {
456        if work_id.is_empty() {
457            return false;
458        }
459        match self.store.work_queue_get(work_id) {
460            Ok(Some(t)) => matches!(t.state.as_str(), work_state::DONE | work_state::CANCELLED | work_state::FAILED),
461            Ok(None) => true,
462            Err(_) => false,
463        }
464    }
465
466    /// A line in the task's history, from `jobs`.
467    fn history(&self, work_id: &str, body: &str) {
468        if work_id.is_empty() {
469            return;
470        }
471        let event = WorkEvent {
472            work_id: work_id.to_string(),
473            at: now_ms(),
474            actor: FILED_BY.to_string(),
475            actor_kind: "system".to_string(),
476            kind: "updated".to_string(),
477            body: body.to_string(),
478            ..Default::default()
479        };
480        if let Err(e) = self.store.work_event_add(&event) {
481            tracing::warn!(work_id, error = %e, "jobs: couldn't add to an incident's task");
482        }
483    }
484
485    /// The run's `links.kanban_task`: the incident's task.
486    fn link_run(&self, run_id: &str, incident: &JobIncident) {
487        let Some(num) = incident.task_num else { return };
488        let link = json!({ "kanban_task": { "id": incident.work_id, "num": num } });
489        if let Err(e) = self.store.job_run_add_links(run_id, &link) {
490            tracing::warn!(run_id, error = %e, "jobs: couldn't link a run to its incident");
491        }
492    }
493
494    /// The `[AgentMux]` note to the owning leader.
495    fn note_leader(&self, incident: &JobIncident, leader: &Leader, note: &str) {
496        if let Err(e) = crate::backend::reactive::get_global_handler().deliver_system_note(&leader.uid, note) {
497            tracing::info!(job_id = %incident.job_id, error = %e, "jobs: the owning leader didn't get the incident note");
498        }
499    }
500
501    /// Send the operator the open incident's notification, if it hasn't
502    /// reached a router yet, and mark it sent only once one took it.
503    fn notify_pending(&self, job_id: &str) {
504        let Ok(Some(inc)) = self.store.job_incident_open_for(job_id) else { return };
505        if inc.notified {
506            return;
507        }
508        let Some(run) = self.store.job_run_get(&inc.last_run_id).ok().flatten() else { return };
509        if !self.notify(&notify_key(job_id), &inc.job_name, notify_body(&run, inc.task_num)) {
510            tracing::info!(job_id, "jobs: no notification router yet; the incident is notified at a later look");
511            return;
512        }
513        if let Err(e) = self.store.job_incident_mark_notified(&inc.id) {
514            tracing::warn!(job_id, error = %e, "jobs: couldn't mark an incident notified");
515        }
516    }
517
518    /// Hand a `JobFailed` notification to this instance's router. `false`
519    /// when there is none yet.
520    fn notify(&self, key: &str, job_name: &str, body: String) -> bool {
521        #[cfg(any(test, feature = "test-support"))]
522        {
523            let mut router = self.router.lock().unwrap();
524            return match router.as_mut() {
525                Some(sent) => {
526                    sent.push((key.to_string(), job_name.to_string(), body));
527                    true
528                }
529                None => false,
530            };
531        }
532        #[cfg(not(any(test, feature = "test-support")))]
533        match crate::backend::notify::router::get(&self.broker) {
534            Some(router) => {
535                router.job_failed(key, job_name, body);
536                true
537            }
538            None => false,
539        }
540    }
541
542    /// Tell the Jobs tab and the Kanban.
543    fn changed(&self, job_id: &str) {
544        let event = crate::backend::mps_events::JobsChangedEvent { job_id: job_id.to_string() };
545        self.broker.publish_event::<crate::backend::mps_events::JobsChanged>(&event, vec![], 0);
546        self.broker.publish_event::<crate::backend::mps_events::WorkQueueChanged>(&(), vec![], 0);
547    }
548}
549
550/// The owning leader of `job` (§3.4): its owner (the cron job's creator),
551/// that owner's lead when it has a seat with one or is a spawned worker, else
552/// the owner itself. `None` when the job has no owner, or none resolves.
553pub fn owning_leader(mstore: Option<&Arc<Store>>, job: &CronJob) -> Option<Leader> {
554    let owner = job.owner_uid();
555    if owner.is_empty() {
556        return None;
557    }
558    let mstore = mstore?;
559    let name_of = |uid: &str| mstore.agent_def_get(uid).ok().flatten().map(|d| d.name);
560    let lead = crate::backend::agent_seat::effective_seat_by_id(mstore, owner).and_then(|s| s.lead);
561    let uid = lead.filter(|l| name_of(l).is_some()).unwrap_or_else(|| owner.to_string());
562    let name = name_of(&uid)?;
563    Some(Leader { uid, name })
564}
565
566/// Whether the `count`th failure in a row gets a line in the task's history:
567/// the first five, then 10, 20, 50, 100, 200, 500… A job failing every
568/// minute would otherwise write 1,440 lines a day; the incident keeps the
569/// exact count, and the Jobs tab every run.
570pub fn worth_a_line(count: i64) -> bool {
571    if count <= 5 {
572        return true;
573    }
574    let mut n = count;
575    while n % 10 == 0 {
576        n /= 10;
577    }
578    matches!(n, 1 | 2 | 5)
579}
580
581/// When the run failed: when it ended, else when it started.
582fn failed_at(run: &JobRun) -> i64 {
583    run.ended_at_ms.unwrap_or(run.started_at_ms)
584}
585
586/// `HH:MM UTC`, as a fire's brief line says times.
587fn clock(at_ms: i64) -> String {
588    chrono::DateTime::from_timestamp_millis(at_ms).map(|t| t.format("%H:%M UTC").to_string()).unwrap_or_default()
589}
590
591/// How the run failed, in a few words of AgentMux's own (never the run's
592/// summary): for titles, notes and the notification.
593pub fn failure_words(run: &JobRun) -> String {
594    if run.state == state::MISSED || run.state == "lost" || (run.state == state::PENDING && run.reason == reason::EXPIRED) {
595        return match run.reason.as_str() {
596            reason::TARGET_STOPPED => "missed: its agent wasn't running".to_string(),
597            reason::EXPIRED => "missed: its agent didn't come back before the next run".to_string(),
598            reason::NO_REPORT if run.state == state::MISSED => "missed: no report came in for it".to_string(),
599            reason::NOT_STARTED if run.state == state::MISSED => "missed: the scheduler never started it".to_string(),
600            _ if run.state == "lost" => "lost: it stopped reporting".to_string(),
601            _ => "missed".to_string(),
602        };
603    }
604    match run.infra.as_str() {
605        infra::ERROR => return "it couldn't be delivered or ran into an error".to_string(),
606        "timeout" => return "it timed out".to_string(),
607        "over_budget" => return "it reached its spending cap".to_string(),
608        infra::INTERRUPTED => return "it was interrupted".to_string(),
609        _ => {}
610    }
611    if run.outcome == "failed" {
612        return "its agent reported it failed".to_string();
613    }
614    "failed".to_string()
615}
616
617/// The task's title: the job's name and how it failed.
618pub fn task_title(run: &JobRun) -> String {
619    format!("Job failed: {} ({})", one_line(&run.job_name), failure_words(run))
620}
621
622fn one_line(text: &str) -> String {
623    text.split_whitespace().collect::<Vec<_>>().join(" ")
624}
625
626fn when(at_ms: i64) -> String {
627    chrono::DateTime::from_timestamp_millis(at_ms).map(|t| t.format("%Y-%m-%d %H:%M UTC").to_string()).unwrap_or_default()
628}
629
630/// The task's body: the failing run's state, reason, infrastructure and
631/// outcome, its summary (the agent's words, as data), its links, and where
632/// the job's history is.
633pub fn task_body(run: &JobRun) -> String {
634    let mut lines = vec![format!("The job \"{}\" failed: {}.", one_line(&run.job_name), failure_words(run)), String::new()];
635    lines.push(format!("Run {}", run.id));
636    if let Some(slot) = run.scheduled_for_ms {
637        lines.push(format!("- Due: {}", when(slot)));
638    }
639    lines.push(format!("- Started: {}", when(run.started_at_ms)));
640    let reason = if run.reason.is_empty() { String::new() } else { format!(" ({})", run.reason) };
641    lines.push(format!("- State: {}{reason}", run.state));
642    if !run.infra.is_empty() {
643        lines.push(format!("- Infrastructure: {}", run.infra));
644    }
645    lines.push(format!("- Outcome: {}", run.outcome));
646    if !run.summary.is_empty() {
647        lines.push(format!("- Summary, as the run reported it: {}", one_line(&run.summary)));
648    }
649    if let Some(block) = run.links.pointer("/transcript/block_id").and_then(|v| v.as_str()) {
650        lines.push(format!("- Transcript: the agent pane {block} (History)"));
651    }
652    if let Some(reported) = run.links.get("reported").and_then(|v| v.as_array()) {
653        for link in reported.iter().take(5) {
654            let url = link.as_str().or_else(|| link.get("url").and_then(|u| u.as_str())).unwrap_or("");
655            if url.starts_with("https://") {
656                lines.push(format!("- Link: {url}"));
657            }
658        }
659    }
660    lines.push(String::new());
661    lines.push(format!(
662        "Every run of the job is in Warden > Jobs > {}. While the job keeps failing, each failure is added to this \
663         task's history; its next success adds \"recovered\", and the task stays open for you to finish.",
664        one_line(&run.job_name)
665    ));
666    lines.join("\n")
667}
668
669/// The `[AgentMux]` note to the owning leader (§3.4). The job's name is
670/// quoted: an agent named it.
671pub fn note_text(run: &JobRun, task_num: Option<i64>) -> String {
672    let task = task_num.map(|n| format!(" Kanban #{n} is yours to look into.")).unwrap_or_default();
673    format!(
674        "[AgentMux] Job \"{}\" failed at {} ({}).{task} Its runs are in Warden > Jobs.",
675        quote_in_system_note(&run.job_name),
676        clock(failed_at(run)),
677        failure_words(run)
678    )
679}
680
681/// The notification's body: fixed text and the reason, never the summary.
682pub fn notify_body(run: &JobRun, task_num: Option<i64>) -> String {
683    let words = failure_words(run);
684    let mut first = words.chars();
685    let words = first.next().map(|c| c.to_uppercase().chain(first).collect::<String>()).unwrap_or_default();
686    match task_num {
687        Some(n) => format!("{words}. Kanban #{n}."),
688        None => format!("{words}."),
689    }
690}
691
692#[cfg(test)]
693#[path = "incidents_tests.rs"]
694mod tests;