Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

fix(cron): judge agent-job frequency by the shortest gap and enforce the 5-minute floor

Shanu9fefbac26dbc
diff --git a/app/src/components/settings/panels/cron/CronJobFormModal.test.tsx b/app/src/components/settings/panels/cron/CronJobFormModal.test.tsx
index 2c184bf617..04ae67f9c7 100644
--- a/app/src/components/settings/panels/cron/CronJobFormModal.test.tsx
+++ b/app/src/components/settings/panels/cron/CronJobFormModal.test.tsx
@@ -279,7 +279,12 @@ describe('<CronJobFormModal />', () => {
expect(screen.getByTestId('cron-form-error')).toBeInTheDocument();
});
- expect(screen.getByTestId('cron-form-error')).toHaveTextContent('Failed to save job');
+ // The core's reason is shown alongside the generic label: a schedule
+ // rejected for being tighter than the agent floor must say so here, not
+ // only in the panel's status line behind the modal.
+ expect(screen.getByTestId('cron-form-error')).toHaveTextContent(
+ 'Failed to save job: network error'
+ );
});
// ── Create: "at" schedule ───────────────────────────────────────────
diff --git a/app/src/components/settings/panels/cron/CronJobFormModal.tsx b/app/src/components/settings/panels/cron/CronJobFormModal.tsx
index cd6671dbec..a354c0e576 100644
--- a/app/src/components/settings/panels/cron/CronJobFormModal.tsx
+++ b/app/src/components/settings/panels/cron/CronJobFormModal.tsx
@@ -287,7 +287,12 @@ const CronJobFormModal = ({
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
log('[CronJobFormModal] save error: %s', msg);
- setError(t('settings.cron.jobs.formError'));
+ // The core's reason (an invalid expression, an agent schedule tighter
+ // than the 5-minute floor, …) is the actionable part; the generic label
+ // alone would leave the user guessing what to change.
+ setError(
+ msg ? `${t('settings.cron.jobs.formError')}: ${msg}` : t('settings.cron.jobs.formError')
+ );
} finally {
setSaving(false);
}
diff --git a/docs/TEST-COVERAGE-MATRIX.md b/docs/TEST-COVERAGE-MATRIX.md
index 7e1ae09a44..0e497b4e68 100644
--- a/docs/TEST-COVERAGE-MATRIX.md
+++ b/docs/TEST-COVERAGE-MATRIX.md
@@ -381,7 +381,7 @@ End-to-end coverage of the agent harness via the web-chat RPC surface against an
| ID | Feature | Layer | Test path(s) | Status | Notes |
| ----- | -------------------------- | ----- | ------------------------ | ------ | ----- |
-| 9.2.1 | Cron Expression Validation | RU | `src/openhuman/cron/` | ✅ | |
+| 9.2.1 | Cron Expression Validation | RU | `src/openhuman/cron/` | ✅ | Incl. the 5-minute agent-job floor (`validate_agent_schedule`, #6158) |
| 9.2.2 | Recurring Execution | WD+RI | `cron-jobs-flow.spec.ts` | ✅ | |
### 9.3 Remote Execution
diff --git a/gitbooks/features/native-tools/cron.md b/gitbooks/features/native-tools/cron.md
index 4afb0a76eb..21d55717e8 100644
--- a/gitbooks/features/native-tools/cron.md
+++ b/gitbooks/features/native-tools/cron.md
@@ -20,6 +20,8 @@ Scheduling is a first-class capability, not a workaround. The agent can set up r
There's also a one-shot `schedule` tool in [System & Utilities](system-and-utilities.md) for "do this once at time T" cases that don't need a recurring entry.
+Agent jobs run a full model turn every time they fire, so they must be scheduled at least five minutes apart. `cron_add` and `cron_update` reject a tighter cron expression or `every_ms` for an agent job and say which two runs would be too close (`*/7 * * * *`, for instance, fires at :56 and again at :00). Shell jobs have no such floor.
+
## What it's good for
- Daily / weekly digests delivered to your messaging channel of choice.
diff --git a/src/openhuman/cron/README.md b/src/openhuman/cron/README.md
index 201d8e9219..ef3a3774cd 100644
--- a/src/openhuman/cron/README.md
+++ b/src/openhuman/cron/README.md
@@ -6,7 +6,7 @@ Scheduled-job runtime. Owns cron-expression and human-delay parsing, the persist
- `pub struct CronJob` / `pub struct CronJobPatch` / `pub struct CronRun` / `pub enum JobType` / `pub enum Schedule` / `pub enum SessionTarget` / `pub struct DeliveryConfig` — `types.rs:1-100` — durable job + run model.
- `pub fn add_once` / `pub fn add_once_at` / `pub fn parse_human_delay` / `pub fn pause_job` / `pub fn resume_job` / `pub fn update_cron_job` — `ops.rs` (re-exported `mod.rs:12`).
-- `pub fn schedule_cron_expression` / `pub fn next_run_for_schedule` / `pub fn normalize_expression` / `pub fn validate_schedule` — `schedule.rs` (re-exported `mod.rs:14-16`).
+- `pub fn schedule_cron_expression` / `pub fn next_run_for_schedule` / `pub fn normalize_expression` / `pub fn validate_schedule` / `pub fn validate_agent_schedule` / `pub fn runs_closer_than` / `pub const MIN_AGENT_JOB_INTERVAL` — `schedule.rs` (re-exported `mod.rs`).
- `pub fn add_job` / `pub fn add_agent_job` / `pub fn add_agent_job_with_definition` / `pub fn add_shell_job` / `pub fn due_jobs` / `pub fn get_job` / `pub fn list_jobs` / `pub fn list_runs` / `pub fn record_last_run` / `pub fn record_run` / `pub fn remove_job` / `pub fn reschedule_after_run` / `pub fn update_job` — `store.rs` (re-exported `mod.rs:22-26`).
- `pub mod scheduler` (`pub async fn run(config: Config)`) — `scheduler.rs:19` — main poll loop.
- `pub mod seed` — `seed.rs` — install built-in jobs on first launch.
@@ -50,6 +50,24 @@ non-web inbound turns instructs the model to default to `announce` with the
current channel + reply target — that is the routing path for the Telegram
"remind me to drink water" use case in #928.
+## Agent-job minimum interval
+
+An agent job is a full inference turn per run, so `schedule.rs` enforces a floor
+of `MIN_AGENT_JOB_INTERVAL` (5 minutes) between consecutive runs of an agent job.
+`validate_agent_schedule` is applied by `add_agent_job*` and by `update_job`
+whenever an agent job's schedule is set, so every creation path (`cron_add`
+tool, `cron.add` RPC, the one-shot `schedule` tool, the settings form) gets the
+same rejection, and the message names the two runs that would be too close.
+Shell and flow jobs are not subject to it.
+
+The check is `runs_closer_than`: it walks consecutive occurrences (bounded) and
+reports the first pair closer than the floor, so an irregular expression such as
+`1,2,30 * * * *` is judged by its tightest gap and the verdict does not depend
+on the instant it runs at. Wrap-around gaps count: `*/7 * * * *` fires at :56
+and then at :00. Rows that predate the floor keep running; the scheduler logs
+`Cron agent job '<id>' is scheduled more frequently than every 5 minutes` with
+that evidence on each run instead (#6158).
+
## Tests
- Unit: `ops_tests.rs`, `scheduler_tests.rs`, `store_tests.rs`.
diff --git a/src/openhuman/cron/mod.rs b/src/openhuman/cron/mod.rs
index 20a9868645..e469585786 100644
--- a/src/openhuman/cron/mod.rs
+++ b/src/openhuman/cron/mod.rs
@@ -17,7 +17,8 @@ pub use ops as rpc;
pub use ops::{add_once, add_once_at, parse_human_delay, pause_job, resume_job, update_cron_job};
#[allow(unused_imports)]
pub use schedule::{
- next_run_for_schedule, normalize_expression, schedule_cron_expression, validate_schedule,
+ next_run_for_schedule, normalize_expression, runs_closer_than, schedule_cron_expression,
+ validate_agent_schedule, validate_schedule, TooFrequent, MIN_AGENT_JOB_INTERVAL,
};
pub use schemas::{
all_controller_schemas as all_cron_controller_schemas,
diff --git a/src/openhuman/cron/schedule.rs b/src/openhuman/cron/schedule.rs
index e19362115d..263a41a422 100644
--- a/src/openhuman/cron/schedule.rs
+++ b/src/openhuman/cron/schedule.rs
@@ -2,8 +2,29 @@ use crate::openhuman::cron::{ActiveHours, Schedule};
use anyhow::{Context, Result};
use chrono::{DateTime, Duration as ChronoDuration, NaiveTime, Timelike, Utc};
use cron::Schedule as CronExprSchedule;
+use std::fmt;
use std::str::FromStr;
+/// The closest together two runs of an *agent* job may be scheduled. Every
+/// run is a full inference turn, so a tighter cadence is almost always a
+/// misconfiguration that bills accordingly. Shell and flow jobs are not
+/// subject to it. Enforced by [`validate_agent_schedule`] when an agent job is
+/// created or its schedule changed; the scheduler warns about rows that
+/// predate the rule.
+pub const MIN_AGENT_JOB_INTERVAL: ChronoDuration = ChronoDuration::minutes(5);
+
+/// Upper bound on cron candidates walked while looking for an occurrence that
+/// falls inside `active_hours`. `next_run_for_schedule` gets a fresh budget
+/// per call; a `runs_closer_than` scan shares one across all of its steps.
+const ACTIVE_WINDOW_CANDIDATE_LIMIT: usize = 100_000;
+
+/// How many consecutive occurrences [`runs_closer_than`] walks before it
+/// concludes a cron schedule keeps its distance. Every gap an hour- or
+/// day-periodic expression can produce shows up well inside this many runs
+/// (a schedule that respects a 5-minute floor fires at most 288 times a day),
+/// so the verdict does not depend on the instant the scan starts from.
+const RUN_GAP_SCAN_OCCURRENCES: usize = 1_000;
+
pub fn next_run_for_schedule(schedule: &Schedule, from: DateTime<Utc>) -> Result<DateTime<Utc>> {
match schedule {
Schedule::Cron {
@@ -11,38 +32,9 @@ pub fn next_run_for_schedule(schedule: &Schedule, from: DateTime<Utc>) -> Result
tz,
active_hours,
} => {
- let normalized = normalize_expression(expr)?;
- let cron = CronExprSchedule::from_str(&normalized)
- .with_context(|| format!("Invalid cron expression: {expr}"))?;
- let timezone = ScheduleTimeZone::parse(tz.as_deref())?;
- // Parsing is cheap; validated at job-creation time via validate_schedule.
- let active_window = active_hours.as_ref().map(ActiveWindow::parse).transpose()?;
-
- let mut current_from = from;
- for _ in 0..100_000 {
- let next_utc = timezone.next_after(&cron, current_from, expr)?;
-
- if let Some(active) = &active_window {
- let local_t = timezone.local_time_of_day(next_utc);
- if active.contains(local_t) {
- return Ok(next_utc);
- }
- tracing::debug!(
- "[cron] next_run candidate {} outside active window {}–{}, advancing",
- next_utc,
- active.start,
- active.end
- );
- current_from = next_utc;
- } else {
- return Ok(next_utc);
- }
- }
- tracing::warn!(
- "[cron] no occurrence found within active_hours for expr={} after 100,000 candidates",
- expr
- );
- anyhow::bail!("No future occurrence found within active hours after 100,000 attempts")
+ let plan = CronPlan::parse(expr, tz.as_deref(), active_hours.as_ref())?;
+ let mut budget = ACTIVE_WINDOW_CANDIDATE_LIMIT;
+ plan.next_after(from, &mut budget)
}
Schedule::At { at } => Ok(*at),
Schedule::Every { every_ms } => {
@@ -87,6 +79,124 @@ pub fn validate_schedule(schedule: &Schedule, now: DateTime<Utc>) -> Result<()>
}
}
+/// [`validate_schedule`] plus the agent-only floor: an agent job may not run
+/// closer together than [`MIN_AGENT_JOB_INTERVAL`]. The error names the two
+/// runs (or the fixed interval) that break the rule, so the caller — an agent
+/// using `cron_add`, or the settings form — can say exactly what to change.
+pub fn validate_agent_schedule(schedule: &Schedule, now: DateTime<Utc>) -> Result<()> {
+ validate_schedule(schedule, now)?;
+ if let Some(too_frequent) = runs_closer_than(schedule, now, MIN_AGENT_JOB_INTERVAL) {
+ anyhow::bail!(
+ "Invalid schedule: agent jobs must run at least {} apart, but this schedule {too_frequent}",
+ describe_gap(MIN_AGENT_JOB_INTERVAL)
+ );
+ }
+ Ok(())
+}
+
+/// Why a schedule runs more often than a threshold allows. Carries the
+/// evidence, not only the verdict, so a log line or an error can quote it.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum TooFrequent {
+ /// A fixed `every_ms` interval shorter than the threshold.
+ FixedInterval(ChronoDuration),
+ /// Two consecutive cron occurrences closer together than the threshold.
+ ConsecutiveRuns {
+ first: DateTime<Utc>,
+ second: DateTime<Utc>,
+ },
+}
+
+impl TooFrequent {
+ /// The offending gap.
+ pub fn gap(&self) -> ChronoDuration {
+ match self {
+ Self::FixedInterval(gap) => *gap,
+ Self::ConsecutiveRuns { first, second } => *second - *first,
+ }
+ }
+}
+
+impl fmt::Display for TooFrequent {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ match self {
+ Self::FixedInterval(gap) => write!(f, "fires every {}", describe_gap(*gap)),
+ Self::ConsecutiveRuns { first, second } => write!(
+ f,
+ "fires at {} and again at {}, {} apart",
+ first.format("%Y-%m-%d %H:%M:%S UTC"),
+ second.format("%Y-%m-%d %H:%M:%S UTC"),
+ describe_gap(*second - *first)
+ ),
+ }
+ }
+}
+
+/// Two consecutive runs of `schedule` after `from` that are closer together
+/// than `min_gap`, if there are any.
+///
+/// Consecutive occurrences are walked in order, so an irregular expression
+/// such as `1,2,30 * * * *` is judged by its shortest gap and not by whichever
+/// pair happens to follow `from`. The shortest gap is what counts, including
+/// the wrap-around one: `*/7 * * * *` fires at :56 and then at :00, four
+/// minutes apart, and is reported as such.
+///
+/// The walk is bounded ([`RUN_GAP_SCAN_OCCURRENCES`] runs, one shared
+/// [`ACTIVE_WINDOW_CANDIDATE_LIMIT`] budget), so a sparse or window-restricted
+/// expression stays cheap. An expression that cannot be parsed, or that has no
+/// second occurrence, is not evidence of anything and yields `None`;
+/// [`validate_schedule`] is where a bad expression gets rejected.
+pub fn runs_closer_than(
+ schedule: &Schedule,
+ from: DateTime<Utc>,
+ min_gap: ChronoDuration,
+) -> Option<TooFrequent> {
+ match schedule {
+ Schedule::At { .. } => None,
+ Schedule::Every { every_ms } => {
+ let gap = ChronoDuration::try_milliseconds(i64::try_from(*every_ms).ok()?)?;
+ (gap < min_gap).then_some(TooFrequent::FixedInterval(gap))
+ }
+ Schedule::Cron {
+ expr,
+ tz,
+ active_hours,
+ } => {
+ let plan = CronPlan::parse(expr, tz.as_deref(), active_hours.as_ref()).ok()?;
+ let mut budget = ACTIVE_WINDOW_CANDIDATE_LIMIT;
+ let mut previous = plan.next_after(from, &mut budget).ok()?;
+ for _ in 1..RUN_GAP_SCAN_OCCURRENCES {
+ let next = plan.next_after(previous, &mut budget).ok()?;
+ if next - previous < min_gap {
+ return Some(TooFrequent::ConsecutiveRuns {
+ first: previous,
+ second: next,
+ });
+ }
+ previous = next;
+ }
+ None
+ }
+ }
+}
+
+/// `4 minutes`, `30 seconds`, `1 minute 30 seconds` — whole seconds only.
+fn describe_gap(gap: ChronoDuration) -> String {
+ fn count(n: i64, unit: &str) -> String {
+ if n == 1 {
+ format!("{n} {unit}")
+ } else {
+ format!("{n} {unit}s")
+ }
+ }
+ let seconds = gap.num_seconds();
+ match (seconds / 60, seconds % 60) {
+ (0, s) => count(s, "second"),
+ (m, 0) => count(m, "minute"),
+ (m, s) => format!("{} {}", count(m, "minute"), count(s, "second")),
+ }
+}
+
pub fn schedule_cron_expression(schedule: &Schedule) -> Option<String> {
match schedule {
Schedule::Cron { expr, .. } => Some(expr.clone()),
@@ -94,6 +204,61 @@ pub fn schedule_cron_expression(schedule: &Schedule) -> Option<String> {
}
}
+/// A [`Schedule::Cron`] parsed once, so walking many occurrences does not pay
+/// for the expression, timezone and active-window parsing on every step.
+struct CronPlan<'a> {
+ expr: &'a str,
+ cron: CronExprSchedule,
+ timezone: ScheduleTimeZone,
+ active_window: Option<ActiveWindow>,
+}
+
+impl<'a> CronPlan<'a> {
+ fn parse(expr: &'a str, tz: Option<&str>, active_hours: Option<&ActiveHours>) -> Result<Self> {
+ let normalized = normalize_expression(expr)?;
+ let cron = CronExprSchedule::from_str(&normalized)
+ .with_context(|| format!("Invalid cron expression: {expr}"))?;
+ let timezone = ScheduleTimeZone::parse(tz)?;
+ let active_window = active_hours.map(ActiveWindow::parse).transpose()?;
+ Ok(Self {
+ expr,
+ cron,
+ timezone,
+ active_window,
+ })
+ }
+
+ /// The first occurrence strictly after `from` that falls inside the active
+ /// window, spending at most `budget` cron candidates to find it.
+ fn next_after(&self, from: DateTime<Utc>, budget: &mut usize) -> Result<DateTime<Utc>> {
+ let mut current_from = from;
+ while *budget > 0 {
+ *budget -= 1;
+ let next_utc = self
+ .timezone
+ .next_after(&self.cron, current_from, self.expr)?;
+ let Some(active) = &self.active_window else {
+ return Ok(next_utc);
+ };
+ if active.contains(self.timezone.local_time_of_day(next_utc)) {
+ return Ok(next_utc);
+ }
+ tracing::debug!(
+ "[cron] next_run candidate {} outside active window {}–{}, advancing",
+ next_utc,
+ active.start,
+ active.end
+ );
+ current_from = next_utc;
+ }
+ tracing::warn!(
+ "[cron] no occurrence found within active_hours for expr={} after 100,000 candidates",
+ self.expr
+ );
+ anyhow::bail!("No future occurrence found within active hours after 100,000 attempts")
+ }
+}
+
#[derive(Debug, Clone, Copy)]
enum ScheduleTimeZone {
Local,
diff --git a/src/openhuman/cron/schedule_tests.rs b/src/openhuman/cron/schedule_tests.rs
index 98514ae267..66b59cc7dc 100644
--- a/src/openhuman/cron/schedule_tests.rs
+++ b/src/openhuman/cron/schedule_tests.rs
@@ -303,3 +303,202 @@ fn validate_schedule_rejects_invalid_active_hours_end() {
let err = validate_schedule(&schedule, now).unwrap_err();
assert!(err.to_string().contains("active_hours.end"));
}
+
+// ── runs_closer_than / validate_agent_schedule (#6158) ──────────
+
+fn utc_cron(expr: &str) -> Schedule {
+ Schedule::Cron {
+ expr: expr.into(),
+ tz: Some("UTC".into()),
+ active_hours: None,
+ }
+}
+
+#[test]
+fn runs_closer_than_reports_the_shortest_gap_of_an_irregular_expression() {
+ // From :03 the pair that follows is :30 → 1:01 — 31 minutes apart, which
+ // is what a "the pair after now" check would have judged the schedule by.
+ // The :01 → :02 pair one minute apart is what counts.
+ let from = Utc.with_ymd_and_hms(2026, 3, 2, 10, 3, 0).unwrap();
+ let hit = runs_closer_than(&utc_cron("1,2,30 * * * *"), from, MIN_AGENT_JOB_INTERVAL)
+ .expect("the one-minute gap must be found");
+ assert_eq!(
+ hit,
+ TooFrequent::ConsecutiveRuns {
+ first: Utc.with_ymd_and_hms(2026, 3, 2, 11, 1, 0).unwrap(),
+ second: Utc.with_ymd_and_hms(2026, 3, 2, 11, 2, 0).unwrap(),
+ }
+ );
+ assert_eq!(hit.gap(), ChronoDuration::minutes(1));
+}
+
+#[test]
+fn runs_closer_than_does_not_depend_on_the_instant_it_starts_from() {
+ for minute in [0, 1, 2, 3, 15, 29, 30, 31, 59] {
+ let from = Utc.with_ymd_and_hms(2026, 3, 2, 10, minute, 0).unwrap();
+ for expr in ["1,2,30 * * * *", "0,1 * * * *", "0,3 9 * * *"] {
+ assert!(
+ runs_closer_than(&utc_cron(expr), from, MIN_AGENT_JOB_INTERVAL).is_some(),
+ "{expr} from :{minute:02}"
+ );
+ }
+ for expr in ["*/10 * * * *", "0 * * * *", "0,30 9 * * *"] {
+ assert!(
+ runs_closer_than(&utc_cron(expr), from, MIN_AGENT_JOB_INTERVAL).is_none(),
+ "{expr} from :{minute:02}"
+ );
+ }
+ }
+}
+
+/// `*/7` is 0,7,…,56: the :56 → :00 step is four minutes, and it counts.
+#[test]
+fn runs_closer_than_counts_the_wrap_around_gap() {
+ let from = Utc.with_ymd_and_hms(2026, 3, 2, 10, 0, 0).unwrap();
+ let hit = runs_closer_than(&utc_cron("*/7 * * * *"), from, MIN_AGENT_JOB_INTERVAL).unwrap();
+ assert_eq!(hit.gap(), ChronoDuration::minutes(4));
+ assert_eq!(
+ hit.to_string(),
+ "fires at 2026-03-02 10:56:00 UTC and again at 2026-03-02 11:00:00 UTC, 4 minutes apart"
+ );
+}
+
+#[test]
+fn runs_closer_than_is_quiet_at_and_above_the_threshold() {
+ let from = Utc.with_ymd_and_hms(2026, 3, 2, 10, 0, 0).unwrap();
+ for expr in [
+ "*/5 * * * *",
+ "*/6 * * * *",
+ "0 * * * *",
+ "0 9 * * *",
+ "0 9 * * 1",
+ "0 0 1 1 *",
+ "0 */5 * * * *",
+ ] {
+ assert!(
+ runs_closer_than(&utc_cron(expr), from, MIN_AGENT_JOB_INTERVAL).is_none(),
+ "{expr}"
+ );
+ }
+ let every_five = Schedule::Every { every_ms: 300_000 };
+ assert!(runs_closer_than(&every_five, from, MIN_AGENT_JOB_INTERVAL).is_none());
+ let once = Schedule::At { at: from };
+ assert!(runs_closer_than(&once, from, MIN_AGENT_JOB_INTERVAL).is_none());
+}
+
+#[test]
+fn runs_closer_than_reports_a_fixed_interval() {
+ let from = Utc::now();
+ let hit = runs_closer_than(
+ &Schedule::Every { every_ms: 90_000 },
+ from,
+ MIN_AGENT_JOB_INTERVAL,
+ )
+ .unwrap();
+ assert_eq!(hit, TooFrequent::FixedInterval(ChronoDuration::seconds(90)));
+ assert_eq!(hit.to_string(), "fires every 1 minute 30 seconds");
+ let just_under = Schedule::Every { every_ms: 299_999 };
+ assert!(runs_closer_than(&just_under, from, MIN_AGENT_JOB_INTERVAL).is_some());
+}
+
+#[test]
+fn runs_closer_than_sees_seconds_level_expressions() {
+ let from = Utc.with_ymd_and_hms(2026, 3, 2, 10, 0, 0).unwrap();
+ let hit = runs_closer_than(&utc_cron("*/30 * * * * *"), from, MIN_AGENT_JOB_INTERVAL).unwrap();
+ assert_eq!(hit.gap(), ChronoDuration::seconds(30));
+}
+
+#[test]
+fn runs_closer_than_judges_the_effective_cadence_inside_the_active_window() {
+ let from = Utc.with_ymd_and_hms(2026, 3, 2, 10, 0, 0).unwrap();
+ let every_minute_during = |start: &str, end: &str| Schedule::Cron {
+ expr: "* * * * *".into(),
+ tz: Some("UTC".into()),
+ active_hours: Some(ActiveHours {
+ start: start.into(),
+ end: end.into(),
+ }),
+ };
+ // Every minute, but only during one minute of the day: effectively daily.
+ let daily = every_minute_during("09:00", "09:00");
+ assert!(runs_closer_than(&daily, from, MIN_AGENT_JOB_INTERVAL).is_none());
+ // A two-minute window lets two adjacent runs through.
+ let hit = runs_closer_than(
+ &every_minute_during("09:00", "09:01"),
+ from,
+ MIN_AGENT_JOB_INTERVAL,
+ )
+ .unwrap();
+ assert_eq!(hit.gap(), ChronoDuration::minutes(1));
+}
+
+#[test]
+fn runs_closer_than_treats_an_unreadable_expression_as_no_evidence() {
+ let from = Utc::now();
+ assert!(runs_closer_than(&utc_cron("not a cron"), from, MIN_AGENT_JOB_INTERVAL).is_none());
+ let bad_tz = Schedule::Cron {
+ expr: "* * * * *".into(),
+ tz: Some("Mars/Olympus_Mons".into()),
+ active_hours: None,
+ };
+ assert!(runs_closer_than(&bad_tz, from, MIN_AGENT_JOB_INTERVAL).is_none());
+}
+
+#[test]
+fn validate_agent_schedule_rejects_tight_schedules_and_names_the_evidence() {
+ let now = Utc.with_ymd_and_hms(2026, 3, 2, 10, 0, 0).unwrap();
+ let err = validate_agent_schedule(&utc_cron("*/3 * * * *"), now)
+ .unwrap_err()
+ .to_string();
+ assert_eq!(
+ err,
+ "Invalid schedule: agent jobs must run at least 5 minutes apart, but this schedule \
+ fires at 2026-03-02 10:03:00 UTC and again at 2026-03-02 10:06:00 UTC, 3 minutes apart"
+ );
+ let err = validate_agent_schedule(&Schedule::Every { every_ms: 60_000 }, now)
+ .unwrap_err()
+ .to_string();
+ assert_eq!(
+ err,
+ "Invalid schedule: agent jobs must run at least 5 minutes apart, but this schedule \
+ fires every 1 minute"
+ );
+}
+
+#[test]
+fn validate_agent_schedule_accepts_the_floor_and_keeps_the_generic_checks() {
+ let now = Utc::now();
+ assert!(validate_agent_schedule(&utc_cron("*/5 * * * *"), now).is_ok());
+ assert!(validate_agent_schedule(&Schedule::Every { every_ms: 300_000 }, now).is_ok());
+ let soon = Schedule::At {
+ at: now + ChronoDuration::minutes(1),
+ };
+ assert!(validate_agent_schedule(&soon, now).is_ok());
+
+ // The generic validation runs first: a broken schedule is rejected as
+ // broken, not as "too frequent".
+ let err = validate_agent_schedule(&utc_cron("not a cron"), now)
+ .unwrap_err()
+ .to_string();
+ assert!(err.contains("Invalid cron expression"), "{err}");
+ let err = validate_agent_schedule(&Schedule::Every { every_ms: 0 }, now)
+ .unwrap_err()
+ .to_string();
+ assert!(err.contains("every_ms must be > 0"), "{err}");
+ let err = validate_agent_schedule(&Schedule::At { at: now }, now)
+ .unwrap_err()
+ .to_string();
+ assert!(err.contains("'at' must be in the future"), "{err}");
+}
+
+#[test]
+fn describe_gap_reads_naturally() {
+ assert_eq!(describe_gap(ChronoDuration::seconds(1)), "1 second");
+ assert_eq!(describe_gap(ChronoDuration::seconds(30)), "30 seconds");
+ assert_eq!(describe_gap(ChronoDuration::minutes(1)), "1 minute");
+ assert_eq!(describe_gap(ChronoDuration::minutes(5)), "5 minutes");
+ assert_eq!(
+ describe_gap(ChronoDuration::seconds(90)),
+ "1 minute 30 seconds"
+ );
+}
diff --git a/src/openhuman/cron/scheduler_part_01.rs b/src/openhuman/cron/scheduler_part_01.rs
index 229840382a..c173d1cc6e 100644
--- a/src/openhuman/cron/scheduler_part_01.rs
+++ b/src/openhuman/cron/scheduler_part_01.rs
@@ -4,8 +4,9 @@ use crate::openhuman::agent::error::AgentError;
use crate::openhuman::agent::Agent;
use crate::openhuman::config::Config;
use crate::openhuman::cron::{
- due_jobs, next_run_for_schedule, record_last_run, record_run, remove_job, reschedule_after_run,
+ due_jobs, record_last_run, record_run, remove_job, reschedule_after_run, runs_closer_than,
update_job, CronJob, CronJobPatch, DeliveryConfig, JobType, Schedule, SessionTarget,
+ TooFrequent, MIN_AGENT_JOB_INTERVAL,
};
use crate::openhuman::security::SecurityPolicy;
use anyhow::Result;
diff --git a/src/openhuman/cron/scheduler_part_03.rs b/src/openhuman/cron/scheduler_part_03.rs
index 15df84f18e..288fb8ca44 100644
--- a/src/openhuman/cron/scheduler_part_03.rs
+++ b/src/openhuman/cron/scheduler_part_03.rs
@@ -67,45 +67,37 @@ fn is_one_shot_auto_delete(job: &CronJob) -> bool {
job.delete_after_run && matches!(job.schedule, Schedule::At { .. })
}
-/// Whether an agent job runs oftener than every 5 minutes.
+/// Why an agent job counts as scheduled more often than every five minutes,
+/// if it does. `None` for shell and flow jobs, for one-shot `At` schedules,
+/// for anything at or above [`MIN_AGENT_JOB_INTERVAL`], and for an expression
+/// that cannot be read (that is not evidence of anything).
///
-/// Returns the verdict rather than only logging it, because the verdict is the
-/// part worth testing: the `Schedule::Cron` arm below was wrong, and no test
-/// could see it, because a function that only warns has nothing to assert.
-///
-/// The gap is measured between two *consecutive* runs. It used to be measured
-/// between the next run after now and the next run after now plus one second,
-/// which are the same instant unless a run happens to fall inside that second:
-/// `num_minutes()` of nothing is 0, 0 is under 5, so **every** cron-scheduled
-/// agent job warned, whatever its expression.
-fn is_high_frequency_agent_job(job: &CronJob) -> bool {
+/// Returns the verdict rather than only logging it, because the verdict is
+/// the part worth testing: the `Schedule::Cron` arm used to measure the gap
+/// between the next run after now and the next run after now plus one
+/// second — the same instant unless a run fell inside that second — so every
+/// cron-scheduled agent job warned, and no test could see it because a
+/// function that only warns has nothing to assert. The gap is now the
+/// shortest one between consecutive runs (`runs_closer_than`), so an
+/// irregular expression is judged by its tightest pair and not by whichever
+/// pair happens to follow the instant of the check.
+fn agent_job_too_frequent(job: &CronJob) -> Option<TooFrequent> {
if !matches!(job.job_type, JobType::Agent) {
- return false;
- }
- match &job.schedule {
- Schedule::Every { every_ms } => *every_ms < 5 * 60 * 1000,
- Schedule::Cron { .. } => {
- let now = Utc::now();
- match next_run_for_schedule(&job.schedule, now) {
- Ok(first) => match next_run_for_schedule(&job.schedule, first) {
- // Truncating division is what makes the boundary read the
- // way the message does: a gap of exactly 5 minutes is 5,
- // and not "more frequently than every 5 minutes".
- Ok(second) => (second - first).num_minutes() < 5,
- // An expression with no second occurrence is not frequent.
- Err(_) => false,
- },
- Err(_) => false,
- }
- }
- Schedule::At { .. } => false,
+ return None;
}
+ runs_closer_than(&job.schedule, Utc::now(), MIN_AGENT_JOB_INTERVAL)
}
+/// New agent jobs cannot be created below the floor (`validate_agent_schedule`
+/// rejects them), so a job that trips this predates the rule. It keeps
+/// running — silently skipping runs would turn its schedule into a lie — and
+/// this line is the operator's signal to edit it.
fn warn_if_high_frequency_agent_job(job: &CronJob) {
- if is_high_frequency_agent_job(job) {
+ if let Some(too_frequent) = agent_job_too_frequent(job) {
tracing::warn!(
- "Cron agent job '{}' is scheduled more frequently than every 5 minutes",
+ "Cron agent job '{}' is scheduled more frequently than every 5 minutes: it \
+ {too_frequent}. It was created before that floor was enforced; edit its \
+ schedule to silence this.",
job.id
);
}
diff --git a/src/openhuman/cron/scheduler_tests_part_03_tests.rs b/src/openhuman/cron/scheduler_tests_part_03_tests.rs
index 26e9bae97f..68c2732aee 100644
--- a/src/openhuman/cron/scheduler_tests_part_03_tests.rs
+++ b/src/openhuman/cron/scheduler_tests_part_03_tests.rs
@@ -7,92 +7,6 @@ fn forbidden_path_argument_skips_flags_and_urls() {
assert!(forbidden_path_argument(&policy, "ls -la").is_none());
}
-fn agent_job_on(schedule: Schedule) -> CronJob {
- let mut job = test_job("echo hi");
- job.job_type = JobType::Agent;
- job.schedule = schedule;
- job
-}
-
-fn cron_agent_job(expr: &str) -> CronJob {
- agent_job_on(Schedule::Cron {
- expr: expr.into(),
- tz: None,
- active_hours: None,
- })
-}
-
-#[test]
-fn warn_if_high_frequency_agent_job_does_not_panic_on_non_agent() {
- let mut job = test_job("echo hi");
- job.job_type = JobType::Shell;
- warn_if_high_frequency_agent_job(&job); // should not panic
- assert!(!is_high_frequency_agent_job(&job));
-}
-
-#[test]
-fn warn_if_high_frequency_agent_job_does_not_panic_on_at_schedule() {
- let job = agent_job_on(Schedule::At { at: Utc::now() });
- warn_if_high_frequency_agent_job(&job); // should not panic
- assert!(!is_high_frequency_agent_job(&job));
-}
-
-#[test]
-fn warn_if_high_frequency_agent_job_handles_every_ms() {
- let job = agent_job_on(Schedule::Every { every_ms: 60_000 }); // 1 minute — too frequent
- warn_if_high_frequency_agent_job(&job); // should warn but not panic
- assert!(is_high_frequency_agent_job(&job));
-}
-
-/// **The warning fired for every cron-scheduled agent job.**
-///
-/// The gap was measured between the next run after now and the next run after
-/// now plus one second, which are the same instant unless a run falls inside
-/// that second. Zero minutes is under five, so an hourly job was reported as
-/// running oftener than every five minutes, and the operator had no way to tell
-/// a real misconfiguration from the noise.
-#[test]
-fn an_ordinary_cron_agent_job_is_not_called_high_frequency() {
- for expr in ["*/10 * * * *", "0 * * * *", "0 9 * * *", "*/6 * * * *"] {
- assert!(
- !is_high_frequency_agent_job(&cron_agent_job(expr)),
- "{expr} runs at most every 6 minutes and must not warn"
- );
- }
-}
-
-#[test]
-fn a_cron_agent_job_under_five_minutes_is_still_caught() {
- for expr in ["*/3 * * * *", "*/1 * * * *", "*/4 * * * *"] {
- assert!(
- is_high_frequency_agent_job(&cron_agent_job(expr)),
- "{expr} runs oftener than every 5 minutes and must warn"
- );
- }
-}
-
-/// Exactly five minutes is the boundary the message names, and it is not over
-/// it. `*/5` is also the expression the codebase's own tests reach for, so
-/// warning on it would train an operator to ignore the warning.
-#[test]
-fn a_cron_agent_job_at_exactly_five_minutes_is_not_high_frequency() {
- assert!(!is_high_frequency_agent_job(&cron_agent_job("*/5 * * * *")));
- assert!(!is_high_frequency_agent_job(&agent_job_on(
- Schedule::Every {
- every_ms: 5 * 60 * 1000
- }
- )));
-}
-
-/// A schedule the arm cannot read is not evidence of anything, least of all of
-/// running too often.
-#[test]
-fn an_unparseable_cron_expression_is_not_called_high_frequency() {
- assert!(!is_high_frequency_agent_job(&cron_agent_job(
- "not a cron expression"
- )));
-}
-
#[tokio::test]
async fn deliver_if_configured_skips_empty_mode() {
let tmp = TempDir::new().unwrap();
diff --git a/src/openhuman/cron/scheduler_tests_part_04_tests.rs b/src/openhuman/cron/scheduler_tests_part_04_tests.rs
index f9cc899cca..e19c10dcb5 100644
--- a/src/openhuman/cron/scheduler_tests_part_04_tests.rs
+++ b/src/openhuman/cron/scheduler_tests_part_04_tests.rs
@@ -79,3 +79,111 @@ async fn cron_agent_job_short_loopback_send_error_stays_retryable() {
"provider-generated short loopback send error must stay retryable without refused errno/tcp-connect evidence; got raw={raw:?}"
);
}
+
+// ── agent-job frequency check (#6158) ───────────────────────────
+//
+// The `Schedule::Cron` arm used to compare the next run after now with the
+// next run after now plus one second — the same instant unless a run fell
+// inside that second — so *every* cron-scheduled agent job warned, whatever
+// its expression, and the three `// should not panic` tests could not tell.
+// The verdict is now returned with its evidence and measured over
+// consecutive runs, so each case below asserts it.
+
+fn agent_job_on(schedule: Schedule) -> CronJob {
+ let mut job = test_job("echo hi");
+ job.job_type = JobType::Agent;
+ job.schedule = schedule;
+ job
+}
+
+fn cron_agent_job(expr: &str) -> CronJob {
+ agent_job_on(Schedule::Cron {
+ expr: expr.into(),
+ tz: None,
+ active_hours: None,
+ })
+}
+
+#[test]
+fn non_agent_and_one_shot_jobs_are_never_high_frequency() {
+ // `test_job` runs every minute — but it is a shell job.
+ let mut shell = test_job("echo hi");
+ shell.job_type = JobType::Shell;
+ assert!(agent_job_too_frequent(&shell).is_none());
+ warn_if_high_frequency_agent_job(&shell);
+
+ let once = agent_job_on(Schedule::At { at: Utc::now() });
+ assert!(agent_job_too_frequent(&once).is_none());
+ warn_if_high_frequency_agent_job(&once);
+}
+
+#[test]
+fn every_ms_below_five_minutes_is_high_frequency() {
+ let job = agent_job_on(Schedule::Every { every_ms: 60_000 });
+ assert_eq!(
+ agent_job_too_frequent(&job),
+ Some(TooFrequent::FixedInterval(ChronoDuration::minutes(1)))
+ );
+ warn_if_high_frequency_agent_job(&job); // logs the evidence, must not panic
+}
+
+/// The regression: every ordinary schedule was reported as too frequent.
+#[test]
+fn an_ordinary_cron_agent_job_is_not_high_frequency() {
+ for expr in [
+ "*/10 * * * *",
+ "0 * * * *",
+ "0 9 * * *",
+ "*/6 * * * *",
+ "0 9 * * 1-5",
+ ] {
+ assert!(
+ agent_job_too_frequent(&cron_agent_job(expr)).is_none(),
+ "{expr} runs at most every 6 minutes and must not warn"
+ );
+ }
+}
+
+#[test]
+fn a_cron_agent_job_under_five_minutes_is_still_caught() {
+ for expr in [
+ "*/3 * * * *",
+ "*/1 * * * *",
+ "*/4 * * * *",
+ "*/30 * * * * *",
+ ] {
+ let hit = agent_job_too_frequent(&cron_agent_job(expr))
+ .unwrap_or_else(|| panic!("{expr} runs oftener than every 5 minutes and must warn"));
+ assert!(hit.gap() < MIN_AGENT_JOB_INTERVAL, "{expr}: {hit}");
+ }
+}
+
+/// An irregular expression is judged by its tightest pair, whatever minute
+/// the check happens to run at (CodeRabbit / Codex on #6159).
+#[test]
+fn an_irregular_cron_agent_job_is_judged_by_its_shortest_gap() {
+ for expr in ["1,2,30 * * * *", "0,1 * * * *", "0,3 9 * * *"] {
+ let hit = agent_job_too_frequent(&cron_agent_job(expr))
+ .unwrap_or_else(|| panic!("{expr} has two runs inside five minutes and must warn"));
+ assert!(hit.gap() <= ChronoDuration::minutes(3), "{expr}: {hit}");
+ }
+}
+
+/// Exactly five minutes is the boundary the message names, and it is not
+/// over it. `*/5` is also the expression the codebase's own tests reach for,
+/// so warning on it would train an operator to ignore the warning.
+#[test]
+fn a_cron_agent_job_at_exactly_five_minutes_is_not_high_frequency() {
+ assert!(agent_job_too_frequent(&cron_agent_job("*/5 * * * *")).is_none());
+ let every_five = agent_job_on(Schedule::Every {
+ every_ms: 5 * 60 * 1000,
+ });
+ assert!(agent_job_too_frequent(&every_five).is_none());
+}
+
+/// A schedule the arm cannot read is not evidence of anything, least of all
+/// of running too often.
+#[test]
+fn an_unparseable_cron_expression_is_not_high_frequency() {
+ assert!(agent_job_too_frequent(&cron_agent_job("not a cron expression")).is_none());
+}
diff --git a/src/openhuman/cron/schemas.rs b/src/openhuman/cron/schemas.rs
index 8557593110..87cfdfe532 100644
--- a/src/openhuman/cron/schemas.rs
+++ b/src/openhuman/cron/schemas.rs
@@ -72,7 +72,8 @@ pub fn schemas(function: &str) -> ControllerSchema {
FieldSchema {
name: "schedule",
ty: TypeSchema::Ref("CronSchedule"),
- comment: "When to run — { kind: 'cron', expr } | { kind: 'at', at } | { kind: 'every', every_ms }.",
+ comment: "When to run — { kind: 'cron', expr } | { kind: 'at', at } | { kind: 'every', every_ms }. \
+ Agent jobs must run at least 5 minutes apart.",
required: true,
},
FieldSchema {
@@ -163,7 +164,8 @@ pub fn schemas(function: &str) -> ControllerSchema {
FieldSchema {
name: "patch",
ty: TypeSchema::Ref("CronJobPatch"),
- comment: "Partial update payload with the fields to mutate.",
+ comment: "Partial update payload with the fields to mutate. A new schedule on an agent job \
+ must keep runs at least 5 minutes apart.",
required: true,
},
],
diff --git a/src/openhuman/cron/store_part_01.rs b/src/openhuman/cron/store_part_01.rs
index f6a5be6bce..e0ab0cbc1d 100644
--- a/src/openhuman/cron/store_part_01.rs
+++ b/src/openhuman/cron/store_part_01.rs
@@ -1,7 +1,7 @@
use crate::openhuman::config::Config;
use crate::openhuman::cron::{
- next_run_for_schedule, schedule_cron_expression, validate_schedule, CronJob, CronJobPatch,
- CronRun, DeliveryConfig, JobType, Schedule, SessionTarget,
+ next_run_for_schedule, schedule_cron_expression, validate_agent_schedule, validate_schedule,
+ CronJob, CronJobPatch, CronRun, DeliveryConfig, JobType, Schedule, SessionTarget,
};
use anyhow::{Context, Result};
use chrono::{DateTime, Utc};
@@ -101,7 +101,9 @@ pub fn add_agent_job_with_definition(
profile_id: Option<String>,
) -> Result<CronJob> {
let now = Utc::now();
- validate_schedule(&schedule, now)?;
+ // Agent runs are inference turns: on top of the generic checks, refuse a
+ // schedule tighter than `MIN_AGENT_JOB_INTERVAL` (#6158).
+ validate_agent_schedule(&schedule, now)?;
let next_run = next_run_for_schedule(&schedule, now)?;
let id = Uuid::new_v4().to_string();
let expression = schedule_cron_expression(&schedule).unwrap_or_default();
@@ -402,7 +404,13 @@ pub fn update_job(config: &Config, job_id: &str, patch: CronJobPatch) -> Result<
let mut schedule_changed = false;
if let Some(schedule) = patch.schedule {
- validate_schedule(&schedule, Utc::now())?;
+ // The agent-only floor applies whenever the schedule is (re)set, so a
+ // row that predates it keeps running untouched until its schedule is
+ // edited — and then has to comply like a new job.
+ match job.job_type {
+ JobType::Agent => validate_agent_schedule(&schedule, Utc::now())?,
+ JobType::Shell | JobType::Flow => validate_schedule(&schedule, Utc::now())?,
+ }
job.schedule = schedule;
job.expression = schedule_cron_expression(&job.schedule).unwrap_or_default();
schedule_changed = true;
diff --git a/src/openhuman/cron/store_tests.rs b/src/openhuman/cron/store_tests.rs
index 04f17f6ee1..a8644a9774 100644
--- a/src/openhuman/cron/store_tests.rs
+++ b/src/openhuman/cron/store_tests.rs
@@ -612,3 +612,6 @@ fn dedup_named_jobs_ignores_unnamed_jobs() {
assert_eq!(removed, 0);
assert_eq!(list_jobs(&config).unwrap().len(), 2);
}
+
+#[path = "store_tests_part_01_tests.rs"]
+mod part_01_tests;
diff --git a/src/openhuman/cron/store_tests_part_01_tests.rs b/src/openhuman/cron/store_tests_part_01_tests.rs
new file mode 100644
index 0000000000..c885e88505
--- /dev/null
+++ b/src/openhuman/cron/store_tests_part_01_tests.rs
@@ -0,0 +1,139 @@
+use super::*;
+
+// ── agent-job minimum interval (#6158) ──────────────────────────
+
+fn utc_cron(expr: &str) -> Schedule {
+ Schedule::Cron {
+ expr: expr.into(),
+ tz: Some("UTC".into()),
+ active_hours: None,
+ }
+}
+
+fn add_agent(config: &Config, schedule: Schedule) -> Result<CronJob> {
+ add_agent_job(
+ config,
+ Some("inbox".into()),
+ schedule,
+ "check my inbox",
+ SessionTarget::Isolated,
+ None,
+ None,
+ false,
+ )
+}
+
+#[test]
+fn add_agent_job_rejects_a_schedule_tighter_than_five_minutes() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+
+ let err = add_agent(&config, utc_cron("*/1 * * * *"))
+ .unwrap_err()
+ .to_string();
+ assert!(
+ err.contains("agent jobs must run at least 5 minutes apart"),
+ "{err}"
+ );
+ let err = add_agent(&config, Schedule::Every { every_ms: 60_000 })
+ .unwrap_err()
+ .to_string();
+ assert!(err.contains("fires every 1 minute"), "{err}");
+ assert!(
+ list_jobs(&config).unwrap().is_empty(),
+ "a rejected job must not be stored"
+ );
+
+ // The floor itself is fine, and shell jobs are not subject to it.
+ assert!(add_agent(&config, utc_cron("*/5 * * * *")).is_ok());
+ assert!(add_shell_job(&config, None, utc_cron("* * * * *"), "echo ok").is_ok());
+}
+
+/// A row that predates the floor (or came in through any path that bypasses
+/// the store's validation) keeps working: the scheduler warns, nothing rejects.
+fn legacy_tight_agent_job(config: &Config) -> CronJob {
+ let job = add_agent(config, utc_cron("*/5 * * * *")).unwrap();
+ let tight = serde_json::to_string(&utc_cron("* * * * *")).unwrap();
+ with_connection(config, |conn| {
+ conn.execute(
+ "UPDATE cron_jobs SET expression = ?1, schedule = ?2 WHERE id = ?3",
+ params!["* * * * *", tight, job.id],
+ )?;
+ Ok(())
+ })
+ .unwrap();
+ get_job(config, &job.id).unwrap()
+}
+
+#[test]
+fn update_job_leaves_a_legacy_tight_agent_job_alone_until_its_schedule_changes() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let job = legacy_tight_agent_job(&config);
+ assert_eq!(job.expression, "* * * * *");
+
+ // Renaming, re-enabling, changing the prompt: none of these touch the
+ // schedule, so none of them are blocked by it.
+ let renamed = update_job(
+ &config,
+ &job.id,
+ CronJobPatch {
+ name: Some("renamed".into()),
+ enabled: Some(true),
+ prompt: Some("new prompt".into()),
+ ..CronJobPatch::default()
+ },
+ )
+ .unwrap();
+ assert_eq!(renamed.name.as_deref(), Some("renamed"));
+ assert_eq!(renamed.expression, "* * * * *");
+
+ // Setting the schedule is where the floor applies.
+ let err = update_job(
+ &config,
+ &job.id,
+ CronJobPatch {
+ schedule: Some(utc_cron("*/2 * * * *")),
+ ..CronJobPatch::default()
+ },
+ )
+ .unwrap_err()
+ .to_string();
+ assert!(
+ err.contains("agent jobs must run at least 5 minutes apart"),
+ "{err}"
+ );
+ assert_eq!(
+ get_job(&config, &job.id).unwrap().expression,
+ "* * * * *",
+ "a rejected patch must not be applied"
+ );
+
+ let fixed = update_job(
+ &config,
+ &job.id,
+ CronJobPatch {
+ schedule: Some(utc_cron("*/10 * * * *")),
+ ..CronJobPatch::default()
+ },
+ )
+ .unwrap();
+ assert_eq!(fixed.expression, "*/10 * * * *");
+}
+
+#[test]
+fn update_job_does_not_apply_the_agent_floor_to_shell_jobs() {
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let job = add_job(&config, "*/5 * * * *", "echo ok").unwrap();
+ let updated = update_job(
+ &config,
+ &job.id,
+ CronJobPatch {
+ schedule: Some(utc_cron("* * * * *")),
+ ..CronJobPatch::default()
+ },
+ )
+ .unwrap();
+ assert_eq!(updated.expression, "* * * * *");
+}
diff --git a/src/openhuman/cron/tools/add.rs b/src/openhuman/cron/tools/add.rs
index fd1d6bedd6..4f2496b52c 100644
--- a/src/openhuman/cron/tools/add.rs
+++ b/src/openhuman/cron/tools/add.rs
@@ -106,7 +106,9 @@ impl Tool for CronAddTool {
Discord, Slack), set `delivery` to `{ \"mode\": \"announce\", \"channel\": <channel>, \
\"to\": <reply target from the context block> }` so the reminder is delivered back to \
the same chat instead of the desktop. Only use the default proactive mode when the \
- user explicitly asks for an in-app notification or when no channel context is present."
+ user explicitly asks for an in-app notification or when no channel context is present.\n\
+ Agent jobs must be scheduled at least 5 minutes apart; a tighter cron expression or \
+ every_ms is rejected."
}
fn parameters_schema(&self) -> serde_json::Value {
@@ -122,7 +124,7 @@ impl Tool for CronAddTool {
"description": "Repeating cron schedule. 'tz' is an IANA timezone (e.g. 'America/Los_Angeles'); defaults to device-local timezone.",
"properties": {
"kind": { "type": "string", "const": "cron" },
- "expr": { "type": "string", "description": "Cron expression (5, 6, or 7 fields)" },
+ "expr": { "type": "string", "description": "Cron expression (5, 6, or 7 fields). For agent jobs, consecutive runs must be at least 5 minutes apart." },
"tz": { "type": "string", "description": "Optional IANA timezone name" },
"active_hours": {
"type": "object",
@@ -153,7 +155,7 @@ impl Tool for CronAddTool {
"description": "Repeating job that fires every N milliseconds.",
"properties": {
"kind": { "type": "string", "const": "every" },
- "every_ms": { "type": "integer", "description": "Interval in milliseconds (must be > 0)" }
+ "every_ms": { "type": "integer", "description": "Interval in milliseconds (must be > 0; at least 300000 = 5 minutes for agent jobs)" }
},
"required": ["kind", "every_ms"],
"additionalProperties": false
diff --git a/src/openhuman/cron/tools/add_tests.rs b/src/openhuman/cron/tools/add_tests.rs
index f96651cad8..8866259ab4 100644
--- a/src/openhuman/cron/tools/add_tests.rs
+++ b/src/openhuman/cron/tools/add_tests.rs
@@ -521,3 +521,81 @@ fn cron_add_tool_schema_requires_name_and_schedule() {
"'schedule' must appear in CronAddTool schema required list"
);
}
+
+#[tokio::test]
+async fn rejects_agent_job_scheduled_tighter_than_five_minutes() {
+ let tmp = TempDir::new().unwrap();
+ let cfg = test_config(&tmp).await;
+ let tool = CronAddTool::new(cfg.clone(), test_security(&cfg));
+
+ for schedule in [
+ json!({ "kind": "every", "every_ms": 60_000 }),
+ json!({ "kind": "cron", "expr": "*/3 * * * *" }),
+ // Bare-string shorthand; irregular, judged by its :01 → :02 pair.
+ json!("1,2,30 * * * *"),
+ ] {
+ let result = tool
+ .execute(json!({
+ "name": "too_eager",
+ "schedule": schedule,
+ "job_type": "agent",
+ "prompt": "check my inbox"
+ }))
+ .await
+ .unwrap();
+ assert!(
+ result.is_error,
+ "{schedule} must be rejected, got {:?}",
+ result.output()
+ );
+ assert!(
+ result
+ .output()
+ .contains("agent jobs must run at least 5 minutes apart"),
+ "{:?}",
+ result.output()
+ );
+ }
+ assert!(cron::list_jobs(&cfg).unwrap().is_empty());
+
+ // Shell jobs keep the old contract: any interval above zero.
+ let shell = tool
+ .execute(json!({
+ "name": "tick",
+ "schedule": { "kind": "every", "every_ms": 60_000 },
+ "job_type": "shell",
+ "command": "echo tick"
+ }))
+ .await
+ .unwrap();
+ assert!(!shell.is_error, "{:?}", shell.output());
+}
+
+#[tokio::test]
+async fn accepts_agent_job_at_exactly_five_minutes() {
+ let tmp = TempDir::new().unwrap();
+ let cfg = test_config(&tmp).await;
+ let tool = CronAddTool::new(cfg.clone(), test_security(&cfg));
+
+ let result = tool
+ .execute(json!({
+ "name": "inbox",
+ "schedule": { "kind": "cron", "expr": "*/5 * * * *" },
+ "job_type": "agent",
+ "prompt": "check my inbox"
+ }))
+ .await
+ .unwrap();
+ assert!(!result.is_error, "{:?}", result.output());
+}
+
+#[test]
+fn schema_and_description_document_the_agent_floor() {
+ let tool = CronAddTool::new(
+ Arc::new(Config::default()),
+ Arc::new(SecurityPolicy::default()),
+ );
+ assert!(tool.description().contains("at least 5 minutes apart"));
+ let schema = tool.parameters_schema().to_string();
+ assert!(schema.contains("at least 300000 = 5 minutes"), "{schema}");
+}
diff --git a/src/openhuman/cron/tools/update_tests.rs b/src/openhuman/cron/tools/update_tests.rs
index 8a1cc444b7..e674b388be 100644
--- a/src/openhuman/cron/tools/update_tests.rs
+++ b/src/openhuman/cron/tools/update_tests.rs
@@ -104,3 +104,48 @@ fn cron_update_permission_level_is_execute() {
let tool = CronUpdateTool::new(cfg.clone(), test_security(&cfg));
assert_eq!(tool.permission_level(), PermissionLevel::Execute);
}
+
+#[tokio::test]
+async fn rejects_tightening_an_agent_job_below_five_minutes() {
+ use crate::openhuman::cron::{Schedule, SessionTarget};
+
+ let tmp = TempDir::new().unwrap();
+ let cfg = test_config(&tmp).await;
+ let job = cron::add_agent_job(
+ &cfg,
+ Some("inbox".into()),
+ Schedule::Every { every_ms: 600_000 },
+ "check my inbox",
+ SessionTarget::Isolated,
+ None,
+ None,
+ false,
+ )
+ .unwrap();
+ let tool = CronUpdateTool::new(cfg.clone(), test_security(&cfg));
+
+ let result = tool
+ .execute(json!({
+ "job_id": job.id,
+ "patch": { "schedule": { "kind": "every", "every_ms": 60_000 } }
+ }))
+ .await
+ .unwrap();
+ assert!(result.is_error, "{:?}", result.output());
+ assert!(
+ result
+ .output()
+ .contains("agent jobs must run at least 5 minutes apart"),
+ "{:?}",
+ result.output()
+ );
+
+ let result = tool
+ .execute(json!({
+ "job_id": job.id,
+ "patch": { "schedule": { "kind": "every", "every_ms": 300_000 } }
+ }))
+ .await
+ .unwrap();
+ assert!(!result.is_error, "{:?}", result.output());
+}