Skip to main content

agentmux_srv/server/
cron.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! HTTP handlers for jobs (docs/specs/SPEC_JOBS_AND_TEMPLATES_2026_10_24.md
5//! §5.1) and the persistent cron scheduler under them.
6//!
7//! Routes (all auth-gated via `X-AuthKey`), under `/agentmux/jobs`, and the
8//! same under `/agentmux/cron`, kept as aliases for one release:
9//!   POST   /agentmux/jobs          — create a job: a job definition
10//!                                    (`jobVersion` 1), or the cron shape
11//!                                    the Schedule tool sends
12//!   DELETE /agentmux/jobs/:id      — delete a job
13//!   GET    /agentmux/jobs          — list all jobs, each with its last run
14//!   PATCH  /agentmux/jobs/:id      — pause / resume, or edit its definition
15//!   GET    /agentmux/jobs/:id/runs — a job's runs, newest first
16//!   POST   /agentmux/jobs/:id/run  — run it now (a `manual` run)
17//!   POST   /agentmux/jobs/runs/:run_id/report — a run's own verdict
18//!
19//! The run routes are the run ledger's (§3.2, §3.3 MuxAPI). Who may do what
20//! is §7: [`Who`].
21
22
23use axum::extract::{Path, Query, State};
24use axum::http::StatusCode;
25use axum::response::Json;
26use chrono::Utc;
27use serde::{Deserialize, Serialize};
28use serde_json::{json, Map, Value};
29use uuid::Uuid;
30
31use crate::backend::cron::schedule::JobSchedule;
32use crate::backend::cron::FireOutcome;
33use crate::backend::jobs;
34use crate::backend::jobs::definition::{Action, Check, JobDefinition, LATER};
35use super::job_caps::{self, Origin};
36use crate::backend::storage::cron::CronJob;
37use crate::backend::storage::job_runs::{JobRun, OUTCOMES};
38use crate::backend::storage::store::Store;
39use std::sync::Arc;
40use super::caller::Caller;
41use super::AppState;
42
43#[derive(Debug, Deserialize)]
44pub struct CronCreateRequest {
45    pub name: String,
46    /// 5-field cron expression: "min hour dom mon dow", read in `tz`.
47    pub expression: String,
48    pub prompt: String,
49    /// Target agent id. Required — no implicit self-targeting from HTTP.
50    pub target: String,
51    /// Identity M3: the target's UID, resolved at the MCP boundary (spec
52    /// §5.4 — resolution at authoring time) and CARRIED here. Absent → the
53    /// job fires by `target`, counted.
54    #[serde(default)]
55    pub target_uid: String,
56    #[serde(default)]
57    pub created_by: String,
58    pub max_fires: Option<i64>,
59    /// Hard expiry bound in seconds since creation. Optional — omit for no
60    /// expiry (matching native CronCreate's 7-day default is a caller
61    /// choice, not enforced here; AgentMux's cross-agent jobs are often
62    /// meant to run indefinitely, e.g. a recurring standup check).
63    #[serde(default)]
64    pub max_age_secs: Option<i64>,
65    /// What an undelivered fire leaves (jobs spec §5.2): `skip` (default) or
66    /// `latest`. The same as `policy.catch_up`; this one wins.
67    #[serde(default)]
68    pub catch_up: Option<String>,
69    /// The expression's IANA time zone; UTC when absent.
70    #[serde(default)]
71    pub tz: Option<String>,
72    /// The definition's `policy` (§5.1).
73    #[serde(default)]
74    pub policy: Option<Value>,
75    /// A template to create the job from: refused until templates land.
76    #[serde(default)]
77    pub template: Option<Value>,
78    #[serde(default)]
79    pub params: Option<Value>,
80}
81
82#[derive(Debug, Serialize)]
83pub struct CronJobView {
84    pub id: String,
85    pub name: String,
86    pub expression: String,
87    /// The cron expression's time zone (`UTC` unless it says otherwise).
88    pub tz: String,
89    pub trigger_kind: String,
90    pub action_kind: String,
91    pub prompt: String,
92    pub target: String,
93    pub enabled: bool,
94    pub last_fired: Option<i64>,
95    pub fire_count: i64,
96    pub max_fires: Option<i64>,
97    pub created_at: i64,
98    pub max_age_secs: Option<i64>,
99    /// Seconds remaining before `max_age_secs` expiry, computed server-side
100    /// (clamped to 0, never negative) so callers don't need their own clock/
101    /// date-math to display something meaningful — `None` when there's no
102    /// `max_age_secs` bound. Fixes a review finding on the first cut of this
103    /// field: the MCP CLI was printing the raw `max_age_secs` bound under an
104    /// "expires_in" label, which is only correct at the instant of creation.
105    pub expires_in_secs: Option<i64>,
106    /// ISO-8601 string of the next scheduled fire (UTC), or null if disabled
107    /// or there is none.
108    pub next_fire: Option<String>,
109    pub catch_up: String,
110    /// The job's newest run in the ledger, if it has one.
111    pub last_run: Option<JobRun>,
112    /// Scheduled fires that reached no one, and the last one's time and
113    /// reason (`CronJob::missed_count`).
114    pub missed_count: i64,
115    pub last_missed_at: Option<i64>,
116    pub last_miss_reason: String,
117    /// The cap its runs are over today (`job_cap`, `account_cap` or
118    /// `message_cap`), if any; they resume at the operator's next midnight.
119    #[serde(skip_serializing_if = "Option::is_none")]
120    pub over_cap: Option<String>,
121    /// The whole job definition (§5.1).
122    pub definition: JobDefinition,
123}
124
125fn to_view(job: &CronJob) -> CronJobView {
126    let expires_in_secs = job.max_age_secs.map(|max_age| {
127        let elapsed = Utc::now().timestamp() - job.created_at;
128        (max_age - elapsed).max(0)
129    });
130    let definition = JobDefinition::from_job(job);
131    CronJobView {
132        id: job.id.clone(),
133        name: job.name.clone(),
134        expression: job.expression.clone(),
135        tz: if job.tz.is_empty() { "UTC".to_string() } else { job.tz.clone() },
136        trigger_kind: definition.trigger.kind().to_string(),
137        action_kind: definition.action.kind().to_string(),
138        prompt: job.prompt.clone(),
139        target: job.target.clone(),
140        enabled: job.enabled,
141        last_fired: job.last_fired,
142        fire_count: job.fire_count,
143        max_fires: job.max_fires,
144        created_at: job.created_at,
145        expires_in_secs,
146        max_age_secs: job.max_age_secs,
147        next_fire: next_fire(job),
148        catch_up: job.catch_up.clone(),
149        last_run: None,
150        missed_count: job.missed_count,
151        last_missed_at: job.last_missed_at,
152        last_miss_reason: job.last_miss_reason.clone(),
153        over_cap: None,
154        definition,
155    }
156}
157
158/// The job's next fire (its trigger's next slot, in its time zone) as an
159/// ISO-8601 UTC string; `None` when disabled, when its trigger has no next
160/// slot, or when it doesn't read.
161fn next_fire(job: &CronJob) -> Option<String> {
162    if !job.enabled {
163        return None;
164    }
165    let next = JobSchedule::of(job).ok()?.next_after(agentmux_common::time::now_ms())?;
166    Some(chrono::DateTime::from_timestamp_millis(next)?.to_rfc3339())
167}
168
169/// Swarm-pane row shape for one cron job (SPEC_SWARM_LONG_RUNNING_PROCESS_
170/// ROWS_2026_07_20 Phase 2) — `CronJobView` plus the `created_by` agent's
171/// resolved `block_id`, so the frontend can group it under that agent's row
172/// the same way `ShellSummary` does for the Shell bucket.
173#[derive(Debug, Serialize)]
174pub struct CronSummary {
175    pub id: String,
176    pub block_id: String,
177    pub name: String,
178    pub expression: String,
179    pub target: String,
180    pub created_by: String,
181    pub enabled: bool,
182    pub last_fired: Option<i64>,
183    pub fire_count: i64,
184    pub max_fires: Option<i64>,
185    /// ISO-8601 string of the next scheduled fire (UTC), or null if disabled.
186    pub next_fire: Option<String>,
187    /// Scheduled fires that reached no one; Swarm's Cron bucket shows them.
188    pub missed_count: i64,
189    pub last_miss_reason: String,
190}
191
192pub(crate) fn to_summary(job: &CronJob, block_id: String) -> CronSummary {
193    CronSummary {
194        id: job.id.clone(),
195        block_id,
196        name: job.name.clone(),
197        expression: job.expression.clone(),
198        target: job.target.clone(),
199        created_by: job.created_by.clone(),
200        enabled: job.enabled,
201        last_fired: job.last_fired,
202        fire_count: job.fire_count,
203        max_fires: job.max_fires,
204        next_fire: next_fire(job),
205        missed_count: job.missed_count,
206        last_miss_reason: job.last_miss_reason.clone(),
207    }
208}
209
210/// Where jobs are (`db_jobs`): the shared store, beside the `db_cron_jobs`
211/// it replaced, or the work store of a `task dev` build, which keeps its own
212/// (`crate::registry::work_store`). Every job read and write goes through here,
213/// so the store can move in one place.
214pub(crate) fn jobs_store(state: &AppState) -> Option<Arc<Store>> {
215    state.cron_store.clone()
216}
217
218/// Where the run ledger is (`db_job_runs`): the identity store, or the work store of
219/// a `task dev` build, which keeps its own (`crate::registry::work_store`).
220///
221/// A known limit: a dev build's job that delivers to an agent in a shared build has
222/// its run in the dev ledger only, so the receiver's `follow_forwarded` finds no row
223/// and the run closes by the no-turn timeout with an unknown cost. The message is
224/// still delivered. Reading a missing cost on such a test job as a bug would be wrong.
225pub(crate) fn ledger_store(state: &AppState) -> Arc<Store> {
226    state.work_store.clone()
227}
228
229/// Tests: keep jobs in the test state's own store (which carries every
230/// schema), as [`jobs_store`] and [`ledger_store`] would find them.
231#[cfg(test)]
232pub(crate) fn use_test_store_for_jobs(state: &mut AppState) {
233    state.cron_store = Some(state.mstore.clone());
234}
235
236/// Where tasks are filed (the work queue and its cards): the identity store, or
237/// the work store of a `task dev` build, which keeps its own.
238pub(crate) fn work_store(state: &AppState) -> Arc<Store> {
239    state.work_store.clone()
240}
241
242/// [`jobs_store`], or the answer when there is none.
243fn jobs_store_or_503(state: &AppState) -> Result<Arc<Store>, Answer> {
244    jobs_store(state).ok_or_else(|| (StatusCode::SERVICE_UNAVAILABLE, Json(json!({"error": "shared store unavailable"}))))
245}
246
247fn publish_cron_changed(state: &AppState) {
248    state.broker.publish_event::<crate::backend::mps_events::CronChanged>(&(), vec![], 0);
249}
250
251/// Who is asking, for the rules of §7. The operator is the app's own
252/// client, which carries no agent token (`Caller::Unattributed`).
253#[derive(Debug, Clone, PartialEq, Eq)]
254pub(crate) enum Who {
255    Operator,
256    Agent { uid: String, slug: String, container: bool },
257}
258
259/// Who stands behind a definition this request writes, as the request proves it: the app's own window, an agent by its
260/// token, or no one (a caller nothing identified, which the rest of this file treats as the operator but cannot prove is).
261/// A scheduled fire of the job is proven only as far as this goes (`CronJob::fire_proof`).
262fn writer_of(from_host: bool, caller: Option<&Caller>) -> String {
263    if from_host {
264        return crate::backend::storage::cron::WRITER_OPERATOR.to_string();
265    }
266    match caller.and_then(Caller::uid) {
267        Some(uid) => uid.to_string(),
268        None => crate::backend::storage::cron::WRITER_UNKNOWN.to_string(),
269    }
270}
271
272fn who(state: &AppState, caller: Option<&Caller>) -> Who {
273    match caller.and_then(Caller::uid) {
274        None => Who::Operator,
275        Some(uid) => {
276            let def = state.mstore.agent_def_get(uid).ok().flatten();
277            Who::Agent {
278                uid: uid.to_string(),
279                slug: def.as_ref().map(|d| d.slug.clone()).unwrap_or_default(),
280                container: def.is_some_and(|d| d.runtime().is_container()),
281            }
282        }
283    }
284}
285
286/// What a container agent is told for a job whose runs start things on the
287/// host (§7): the only jobs it can't have, as it can't start or run anything
288/// there. It says why and what to do instead.
289const CONTAINER_HOST_JOB: &str = "a container agent can't schedule a job that starts workers or runs a Drone, because its runs start things on the host: schedule a message or task job instead, or ask your leader to create this one";
290
291fn forbidden(why: impl Into<String>) -> Answer {
292    (StatusCode::FORBIDDEN, Json(json!({"error": why.into()})))
293}
294
295fn bad_request(why: impl Into<String>) -> Answer {
296    (StatusCode::BAD_REQUEST, Json(json!({"error": why.into()})))
297}
298
299/// Whether a job of this `action_kind` is one a container agent can't run
300/// now or have scheduled: a spawn or Drone job starts things on the host.
301fn starts_on_the_host(action_kind: &str) -> bool {
302    matches!(action_kind, "spawn" | "drone")
303}
304
305/// Whether `who` may define a job like `def` (§7): the operator any job; an
306/// agent, container or not, a `message` or `task` job it owns; a native agent
307/// a Drone job too, which a container agent can't have as its runs start on
308/// the host. A `spawn` job needs the operator's approval once (the spawn
309/// consent rule, made at creation since its runs are unattended), which has
310/// no flow yet, so an agent can't create one. `current_owner` is the job's
311/// owner on an edit.
312pub(crate) fn may_define(who: &Who, def: &JobDefinition, current_owner: Option<&str>) -> Result<(), String> {
313    let Who::Agent { uid, container, .. } = who else { return Ok(()) };
314    if *container && matches!(def.action, Action::Spawn { .. } | Action::Drone { .. }) {
315        return Err(CONTAINER_HOST_JOB.to_string());
316    }
317    if let Action::Spawn { leader, .. } = &def.action {
318        if leader != uid {
319            return Err("an agent can create a spawn job only with itself as the leader".to_string());
320        }
321        return Err(
322            "a spawn job an agent creates needs the operator's approval once, which isn't available yet: ask the operator to create it"
323                .to_string(),
324        );
325    }
326    let owner = def.owner.trim();
327    let allowed = owner.is_empty() || owner == uid || current_owner == Some(owner);
328    if !allowed {
329        return Err("an agent's job is owned by that agent: leave owner out, or name yourself".to_string());
330    }
331    Ok(())
332}
333
334/// What this build can't run yet, though the definition is valid. Refused
335/// rather than stored and silently ignored: `max_turns` is a flag at the CLI's
336/// launch, which a message to a running agent can't set.
337pub(crate) fn runnable_yet(def: &JobDefinition) -> Result<(), String> {
338    match def.policy.max_turns {
339        Some(_) => Err(format!("policy.max_turns is {LATER}")),
340        None => Ok(()),
341    }
342}
343
344/// What a spawn job asks of anyone who isn't the app's own controls: it
345/// starts agents that spend until someone stops them.
346const SPAWN_FROM_THE_APP: &str =
347    "a spawn job starts workers that spend until stopped: only the operator's own host creates and runs it, not this route";
348
349/// A message's `to` as the job's target `(name, uid)`: a UID names that
350/// agent; anything else is kept as a name, never resolved here (identity
351/// spec §5.4: the job then fires by name, counted).
352fn target_of(state: &AppState, to: &str) -> (String, String) {
353    match state.mstore.agent_def_get(to) {
354        Ok(Some(def)) if !to.is_empty() => (def.slug, to.to_string()),
355        _ => {
356            if !to.is_empty() {
357                crate::backend::agent_resolve::record_uid_fallback("jobs_create.uid_not_carried");
358            }
359            (to.to_string(), String::new())
360        }
361    }
362}
363
364/// The definition the cron shape describes: a `cron` trigger in `tz` and a
365/// `message` action to the target.
366fn legacy_definition(req: &CronCreateRequest, check: Check) -> Result<JobDefinition, String> {
367    let mut policy = match &req.policy {
368        None | Some(Value::Null) => Map::new(),
369        Some(Value::Object(p)) => p.clone(),
370        Some(_) => return Err("policy is an object".to_string()),
371    };
372    if let Some(catch_up) = &req.catch_up {
373        if catch_up != jobs::CATCH_UP_SKIP && catch_up != jobs::CATCH_UP_LATEST {
374            return Err(format!("invalid catch_up '{catch_up}' (use 'skip' or 'latest')"));
375        }
376        policy.insert("catch_up".into(), json!(catch_up));
377    }
378    let to = if req.target_uid.trim().is_empty() { req.target.trim() } else { req.target_uid.trim() };
379    let mut def = json!({
380        "jobVersion": jobs::definition::JOB_VERSION,
381        "name": req.name,
382        "trigger": { "kind": "cron", "cron": req.expression, "tz": req.tz.as_deref().unwrap_or("UTC") },
383        "action": { "kind": "message", "to": to, "brief": req.prompt },
384        "policy": policy,
385    });
386    for (key, value) in [("template", &req.template), ("params", &req.params)] {
387        if let Some(v) = value.as_ref().filter(|v| !v.is_null()) {
388            def[key] = v.clone();
389        }
390    }
391    jobs::from_template::apply(&mut def, None)?;
392    JobDefinition::parse(&def, check)
393}
394
395pub(super) async fn handle_cron_create(
396    State(state): State<AppState>,
397    caller: Option<axum::Extension<super::caller::Caller>>,
398    Json(body): Json<Value>,
399) -> (StatusCode, Json<Value>) {
400    create_job(&state, caller.as_deref(), body, Origin::default())
401}
402
403/// Create a job from a definition or the cron shape. `origin.from_host`: the
404/// operator's decision, from the host route (`handle_host_jobs`) or the
405/// app's own proven window (`jobs.save`): the only way to create a job that
406/// starts workers, to raise a cap, or to confirm a job on a provider that
407/// reports no cost. A definition that names a template is made from it
408/// (`jobs::from_template`).
409pub(crate) fn create_job(state: &AppState, caller: Option<&Caller>, body: Value, origin: Origin) -> (StatusCode, Json<Value>) {
410    let from_host = origin.from_host;
411    let check = Check { fresh: true, now_ms: agentmux_common::time::now_ms() };
412    let who = if from_host { Who::Operator } else { who(state, caller) };
413    // The cron shape (no `jobVersion`) carries its target, creator and limits
414    // beside the definition.
415    let legacy = match body.get("jobVersion") {
416        Some(_) => None,
417        None => match serde_json::from_value::<CronCreateRequest>(body.clone()) {
418            Ok(req) => Some(req),
419            Err(e) => return bad_request(format!("invalid job: {e}")),
420        },
421    };
422    let parsed = match &legacy {
423        Some(req) => {
424            super::actor::check_actor(state, caller, super::actor::ActorSite::CronCreate, Some(&req.created_by));
425            legacy_definition(req, check)
426        }
427        None => {
428            let mut body = body.clone();
429            jobs::from_template::apply(&mut body, None).and_then(|()| JobDefinition::parse(&body, check))
430        }
431    };
432    let mut def = match parsed {
433        Ok(def) => def,
434        Err(e) => return bad_request(e),
435    };
436    if let Err(e) = may_define(&who, &def, None) {
437        return forbidden(e);
438    }
439    if matches!(def.action, Action::Spawn { .. }) && !from_host {
440        return forbidden(SPAWN_FROM_THE_APP);
441    }
442    if let Err(e) = runnable_yet(&def) {
443        return bad_request(e);
444    }
445    if let Err(stop) = super::drone_turn_on::allowed(state, &def, origin, true) {
446        return stop.answer();
447    }
448    let notes = match job_caps::apply_rules(state, &mut def, None, origin) {
449        Ok(notes) => notes,
450        Err(refused) => return refused,
451    };
452
453    let (created_by, owner) = match &who {
454        Who::Operator => (jobs::BY_OPERATOR.to_string(), def.owner.trim().to_string()),
455        Who::Agent { uid, slug, .. } => (if slug.is_empty() { uid.clone() } else { slug.clone() }, uid.clone()),
456    };
457    let mut job = CronJob {
458        id: Uuid::new_v4().to_string(),
459        created_by,
460        // Identity M4c-1 (§6.5.9): the creator's UID is the request's
461        // `Caller` — its token — never a body field; `""` when Unattributed.
462        created_by_uid: super::caller::attributed_uid(caller),
463        last_written_by: writer_of(from_host, caller),
464        created_at: Utc::now().timestamp(),
465        ..Default::default()
466    };
467    match &legacy {
468        Some(req) => {
469            // Identity M3: the target's UID is stored only if the caller
470            // CARRIED one, resolved at the boundary where the name was typed
471            // (spec §5.4). A named target with no carried UID keeps firing by
472            // name until M5, counted.
473            let target_uid = req.target_uid.trim().to_string();
474            if target_uid.is_empty() && !req.target.trim().is_empty() {
475                crate::backend::agent_resolve::record_uid_fallback("cron_create.uid_not_carried");
476            }
477            def.apply_to(&mut job, &|_| (req.target.clone(), target_uid.clone()));
478            job.created_by = req.created_by.clone();
479            (job.max_fires, job.max_age_secs) = (req.max_fires, req.max_age_secs);
480        }
481        None => def.apply_to(&mut job, &|to| target_of(state, to)),
482    }
483    // An agent's job is its own (§7); the operator's has the owner it names.
484    job.owner = owner;
485
486    let store = match jobs_store_or_503(state) {
487        Ok(store) => store,
488        Err(e) => return e,
489    };
490    if let Err(e) = store.cron_create(&job) {
491        return (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": e.to_string()})));
492    }
493
494    // Register the new job with the live scheduler.
495    if job.enabled {
496        state.cron_scheduler.schedule_job(&job);
497    }
498    publish_cron_changed(state);
499
500    (StatusCode::CREATED, Json(json!({"job": to_view(&job), "notes": notes})))
501}
502
503pub(super) async fn handle_cron_list(
504    State(state): State<AppState>,
505) -> (StatusCode, Json<Value>) {
506    let store = match jobs_store_or_503(&state) {
507        Ok(store) => store,
508        Err(e) => return e,
509    };
510    match store.cron_list() {
511        Ok(jobs) => {
512            let ledger = state.cron_scheduler.runs().cloned();
513            let (views, paused_all) = tokio::task::spawn_blocking(move || {
514                let views = jobs
515                    .iter()
516                    .map(|job| {
517                        let mut view = to_view(job);
518                        view.last_run = ledger.as_ref().and_then(|l| l.store().job_run_last(&job.id).ok().flatten());
519                        view.over_cap = ledger.as_ref().and_then(|l| l.over_cap_today(job)).map(str::to_string);
520                        view
521                    })
522                    .collect::<Vec<_>>();
523                // Pause all (jobs spec §3.3), so the Schedule tool can say so.
524                (views, ledger.as_ref().and_then(|l| l.paused_all()))
525            })
526            .await
527            .unwrap_or_default();
528            (StatusCode::OK, Json(json!({"jobs": views, "paused_all": paused_all})))
529        }
530        Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": e.to_string()}))),
531    }
532}
533
534/// Whether `caller` may act on `job` (Run now): the operator (the app's own
535/// client, which carries no agent token) or the agent that created or owns
536/// it (jobs spec §7). By UID when the job recorded one, else by the
537/// creator's name against the caller's agent slug.
538fn may_act_on(state: &AppState, caller: Option<&Caller>, job: &CronJob) -> bool {
539    let Some(uid) = caller.and_then(Caller::uid) else {
540        return true;
541    };
542    if job.owner_uid() == uid {
543        return true;
544    }
545    if !job.created_by_uid.is_empty() {
546        return job.created_by_uid == uid;
547    }
548    match state.mstore.agent_def_get(uid) {
549        // The person's own mark on a job is never an agent's slug, whatever the agent is called.
550        Ok(Some(def)) => {
551            !job.created_by.is_empty()
552                && !job.created_by.eq_ignore_ascii_case(jobs::BY_OPERATOR)
553                && def.slug.eq_ignore_ascii_case(&job.created_by)
554        }
555        _ => false,
556    }
557}
558
559#[derive(Debug, Deserialize)]
560pub struct CronRunsQuery {
561    #[serde(default)]
562    pub limit: Option<i64>,
563    /// Page: runs started before this (ms epoch).
564    #[serde(default)]
565    pub before: Option<i64>,
566}
567
568/// The most runs one history call returns.
569const RUNS_MAX: i64 = 200;
570
571type Answer = (StatusCode, Json<Value>);
572
573fn ledger_or_503(state: &AppState) -> Result<std::sync::Arc<jobs::RunLedger>, Answer> {
574    state
575        .cron_scheduler
576        .runs()
577        .cloned()
578        .ok_or_else(|| (StatusCode::SERVICE_UNAVAILABLE, Json(json!({"error": "run ledger unavailable"}))))
579}
580
581/// Deliver on this instance (`jekt_files::inject_here`). A delivery another
582/// instance forwarded here whose `request_id` is a run another channel
583/// fired is followed here, before the answer goes back (#1988).
584pub(super) async fn inject_here_following_runs(
585    state: &AppState,
586    req: &crate::backend::reactive::types::InjectionRequest,
587) -> crate::backend::reactive::types::InjectionResponse {
588    let delivery_started = agentmux_common::time::now_ms();
589    let resp = super::jekt_files::inject_here(state, req);
590    let run_id = req.request_id.clone().unwrap_or_default();
591    let block_id = resp.block_id.clone().unwrap_or_default();
592    if resp.success && req.forward_hops > 0 && !run_id.is_empty() && !block_id.is_empty() {
593        if let Some(ledger) = state.cron_scheduler.runs().cloned() {
594            let _ = tokio::task::spawn_blocking(move || ledger.follow_forwarded(&run_id, &block_id, delivery_started)).await;
595        }
596    }
597    resp
598}
599
600pub(super) async fn handle_cron_runs(
601    State(state): State<AppState>,
602    Path(id): Path<String>,
603    Query(q): Query<CronRunsQuery>,
604) -> Answer {
605    let ledger = match ledger_or_503(&state) {
606        Ok(l) => l,
607        Err(e) => return e,
608    };
609    let limit = q.limit.unwrap_or(20).clamp(1, RUNS_MAX);
610    match tokio::task::spawn_blocking(move || ledger.store().job_runs_for_job(&id, limit, q.before)).await {
611        Ok(Ok(runs)) => (StatusCode::OK, Json(json!({"runs": runs}))),
612        Ok(Err(e)) => (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": e.to_string()}))),
613        Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": e.to_string()}))),
614    }
615}
616
617pub(super) async fn handle_cron_run_now(
618    State(state): State<AppState>,
619    caller: Option<axum::Extension<Caller>>,
620    Path(id): Path<String>,
621) -> Answer {
622    let store = match jobs_store_or_503(&state) {
623        Ok(store) => store,
624        Err(e) => return e,
625    };
626    let job = match store.cron_get(&id) {
627        Ok(Some(job)) => job,
628        Ok(None) => return (StatusCode::NOT_FOUND, Json(json!({"error": "job not found"}))),
629        Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": e.to_string()}))),
630    };
631    if !may_act_on(&state, caller.as_deref(), &job) {
632        return (
633            StatusCode::FORBIDDEN,
634            Json(json!({"error": "only the agent that created this job, or the operator, can run it now"})),
635        );
636    }
637    if starts_on_the_host(&job.action_kind) && matches!(who(&state, caller.as_deref()), Who::Agent { container: true, .. }) {
638        return forbidden(CONTAINER_HOST_JOB);
639    }
640    if job.action_kind == "spawn" {
641        return forbidden(SPAWN_FROM_THE_APP);
642    }
643    let triggered_by =
644        caller.as_deref().and_then(Caller::uid).map(str::to_string).unwrap_or_else(|| jobs::BY_OPERATOR.to_string());
645    run_job_now(&state, &job, &triggered_by).await
646}
647
648/// Run `job` now and say how it went.
649async fn run_job_now(state: &AppState, job: &CronJob, triggered_by: &str) -> Answer {
650    let fired = state.cron_scheduler.run_now(job, triggered_by).await;
651    if let Some(why) = fired.waiting {
652        let body = json!({"run_id": fired.run_id, "outcome": "queued", "error": null, "waiting_for": why});
653        return (StatusCode::OK, Json(body));
654    }
655    let (outcome, error) = match &fired.outcome {
656        Some(FireOutcome::Delivered { .. }) => ("delivered", None),
657        Some(FireOutcome::Missed { .. }) => ("missed", Some(format!("agent {} is not running", job.target))),
658        Some(FireOutcome::Failed { error }) => ("failed", Some(error.clone())),
659        None => ("failed", Some("no way to deliver".to_string())),
660    };
661    (StatusCode::OK, Json(json!({"run_id": fired.run_id, "outcome": outcome, "error": error})))
662}
663
664/// `POST /api/v1/host/jobs`: what the operator decides in the Jobs tab that
665/// starts agents, relayed by the host with its own token. `action` is
666/// `create` (`definition`: a job definition, a `spawn` job included),
667/// `update` (`id`, `fields`: an edit, which may raise the job's caps) or
668/// `run_now` (`id`). `confirm_no_cost: true` confirms a job whose agent's
669/// provider reports no cost (§5.3).
670pub(crate) async fn handle_host_jobs(
671    State(state): State<AppState>,
672    headers: axum::http::HeaderMap,
673    Json(body): Json<Value>,
674) -> axum::response::Response {
675    use axum::response::IntoResponse;
676    if !super::ui_handlers::from_host(&state, &headers).await {
677        return forbidden("only the AgentMux host can create, change or run a job that starts workers, or raise a spending cap").into_response();
678    }
679    let origin = Origin {
680        from_host: true,
681        confirm_no_cost: body.get("confirm_no_cost").and_then(Value::as_bool) == Some(true),
682        confirm_turn_on: body.get("confirm_turn_on").and_then(Value::as_bool) == Some(true),
683    };
684    match body.get("action").and_then(Value::as_str).unwrap_or("") {
685        "create" => create_job(&state, None, body.get("definition").cloned().unwrap_or(Value::Null), origin).into_response(),
686        "update" => {
687            let id = body.get("id").and_then(Value::as_str).unwrap_or("");
688            patch_job(&state, None, id, body.get("fields").cloned().unwrap_or(Value::Null), origin).into_response()
689        }
690        "run_now" => {
691            let id = body.get("id").and_then(Value::as_str).unwrap_or("");
692            let store = match jobs_store_or_503(&state) {
693                Ok(store) => store,
694                Err(e) => return e.into_response(),
695            };
696            match store.cron_get(id) {
697                Ok(Some(job)) => run_job_now(&state, &job, jobs::BY_OPERATOR).await.into_response(),
698                Ok(None) => (StatusCode::NOT_FOUND, Json(json!({"error": "job not found"}))).into_response(),
699                Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": e.to_string()}))).into_response(),
700            }
701        }
702        other => bad_request(format!("unknown action {other:?} (use create, update or run_now)")).into_response(),
703    }
704}
705
706#[derive(Debug, Deserialize)]
707pub struct CronReportRequest {
708    /// `ok`, `findings` or `failed`.
709    pub outcome: String,
710    #[serde(default)]
711    pub summary: String,
712    /// Up to five links (strings or `{label, url}`), kept as given.
713    #[serde(default)]
714    pub links: Option<Value>,
715}
716
717/// The most links one report keeps, and the longest url and label.
718const REPORT_LINKS_MAX: usize = 5;
719const REPORT_URL_MAX: usize = 2048;
720const REPORT_LABEL_MAX: usize = 120;
721
722/// The links a report keeps: https URLs, given as strings or as
723/// `{label, url}`, within the length bounds, at most five. Anything else is
724/// dropped: the ledger shows them to other agents and the UI.
725fn report_links(given: Option<Value>) -> Value {
726    let https = |u: &str| u.len() <= REPORT_URL_MAX && u.starts_with("https://") && u.len() > "https://".len();
727    let items = match given {
728        None | Some(Value::Null) => return Value::Null,
729        Some(Value::Array(items)) => items,
730        Some(other) => vec![other],
731    };
732    let kept: Vec<Value> = items
733        .into_iter()
734        .filter_map(|item| match item {
735            Value::String(u) if https(&u) => Some(Value::String(u)),
736            Value::Object(o) => {
737                let url = o.get("url").and_then(Value::as_str).filter(|u| https(u))?;
738                let label = o.get("label").and_then(Value::as_str).unwrap_or("");
739                (label.chars().count() <= REPORT_LABEL_MAX).then(|| json!({ "label": label, "url": url }))
740            }
741            _ => None,
742        })
743        .take(REPORT_LINKS_MAX)
744        .collect();
745    Value::Array(kept)
746}
747
748pub(super) async fn handle_cron_report(
749    State(state): State<AppState>,
750    caller: Option<axum::Extension<Caller>>,
751    Path(run_id): Path<String>,
752    Json(req): Json<CronReportRequest>,
753) -> Answer {
754    if req.outcome == "unknown" || !OUTCOMES.contains(&req.outcome.as_str()) {
755        return (
756            StatusCode::BAD_REQUEST,
757            Json(json!({"error": format!("invalid outcome '{}' (use ok, findings or failed)", req.outcome)})),
758        );
759    }
760    let links = report_links(req.links);
761    let ledger = match ledger_or_503(&state) {
762        Ok(l) => l,
763        Err(e) => return e,
764    };
765    let run = match ledger.store().job_run_get(&run_id) {
766        Ok(Some(run)) => run,
767        Ok(None) => return (StatusCode::NOT_FOUND, Json(json!({"error": "run not found"}))),
768        Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": e.to_string()}))),
769    };
770    // The agent that ran it reports; so may the job's creator, or the operator.
771    // A run whose receiver's UID couldn't be resolved at delivery is
772    // reported only from the pane that took it, never by another agent.
773    let allowed = match caller.as_deref().and_then(Caller::uid) {
774        None => true,
775        Some(uid) => {
776            let ran_it = if run.target_agent_uid.is_empty() {
777                !run.block_id.is_empty() && state.reactive_handler.block_for_uid(uid).as_deref() == Some(run.block_id.as_str())
778            } else {
779                run.target_agent_uid == uid
780            };
781            ran_it
782                || jobs_store(&state)
783                    .and_then(|s| s.cron_get(&run.job_id).ok().flatten())
784                    .is_some_and(|job| may_act_on(&state, caller.as_deref(), &job))
785        }
786    };
787    if !allowed {
788        return (StatusCode::FORBIDDEN, Json(json!({"error": "only the agent that ran this run can report it"})));
789    }
790    match ledger.store().job_run_report(&run_id, &req.outcome, &req.summary, &links) {
791        Ok(true) => {
792            ledger.changed(&run.job_id);
793            (StatusCode::OK, Json(json!({"ok": true, "run_id": run_id, "outcome": req.outcome})))
794        }
795        Ok(false) => (
796            StatusCode::CONFLICT,
797            Json(json!({"error": format!("run {run_id} never ran ({}): there is nothing to report", run.state)})),
798        ),
799        Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": e.to_string()}))),
800    }
801}
802
803/// Whether `caller` may pause, resume or delete `job`. An agent (a request
804/// carrying its token) may change only a job it created or owns, or one
805/// aimed at it; everyone else, the UI included, may change any job.
806/// Unattributed requests can't be refused: at the same-user boundary one
807/// that omits its token looks like the UI (caller.rs). This stops an agent
808/// changing another agent's job by mistake, not a determined one. A job with
809/// no recorded creator UID (created before identity M4c-1, or unattributed)
810/// is open to any caller. Editing the definition is narrower: [`may_edit_job`].
811fn may_change_job(caller: Option<&super::caller::Caller>, job: &CronJob) -> bool {
812    let Some(uid) = caller.and_then(super::caller::Caller::uid) else {
813        return true;
814    };
815    job.created_by_uid.is_empty() || may_edit_job(caller, job) || job.target_uid == uid
816}
817
818/// Whether `caller` may edit `job`'s definition: the operator, or the agent
819/// that created or owns it (§7). The agent a job messages may pause it, not
820/// rewrite it. A job with no creator (the operator's, or one from before
821/// creators were recorded) is the operator's to edit.
822fn may_edit_job(caller: Option<&super::caller::Caller>, job: &CronJob) -> bool {
823    let Some(uid) = caller.and_then(super::caller::Caller::uid) else {
824        return true;
825    };
826    !uid.is_empty() && (job.created_by_uid == uid || job.owner_uid() == uid)
827}
828
829/// The store and the job, or the response refusing the change: no store, no
830/// such job, or a caller [`may_change_job`] refuses.
831fn job_for_change(
832    state: &AppState,
833    caller: Option<&super::caller::Caller>,
834    id: &str,
835) -> Result<(Arc<Store>, CronJob), Answer> {
836    let store = jobs_store_or_503(state)?;
837    match store.cron_get(id) {
838        Ok(Some(job)) if may_change_job(caller, &job) => Ok((store, job)),
839        Ok(Some(_)) => Err(forbidden("an agent can change only a scheduled job it created or one aimed at it")),
840        Ok(None) => Err((StatusCode::NOT_FOUND, Json(json!({"error": "job not found"})))),
841        Err(e) => Err((StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": e.to_string()})))),
842    }
843}
844
845pub(super) async fn handle_cron_delete(
846    State(state): State<AppState>,
847    caller: Option<axum::Extension<super::caller::Caller>>,
848    Path(id): Path<String>,
849) -> (StatusCode, Json<Value>) {
850    let store = match job_for_change(&state, caller.as_deref(), &id) {
851        Ok((store, _)) => store,
852        Err(refused) => return refused,
853    };
854
855    // Cancel live task first.
856    state.cron_scheduler.cancel_job(&id);
857
858    match store.cron_delete(&id) {
859        Ok(true) => {
860            publish_cron_changed(&state);
861            (StatusCode::OK, Json(json!({"ok": true})))
862        }
863        Ok(false) => (StatusCode::NOT_FOUND, Json(json!({"error": "job not found"}))),
864        Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": e.to_string()}))),
865    }
866}
867
868/// A job's fields an edit can't change: srv sets them.
869const FIXED_FIELDS: [&str; 3] = ["id", "jobVersion", "created_by"];
870
871/// `PATCH`: `{"action": "pause" | "resume"}`, or an edit: definition fields
872/// (§5.1) laid over the job's definition, which is then read as a create's
873/// is. The 15-minute minimum applies only when the edit sets the trigger or
874/// the action, so a job kept as it was isn't refused for a rule newer than
875/// it.
876pub(super) async fn handle_cron_patch(
877    State(state): State<AppState>,
878    caller: Option<axum::Extension<super::caller::Caller>>,
879    Path(id): Path<String>,
880    Json(body): Json<Value>,
881) -> (StatusCode, Json<Value>) {
882    patch_job(&state, caller.as_deref(), &id, body, Origin::default())
883}
884
885/// [`handle_cron_patch`]'s work. `origin.from_host`: the operator's edit,
886/// from the host route or the app's own proven window, which may raise caps,
887/// confirm a job on a provider that reports no cost, and change a spawn job.
888pub(crate) fn patch_job(state: &AppState, caller: Option<&Caller>, id: &str, body: Value, origin: Origin) -> (StatusCode, Json<Value>) {
889    let (store, job) = match job_for_change(state, caller, id) {
890        Ok(found) => found,
891        Err(refused) => return refused,
892    };
893    if let Some(action) = body.get("action").and_then(Value::as_str) {
894        return set_enabled(state, &store, id, action, origin);
895    }
896    let Some(fields) = body.as_object() else { return bad_request("an edit is a JSON object of job fields") };
897    if job.action_kind == "spawn" && !origin.from_host {
898        return forbidden("a spawn job can be paused, resumed or deleted here; to change it, delete it and create it again from the Jobs tab");
899    }
900    if !may_edit_job(caller, &job) {
901        return forbidden("an agent can edit only a job it created or owns");
902    }
903    let before = JobDefinition::from_job(&job);
904    let mut merged = serde_json::to_value(&before).unwrap_or_default();
905    for (key, value) in fields {
906        if FIXED_FIELDS.contains(&key.as_str()) {
907            if merged.get(key) != Some(value) {
908                return bad_request(format!("{key} can't be changed"));
909            }
910            continue;
911        }
912        merged[key.as_str()] = value.clone();
913    }
914    if jobs::from_template::edit_needs_render(fields, &before) {
915        if let Err(e) = jobs::from_template::apply(&mut merged, before.template.as_ref()) {
916            return bad_request(e);
917        }
918    }
919    let fresh = fields.contains_key("trigger") || fields.contains_key("action");
920    let mut def = match JobDefinition::parse(&merged, Check { fresh, now_ms: agentmux_common::time::now_ms() }) {
921        Ok(def) => def,
922        Err(e) => return bad_request(e),
923    };
924    let editor = if origin.from_host { Who::Operator } else { who(state, caller) };
925    if let Err(e) = may_define(&editor, &def, Some(job.owner_uid())) {
926        return forbidden(e);
927    }
928    if matches!(def.action, Action::Spawn { .. }) && !(origin.from_host && job.action_kind == "spawn") {
929        return forbidden(SPAWN_FROM_THE_APP);
930    }
931    if let Err(e) = runnable_yet(&def) {
932        return bad_request(e);
933    }
934    let asks = !before.enabled || fields.contains_key("action") || fields.contains_key("trigger");
935    if let Err(stop) = super::drone_turn_on::allowed(state, &def, origin, asks) {
936        return stop.answer();
937    }
938    let notes = match job_caps::apply_rules(state, &mut def, Some(&before), origin) {
939        Ok(notes) => notes,
940        Err(refused) => return refused,
941    };
942    let mut edited = job.clone();
943    // Whoever wrote this edit now stands behind the job: a fire of it is proven only as far as they were.
944    edited.last_written_by = writer_of(origin.from_host, caller);
945    if fields.contains_key("action") {
946        def.apply_to(&mut edited, &|to| target_of(state, to));
947    } else {
948        // The target as it was: a job by name keeps firing by name.
949        def.apply_to(&mut edited, &|_| (job.target.clone(), job.target_uid.clone()));
950    }
951    match store.cron_update_definition(&edited) {
952        Ok(true) => {}
953        Ok(false) => return (StatusCode::NOT_FOUND, Json(json!({"error": "job not found"}))),
954        Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": e.to_string()}))),
955    }
956    if edited.enabled {
957        state.cron_scheduler.schedule_job(&edited);
958    } else {
959        state.cron_scheduler.cancel_job(id);
960    }
961    publish_cron_changed(state);
962    (StatusCode::OK, Json(json!({"ok": true, "enabled": edited.enabled, "job": to_view(&edited), "notes": notes})))
963}
964
965/// Pause or resume job `id`.
966fn set_enabled(state: &AppState, store: &Store, id: &str, action: &str, origin: Origin) -> Answer {
967    let enabled = match action {
968        "resume" => true,
969        "pause" => false,
970        other => return bad_request(format!("unknown action '{other}' (use 'pause' or 'resume')")),
971    };
972    if enabled {
973        if let Ok(Some(job)) = store.cron_get(id) {
974            let mut def = JobDefinition::from_job(&job);
975            def.enabled = true;
976            if let Err(stop) = super::drone_turn_on::allowed(state, &def, origin, true) {
977                return stop.answer();
978            }
979        }
980    }
981    match store.cron_set_enabled(id, enabled) {
982        Ok(true) => {}
983        Ok(false) => return (StatusCode::NOT_FOUND, Json(json!({"error": "job not found"}))),
984        Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": e.to_string()}))),
985    }
986
987    if enabled {
988        if let Ok(Some(job)) = store.cron_get(id) {
989            state.cron_scheduler.schedule_job(&job);
990        }
991    } else {
992        state.cron_scheduler.cancel_job(id);
993    }
994    publish_cron_changed(state);
995
996    (StatusCode::OK, Json(json!({"ok": true, "enabled": enabled})))
997}
998
999#[cfg(test)]
1000mod tests {
1001    use super::*;
1002
1003    fn mk_job(enabled: bool, max_fires: Option<i64>, fire_count: i64) -> CronJob {
1004        CronJob {
1005            id: "job-1".to_string(),
1006            name: "nightly build".to_string(),
1007            expression: "0 9 * * *".to_string(),
1008            prompt: "run the build".to_string(),
1009            target: "target-agent".to_string(),
1010            target_uid: String::new(),
1011            created_by: "creator-agent".to_string(),
1012            created_by_uid: String::new(),
1013            enabled,
1014            last_fired: Some(1_700_000_000),
1015            fire_count,
1016            max_fires,
1017            created_at: 1_699_000_000,
1018            max_age_secs: None,
1019            catch_up: "skip".to_string(),
1020            ..Default::default()
1021        }
1022    }
1023
1024    /// Report links keep https URLs only, as strings or `{label, url}`,
1025    /// within the length bounds, at most five.
1026    #[test]
1027    fn report_links_keep_only_bounded_https_urls() {
1028        let long_url = format!("https://example.com/{}", "a".repeat(REPORT_URL_MAX));
1029        let given = json!([
1030            "https://example.com/pr/1",
1031            "http://example.com/plain",
1032            "javascript:alert(1)",
1033            "https://",
1034            {"label": "Report", "url": "https://example.com/r"},
1035            {"label": "x".repeat(REPORT_LABEL_MAX + 1), "url": "https://example.com/too-long-label"},
1036            {"label": "bad", "url": "ftp://example.com"},
1037            {"url": "https://example.com/no-label"},
1038            long_url,
1039            42,
1040            {"label": "nested", "url": {"href": "https://example.com"}},
1041        ]);
1042        assert_eq!(
1043            report_links(Some(given)),
1044            json!([
1045                "https://example.com/pr/1",
1046                {"label": "Report", "url": "https://example.com/r"},
1047                {"label": "", "url": "https://example.com/no-label"},
1048            ])
1049        );
1050        let many: Vec<Value> = (0..9).map(|i| json!(format!("https://example.com/{i}"))).collect();
1051        assert_eq!(report_links(Some(Value::Array(many))).as_array().unwrap().len(), REPORT_LINKS_MAX);
1052        assert_eq!(report_links(Some(json!("https://example.com/one"))), json!(["https://example.com/one"]));
1053        assert_eq!(report_links(None), Value::Null);
1054    }
1055
1056    #[test]
1057    fn a_definition_is_written_by_whoever_the_request_proves() {
1058        use super::super::caller::Caller;
1059        use crate::backend::storage::cron::{WRITER_OPERATOR, WRITER_UNKNOWN};
1060        let agent = Caller::Agent { uid: "uid-a".to_string() };
1061        // The app's own window, whatever else the request carries.
1062        assert_eq!(writer_of(true, None), WRITER_OPERATOR);
1063        assert_eq!(writer_of(true, Some(&Caller::Unattributed)), WRITER_OPERATOR);
1064        // An agent's token names the agent.
1065        assert_eq!(writer_of(false, Some(&agent)), "uid-a");
1066        // A caller nothing identified is not the operator, even though the rest of this file treats it as one.
1067        assert_eq!(writer_of(false, Some(&Caller::Unattributed)), WRITER_UNKNOWN);
1068        assert_eq!(writer_of(false, None), WRITER_UNKNOWN);
1069    }
1070
1071    #[test]
1072    fn an_agent_changes_only_its_own_jobs_or_ones_aimed_at_it() {
1073        use super::super::caller::Caller;
1074        let mut job = mk_job(true, None, 0);
1075        job.created_by_uid = "uid-creator".to_string();
1076        job.target_uid = "uid-target".to_string();
1077        let agent = |uid: &str| Caller::Agent { uid: uid.to_string() };
1078        assert!(may_change_job(Some(&agent("uid-creator")), &job));
1079        assert!(may_change_job(Some(&agent("uid-target")), &job), "the agent it pings may pause it");
1080        assert!(!may_change_job(Some(&agent("uid-other")), &job));
1081        // The UI and every other unattributed request can't be told apart: never refused.
1082        assert!(may_change_job(Some(&Caller::Unattributed), &job));
1083        assert!(may_change_job(None, &job));
1084        // A job with no recorded creator is open to any caller.
1085        job.created_by_uid.clear();
1086        assert!(may_change_job(Some(&agent("uid-other")), &job));
1087    }
1088
1089    #[tokio::test]
1090    async fn an_agent_called_operator_cannot_act_on_a_job_the_person_made() {
1091        use super::super::caller::Caller;
1092        let state = crate::server::tests::test_state();
1093        // Agents seeded directly: one with a reserved name (made before the rule), one with a nickname.
1094        let seed = |id: &str, slug: &str| {
1095            let mut def = crate::backend::storage::agents::test_agent_def(id, slug, "claude", "agent", 1, "");
1096            def.slug = slug.to_string();
1097            state.mstore.agent_def_insert(&mut def).unwrap();
1098            Caller::Agent { uid: id.to_string() }
1099        };
1100        let reserved = seed("uid-reserved", "operator");
1101        let nickname = seed("uid-nick", "creator-agent");
1102        let mut job = mk_job(true, None, 0);
1103        // A job the person made: the creator is `operator`, with no agent uid.
1104        job.created_by = "operator".to_string();
1105        assert!(!may_act_on(&state, Some(&reserved), &job), "an agent that is called operator is not the person");
1106        // A job an agent made, recorded by its slug before uids were kept, is still its own.
1107        job.created_by = "creator-agent".to_string();
1108        assert!(may_act_on(&state, Some(&nickname), &job));
1109        assert!(!may_act_on(&state, Some(&reserved), &job));
1110        // An agent whose slug is another reserved word, from before the rule, still acts on its own job.
1111        let legacy = seed("uid-legacy", "swarm");
1112        job.created_by = "swarm".to_string();
1113        assert!(may_act_on(&state, Some(&legacy), &job));
1114    }
1115
1116    #[test]
1117    fn views_carry_the_miss_record() {
1118        let mut job = mk_job(true, None, 2);
1119        job.missed_count = 3;
1120        job.last_missed_at = Some(1_700_000_100);
1121        job.last_miss_reason = "target_stopped".to_string();
1122        let view = to_view(&job);
1123        assert_eq!((view.missed_count, view.last_missed_at), (3, Some(1_700_000_100)));
1124        assert_eq!(view.last_miss_reason, "target_stopped");
1125        let summary = to_summary(&job, "block-1".to_string());
1126        assert_eq!((summary.missed_count, summary.last_miss_reason.as_str()), (3, "target_stopped"));
1127    }
1128
1129    #[test]
1130    fn to_summary_carries_the_resolved_block_id() {
1131        let job = mk_job(true, None, 3);
1132        let summary = to_summary(&job, "block-42".to_string());
1133        assert_eq!(summary.id, "job-1");
1134        assert_eq!(summary.block_id, "block-42");
1135        assert_eq!(summary.created_by, "creator-agent");
1136        assert_eq!(summary.fire_count, 3);
1137        assert_eq!(summary.max_fires, None);
1138    }
1139
1140    #[test]
1141    fn to_summary_omits_next_fire_when_disabled() {
1142        let job = mk_job(false, Some(5), 5);
1143        let summary = to_summary(&job, "block-1".to_string());
1144        assert!(!summary.enabled);
1145        assert_eq!(summary.next_fire, None);
1146    }
1147
1148    #[test]
1149    fn to_summary_computes_next_fire_when_enabled() {
1150        let job = mk_job(true, None, 0);
1151        let summary = to_summary(&job, "block-1".to_string());
1152        assert!(summary.enabled);
1153        assert!(summary.next_fire.is_some());
1154    }
1155}
1156
1157#[cfg(test)]
1158#[path = "cron_tests.rs"]
1159mod route_tests;