The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
fix(cron): correct job scheduling to respect floor time constraints
Steven Enamakel7d1c8c8c68da
diff --git a/crates/openhuman-core/src/cron/store.rs b/crates/openhuman-core/src/cron/store.rsindex e979216e18..62b36a7ae9 100644--- a/crates/openhuman-core/src/cron/store.rs+++ b/crates/openhuman-core/src/cron/store.rs@@ -1,31 +1,181 @@-//! Cron persistence: SQLite-backed job storage and run history.+//! Cron persistence: a thin host wrapper over `tinyflows_sqlite::schedule`.//!-//! Split by responsibility: [`schema`] owns row mapping and the-//! connection/migration setup, [`jobs`] owns job CRUD, and [`runs`] owns-//! run-history recording, output truncation, and history reads.+//! The SQLite job store and run history live upstream (schema, CRUD, output+//! truncation, pruning). This module only turns the host [`Config`] into the+//! store's [`CronStoreOptions`] — database path under the workspace, run-history+//! cap, and due-job batch size — so callers keep passing `&Config`.-mod jobs;-mod runs;-mod schema;+use crate::config::Config;+use anyhow::Result;+use chrono::{DateTime, Utc};+use tinyflows_schedule::{CronJob, CronJobPatch, CronRun, DeliveryConfig, Schedule, SessionTarget};+use tinyflows_sqlite::schedule::{self as upstream, CronStoreOptions};++/// Builds the store options from the host config: `<workspace>/cron/jobs.db`,+/// `cron.max_run_history`, `scheduler.max_tasks`.+fn opts(config: &Config) -> CronStoreOptions {+ CronStoreOptions {+ db_path: config.workspace_dir.join("cron").join("jobs.db"),+ max_run_history: config.cron.max_run_history,+ max_tasks: config.scheduler.max_tasks,+ }+}++pub fn add_job(config: &Config, expression: &str, command: &str) -> Result<CronJob> {+ upstream::add_job(&opts(config), expression, command)+}++pub fn add_shell_job(+ config: &Config,+ name: Option<String>,+ schedule: Schedule,+ command: &str,+) -> Result<CronJob> {+ upstream::add_shell_job(&opts(config), name, schedule, command)+}++#[allow(clippy::too_many_arguments)]+pub fn add_agent_job(+ config: &Config,+ name: Option<String>,+ schedule: Schedule,+ prompt: &str,+ session_target: SessionTarget,+ model: Option<String>,+ delivery: Option<DeliveryConfig>,+ delete_after_run: bool,+) -> Result<CronJob> {+ upstream::add_agent_job(+ &opts(config),+ name,+ schedule,+ prompt,+ session_target,+ model,+ delivery,+ delete_after_run,+ )+}++/// Like [`add_agent_job`] but accepts an optional built-in agent definition+/// ID and the initial enabled state.+#[allow(clippy::too_many_arguments)]+pub fn add_agent_job_with_definition(+ config: &Config,+ name: Option<String>,+ schedule: Schedule,+ prompt: &str,+ session_target: SessionTarget,+ model: Option<String>,+ delivery: Option<DeliveryConfig>,+ delete_after_run: bool,+ agent_id: Option<String>,+ enabled: bool,+) -> Result<CronJob> {+ upstream::add_agent_job_with_definition(+ &opts(config),+ name,+ schedule,+ prompt,+ session_target,+ model,+ delivery,+ delete_after_run,+ agent_id,+ enabled,+ )+}++/// Registers (idempotently) the cron job that fires a flow's `schedule`+/// trigger; see `tinyflows_sqlite::schedule::add_flow_schedule_job`.+pub fn add_flow_schedule_job(config: &Config, flow_id: &str, schedule: Schedule) -> Result<CronJob> {+ upstream::add_flow_schedule_job(&opts(config), flow_id, schedule)+}++pub fn find_flow_schedule_job(config: &Config, flow_id: &str) -> Result<Option<CronJob>> {+ upstream::find_flow_schedule_job(&opts(config), flow_id)+}++pub fn list_jobs(config: &Config) -> Result<Vec<CronJob>> {+ upstream::list_jobs(&opts(config))+}++pub fn get_job(config: &Config, job_id: &str) -> Result<CronJob> {+ upstream::get_job(&opts(config), job_id)+}++pub fn remove_job(config: &Config, id: &str) -> Result<()> {+ upstream::remove_job(&opts(config), id)?;+ println!("✅ Removed cron job {id}");+ Ok(())+}++/// Deletes every cron job in the workspace (E2E `openhuman.test_reset`).+pub fn clear_all_jobs(config: &Config) -> Result<usize> {+ upstream::clear_all_jobs(&opts(config))+}++/// Removes duplicate jobs sharing a `name`, keeping the one with most history.+pub fn dedup_named_jobs(config: &Config) -> Result<usize> {+ upstream::dedup_named_jobs(&opts(config))+}++pub fn due_jobs(config: &Config, now: DateTime<Utc>) -> Result<Vec<CronJob>> {+ upstream::due_jobs(&opts(config), now)+}++pub fn update_job(config: &Config, job_id: &str, patch: CronJobPatch) -> Result<CronJob> {+ upstream::update_job(&opts(config), job_id, patch)+}++pub fn record_last_run(+ config: &Config,+ job_id: &str,+ finished_at: DateTime<Utc>,+ success: bool,+ output: &str,+) -> Result<()> {+ upstream::record_last_run(&opts(config), job_id, finished_at, success, output)+}++pub fn reschedule_after_run(+ config: &Config,+ job: &CronJob,+ success: bool,+ output: &str,+) -> Result<()> {+ upstream::reschedule_after_run(&opts(config), job, success, output)+}++pub fn record_run(+ config: &Config,+ job_id: &str,+ started_at: DateTime<Utc>,+ finished_at: DateTime<Utc>,+ status: &str,+ output: Option<&str>,+ duration_ms: i64,+) -> Result<()> {+ upstream::record_run(+ &opts(config),+ job_id,+ started_at,+ finished_at,+ status,+ output,+ duration_ms,+ )+}++/// Removes "queued" placeholder rows so only the real result row remains.+pub fn delete_queued_runs(config: &Config, job_id: &str) -> Result<usize> {+ upstream::delete_queued_runs(&opts(config), job_id)+}++pub fn list_runs(config: &Config, job_id: &str, limit: usize) -> Result<Vec<CronRun>> {+ upstream::list_runs(&opts(config), job_id, limit)+}#[cfg(test)]#[path = "store_tests.rs"]mod tests;--pub use jobs::{- add_agent_job, add_agent_job_with_definition, add_flow_schedule_job, add_job, add_shell_job,- clear_all_jobs, dedup_named_jobs, due_jobs, find_flow_schedule_job, get_job, list_jobs,- remove_job, update_job,-};-pub use runs::{delete_queued_runs, list_runs, record_last_run, record_run, reschedule_after_run};--// Re-exported (private `use`, visible to this module and its `tests`-// descendant) so `store_tests.rs` / its sub-test-modules can keep exercising-// the connection helper and the `rusqlite::params!` macro directly via-// `use super::*;`, exactly as when this was one spliced file.-#[allow(unused_imports)]-use runs::{MAX_CRON_OUTPUT_BYTES, TRUNCATED_OUTPUT_MARKER};-#[allow(unused_imports)]-use rusqlite::params;-#[allow(unused_imports)]-use schema::with_connection;diff --git a/crates/openhuman-core/src/cron/store/jobs.rs b/crates/openhuman-core/src/cron/store/jobs.rsdeleted file mode 100644index 89bd801be6..0000000000--- a/crates/openhuman-core/src/cron/store/jobs.rs+++ /dev/null@@ -1,494 +0,0 @@-//! Cron job CRUD: creating shell/agent/flow-schedule jobs, listing,-//! patching, deduplicating, and selecting due jobs.--use super::schema::{map_cron_job_row, with_connection};-use crate::config::Config;-use crate::cron::{- next_run_for_schedule, schedule_cron_expression, validate_agent_schedule, validate_schedule,- CronJob, CronJobPatch, DeliveryConfig, JobType, Schedule, SessionTarget,-};-use anyhow::{Context, Result};-use chrono::{DateTime, Utc};-use rusqlite::params;-use uuid::Uuid;--pub fn add_job(config: &Config, expression: &str, command: &str) -> Result<CronJob> {- let schedule = Schedule::Cron {- expr: expression.to_string(),- tz: None,- active_hours: None,- };- add_shell_job(config, None, schedule, command)-}--pub fn add_shell_job(- config: &Config,- name: Option<String>,- schedule: Schedule,- command: &str,-) -> Result<CronJob> {- let now = Utc::now();- validate_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();- let schedule_json = serde_json::to_string(&schedule)?;-- with_connection(config, |conn| {- conn.execute(- "INSERT INTO cron_jobs (- id, expression, command, schedule, job_type, prompt, name, session_target, model,- enabled, delivery, delete_after_run, created_at, next_run- ) VALUES (?1, ?2, ?3, ?4, 'shell', NULL, ?5, 'isolated', NULL, 1, ?6, 0, ?7, ?8)",- params![- id,- expression,- command,- schedule_json,- name,- serde_json::to_string(&DeliveryConfig::default())?,- now.to_rfc3339(),- next_run.to_rfc3339(),- ],- )- .context("Failed to insert cron shell job")?;- Ok(())- })?;-- get_job(config, &id)-}--#[allow(clippy::too_many_arguments)]-pub fn add_agent_job(- config: &Config,- name: Option<String>,- schedule: Schedule,- prompt: &str,- session_target: SessionTarget,- model: Option<String>,- delivery: Option<DeliveryConfig>,- delete_after_run: bool,-) -> Result<CronJob> {- add_agent_job_with_definition(- config,- name,- schedule,- prompt,- session_target,- model,- delivery,- delete_after_run,- None,- true,- )-}--/// Like [`add_agent_job`] but accepts an optional built-in agent definition-/// ID. When set, the scheduler resolves the agent definition from the-/// registry and runs with its prompt, tool allowlist, and iteration cap.-#[allow(clippy::too_many_arguments)]-pub fn add_agent_job_with_definition(- config: &Config,- name: Option<String>,- schedule: Schedule,- prompt: &str,- session_target: SessionTarget,- model: Option<String>,- delivery: Option<DeliveryConfig>,- delete_after_run: bool,- agent_id: Option<String>,- enabled: bool,-) -> Result<CronJob> {- let now = Utc::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();- let schedule_json = serde_json::to_string(&schedule)?;- let delivery = delivery.unwrap_or_default();-- with_connection(config, |conn| {- // `enabled` is bound (?13) rather than hard-coded so callers can insert a- // job in its final disabled state in one statement — important for opt-in- // jobs (e.g. the autopilot) where a create-then-disable sequence could- // leave the row enabled if the process died between the two writes.- conn.execute(- "INSERT INTO cron_jobs (- id, expression, command, schedule, job_type, prompt, name, session_target, model,- enabled, delivery, delete_after_run, created_at, next_run, agent_id- ) VALUES (?1, ?2, '', ?3, 'agent', ?4, ?5, ?6, ?7, ?13, ?8, ?9, ?10, ?11, ?12)",- params![- id,- expression,- schedule_json,- prompt,- name,- session_target.as_str(),- model,- serde_json::to_string(&delivery)?,- if delete_after_run { 1 } else { 0 },- now.to_rfc3339(),- next_run.to_rfc3339(),- agent_id,- if enabled { 1 } else { 0 },- ],- )- .context("Failed to insert cron agent job")?;- Ok(())- })?;-- get_job(config, &id)-}--/// Registers the cron job that fires a `flows::Flow`'s `schedule` trigger-/// (issue B2). The flow's id is stored in `command` — a flow-schedule job has-/// no shell command / agent prompt of its own, it only needs to name which-/// flow to tick (see `JobType::Flow`'s doc). On fire the scheduler publishes-/// `DomainEvent::FlowScheduleTick { flow_id: command }` instead of running-/// anything; `flows::bus::FlowTriggerSubscriber` does the actual dispatch.-///-/// Race-safe / idempotent: `bind_schedule_trigger` does check-then-act-/// (`find_flow_schedule_job` then this function), so two concurrent binds for-/// the same flow can both observe "no job yet". The `idx_cron_jobs_flow_command`-/// partial unique index (flow jobs only) turns the loser's `INSERT` into a-/// no-op via `ON CONFLICT ... DO NOTHING`, and that loser then looks up and-/// returns the winner's row instead of erroring — callers always get back-/// exactly one cron job for `flow_id`, never a duplicate and never a-/// constraint-violation error.-pub fn add_flow_schedule_job(- config: &Config,- flow_id: &str,- schedule: Schedule,-) -> Result<CronJob> {- let now = Utc::now();- validate_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();- let schedule_json = serde_json::to_string(&schedule)?;- let name = format!("flow:{flow_id}");-- let inserted_rows = with_connection(config, |conn| {- let rows = conn- .execute(- "INSERT INTO cron_jobs (- id, expression, command, schedule, job_type, prompt, name, session_target, model,- enabled, delivery, delete_after_run, created_at, next_run- ) VALUES (?1, ?2, ?3, ?4, 'flow', NULL, ?5, 'isolated', NULL, 1, ?6, 0, ?7, ?8)- ON CONFLICT (command) WHERE job_type = 'flow' DO NOTHING",- params![- id,- expression,- flow_id,- schedule_json,- name,- serde_json::to_string(&DeliveryConfig::default())?,- now.to_rfc3339(),- next_run.to_rfc3339(),- ],- )- .context("Failed to insert cron flow-schedule job")?;- Ok(rows)- })?;-- if inserted_rows > 0 {- get_job(config, &id)- } else {- // Lost the race — another caller already holds the flow-schedule job- // for this flow_id/command. Return its row rather than erroring so- // `add_flow_schedule_job` is safe to call twice concurrently.- tracing::debug!(- target: "cron",- %flow_id,- "[cron] add_flow_schedule_job: insert conflicted with an existing flow job — returning the existing binding"- );- find_flow_schedule_job(config, flow_id)?.with_context(|| {- format!(- "add_flow_schedule_job: insert for flow '{flow_id}' conflicted but no existing \- flow-schedule job was found"- )- })- }-}--/// Finds the cron job (if any) registered for a flow's `schedule` trigger —-/// used by `flows::ops::flows_set_enabled` to make enable/disable idempotent-/// (re-use the existing binding rather than creating a duplicate) and to tear-/// it down on disable.-pub fn find_flow_schedule_job(config: &Config, flow_id: &str) -> Result<Option<CronJob>> {- with_connection(config, |conn| {- let mut stmt = conn.prepare(- "SELECT id, expression, command, schedule, job_type, prompt, name, session_target, model,- enabled, delivery, delete_after_run, created_at, next_run, last_run, last_status, last_output,- agent_id- FROM cron_jobs WHERE job_type = 'flow' AND command = ?1 LIMIT 1",- )?;- let mut rows = stmt.query(params![flow_id])?;- match rows.next()? {- Some(row) => Ok(Some(map_cron_job_row(row)?)),- None => Ok(None),- }- })-}--pub fn list_jobs(config: &Config) -> Result<Vec<CronJob>> {- with_connection(config, |conn| {- let mut stmt = conn.prepare(- "SELECT id, expression, command, schedule, job_type, prompt, name, session_target, model,- enabled, delivery, delete_after_run, created_at, next_run, last_run, last_status, last_output,- agent_id- FROM cron_jobs ORDER BY next_run ASC",- )?;-- let rows = stmt.query_map([], map_cron_job_row)?;-- let mut jobs = Vec::new();- for row in rows {- jobs.push(row?);- }- Ok(jobs)- })-}--pub fn get_job(config: &Config, job_id: &str) -> Result<CronJob> {- with_connection(config, |conn| {- let mut stmt = conn.prepare(- "SELECT id, expression, command, schedule, job_type, prompt, name, session_target, model,- enabled, delivery, delete_after_run, created_at, next_run, last_run, last_status, last_output,- agent_id- FROM cron_jobs WHERE id = ?1",- )?;-- let mut rows = stmt.query(params![job_id])?;- if let Some(row) = rows.next()? {- map_cron_job_row(row).map_err(Into::into)- } else {- anyhow::bail!("Cron job '{job_id}' not found")- }- })-}--pub fn remove_job(config: &Config, id: &str) -> Result<()> {- let changed = with_connection(config, |conn| {- conn.execute("DELETE FROM cron_jobs WHERE id = ?1", params![id])- .context("Failed to delete cron job")- })?;-- if changed == 0 {- anyhow::bail!("Cron job '{id}' not found");- }-- println!("✅ Removed cron job {id}");- Ok(())-}--/// Deletes every cron job in the workspace. Returns the number of rows removed.-///-/// Intended for the `openhuman.test_reset` RPC used by E2E specs to wipe state-/// between tests without restarting the sidecar. The cron scheduler picks up-/// the empty table on its next tick — no in-memory cache to invalidate.-pub fn clear_all_jobs(config: &Config) -> Result<usize> {- let removed = with_connection(config, |conn| {- conn.execute("DELETE FROM cron_jobs", params![])- .context("Failed to clear cron jobs")- })?;- log::info!("[cron] cleared all cron jobs (removed {removed} rows)");- Ok(removed)-}--/// Remove duplicate cron jobs that share the same `name`.-///-/// Older builds used a non-atomic check-then-insert in `seed_proactive_agents`,-/// which allowed two identical rows (e.g. two `morning_briefing` entries) to-/// land in the database when the function raced or was called twice before the-/// first insert committed. The `cron_jobs` table has no `UNIQUE` constraint on-/// `name`, so both rows persist and the Routines screen renders two cards.-///-/// For each duplicated name this function keeps the row with the most-/// `cron_runs` history (ties broken by earliest `created_at`) and deletes-/// all others. Returns the total number of rows removed across all names.-///-/// Idempotent: calling it on a database with no duplicates removes nothing-/// and returns `Ok(0)`.-pub fn dedup_named_jobs(config: &Config) -> Result<usize> {- with_connection(config, |conn| {- // 1. Find all names that appear more than once.- let duplicated_names: Vec<String> = {- let mut stmt = conn.prepare(- "SELECT name FROM cron_jobs \- WHERE name IS NOT NULL \- GROUP BY name \- HAVING COUNT(*) > 1",- )?;- let names = stmt.query_map([], |row| row.get::<_, String>(0))?;- let mut out = Vec::new();- for n in names {- out.push(n?);- }- out- };-- if duplicated_names.is_empty() {- return Ok(0);- }-- let mut canonical_stmt = conn.prepare(- "SELECT j.id \- FROM cron_jobs j \- LEFT JOIN cron_runs r ON r.job_id = j.id \- WHERE j.name = ?1 \- GROUP BY j.id \- ORDER BY COUNT(r.id) DESC, j.created_at ASC, j.id ASC \- LIMIT 1",- )?;-- let mut total_removed = 0usize;- for name in &duplicated_names {- // 2. Find the canonical id: most run history, tie-break earliest created_at.- let canonical_id: Option<String> = {- let mut rows = canonical_stmt.query(params![name])?;- rows.next()?.map(|r| r.get::<_, String>(0)).transpose()?- };-- let Some(keep_id) = canonical_id else {- continue;- };-- // 3. Delete every other row sharing this name.- let deleted = conn.execute(- "DELETE FROM cron_jobs WHERE name = ?1 AND id != ?2",- params![name, keep_id],- )?;- log::info!(- "[cron] dedup_named_jobs: removed {deleted} duplicate(s) of '{name}' \- (keeping id={keep_id})"- );- total_removed += deleted;- }-- Ok(total_removed)- })-}--pub fn due_jobs(config: &Config, now: DateTime<Utc>) -> Result<Vec<CronJob>> {- let lim = i64::try_from(config.scheduler.max_tasks.max(1))- .context("Scheduler max_tasks overflows i64")?;- with_connection(config, |conn| {- let mut stmt = conn.prepare(- "SELECT id, expression, command, schedule, job_type, prompt, name, session_target, model,- enabled, delivery, delete_after_run, created_at, next_run, last_run, last_status, last_output,- agent_id- FROM cron_jobs- WHERE enabled = 1 AND next_run <= ?1- ORDER BY next_run ASC- LIMIT ?2",- )?;-- let rows = stmt.query_map(params![now.to_rfc3339(), lim], map_cron_job_row)?;-- let mut jobs = Vec::new();- for row in rows {- jobs.push(row?);- }- Ok(jobs)- })-}--pub fn update_job(config: &Config, job_id: &str, patch: CronJobPatch) -> Result<CronJob> {- let mut job = get_job(config, job_id)?;- let was_enabled = job.enabled;- let mut schedule_changed = false;-- if let Some(schedule) = patch.schedule {- // 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;- }- if let Some(command) = patch.command {- job.command = command;- }- if let Some(prompt) = patch.prompt {- job.prompt = Some(prompt);- }- if let Some(name) = patch.name {- job.name = Some(name);- }- if let Some(enabled) = patch.enabled {- job.enabled = enabled;- }- if let Some(delivery) = patch.delivery {- job.delivery = delivery;- }- if let Some(model) = patch.model {- job.model = Some(model);- }- if let Some(target) = patch.session_target {- job.session_target = target;- }- if let Some(delete_after_run) = patch.delete_after_run {- job.delete_after_run = delete_after_run;- }- if let Some(agent_id) = patch.agent_id {- job.agent_id = agent_id;- }- if schedule_changed {- job.next_run = next_run_for_schedule(&job.schedule, Utc::now())?;- } else if job.enabled && !was_enabled {- // Disabled→enabled transition (e.g. opting into a seeded morning- // briefing). A job that sat disabled past its originally computed- // next_run would otherwise fire immediately on opt-in, because the- // scheduler selects `enabled = 1 AND next_run <= now`. Refresh a stale- // next_run so the first run lands on the next scheduled occurrence- // rather than firing the instant the user flips the switch.- let now = Utc::now();- if job.next_run <= now {- let refreshed = next_run_for_schedule(&job.schedule, now)?;- tracing::debug!(- job_id = %job.id,- stale_next_run = %job.next_run.to_rfc3339(),- next_run = %refreshed.to_rfc3339(),- "[cron::update_job] refreshed stale next_run on disabled→enabled transition"- );- job.next_run = refreshed;- }- }-- with_connection(config, |conn| {- conn.execute(- "UPDATE cron_jobs- SET expression = ?1, command = ?2, schedule = ?3, job_type = ?4, prompt = ?5, name = ?6,- session_target = ?7, model = ?8, enabled = ?9, delivery = ?10, delete_after_run = ?11,- next_run = ?12, agent_id = ?14- WHERE id = ?13",- params![- job.expression,- job.command,- serde_json::to_string(&job.schedule)?,- job.job_type.as_str(),- job.prompt,- job.name,- job.session_target.as_str(),- job.model,- if job.enabled { 1 } else { 0 },- serde_json::to_string(&job.delivery)?,- if job.delete_after_run { 1 } else { 0 },- job.next_run.to_rfc3339(),- job.id,- job.agent_id,- ],- )- .context("Failed to update cron job")?;- Ok(())- })?;-- get_job(config, job_id)-}diff --git a/crates/openhuman-core/src/cron/store/runs.rs b/crates/openhuman-core/src/cron/store/runs.rsdeleted file mode 100644index a9c50e6dfa..0000000000--- a/crates/openhuman-core/src/cron/store/runs.rs+++ /dev/null@@ -1,176 +0,0 @@-//! Cron run-history persistence: recording job outcomes with bounded output,-//! pruning old history, and reading it back.--use super::schema::{parse_rfc3339, sql_conversion_error, with_connection};-use crate::config::Config;-use crate::cron::{next_run_for_schedule, CronJob, CronRun};-use anyhow::{Context, Result};-use chrono::{DateTime, Utc};-use rusqlite::params;--pub(crate) const MAX_CRON_OUTPUT_BYTES: usize = 16 * 1024;-pub(crate) const TRUNCATED_OUTPUT_MARKER: &str = "\n...[truncated]";--pub fn record_last_run(- config: &Config,- job_id: &str,- finished_at: DateTime<Utc>,- success: bool,- output: &str,-) -> Result<()> {- let status = if success { "ok" } else { "error" };- let bounded_output = truncate_cron_output(output);- with_connection(config, |conn| {- conn.execute(- "UPDATE cron_jobs- SET last_run = ?1, last_status = ?2, last_output = ?3- WHERE id = ?4",- params![finished_at.to_rfc3339(), status, bounded_output, job_id],- )- .context("Failed to update cron last run fields")?;- Ok(())- })-}--pub fn reschedule_after_run(- config: &Config,- job: &CronJob,- success: bool,- output: &str,-) -> Result<()> {- let now = Utc::now();- let next_run = next_run_for_schedule(&job.schedule, now)?;- let status = if success { "ok" } else { "error" };- let bounded_output = truncate_cron_output(output);-- with_connection(config, |conn| {- conn.execute(- "UPDATE cron_jobs- SET next_run = ?1, last_run = ?2, last_status = ?3, last_output = ?4- WHERE id = ?5",- params![- next_run.to_rfc3339(),- now.to_rfc3339(),- status,- bounded_output,- job.id- ],- )- .context("Failed to update cron job run state")?;- Ok(())- })-}--pub fn record_run(- config: &Config,- job_id: &str,- started_at: DateTime<Utc>,- finished_at: DateTime<Utc>,- status: &str,- output: Option<&str>,- duration_ms: i64,-) -> Result<()> {- let bounded_output = output.map(truncate_cron_output);- with_connection(config, |conn| {- // Wrap INSERT + pruning DELETE in an explicit transaction so that- // if the DELETE fails, the INSERT is rolled back and the run table- // cannot grow unboundedly.- let tx = conn.unchecked_transaction()?;-- tx.execute(- "INSERT INTO cron_runs (job_id, started_at, finished_at, status, output, duration_ms)- VALUES (?1, ?2, ?3, ?4, ?5, ?6)",- params![- job_id,- started_at.to_rfc3339(),- finished_at.to_rfc3339(),- status,- bounded_output.as_deref(),- duration_ms,- ],- )- .context("Failed to insert cron run")?;-- let keep = config.cron.max_run_history.max(1) as i64;- tx.execute(- "DELETE FROM cron_runs- WHERE job_id = ?1- AND id NOT IN (- SELECT id FROM cron_runs- WHERE job_id = ?1- ORDER BY started_at DESC, id DESC- LIMIT ?2- )",- params![job_id, keep],- )- .context("Failed to prune cron run history")?;-- tx.commit()- .context("Failed to commit cron run transaction")?;- Ok(())- })-}--/// Remove all "queued" placeholder records for a given job so that only the-/// real (ok/error) result row remains in the run history.-pub fn delete_queued_runs(config: &Config, job_id: &str) -> Result<usize> {- with_connection(config, |conn| {- let deleted = conn.execute(- "DELETE FROM cron_runs WHERE job_id = ?1 AND status = 'queued'",- params![job_id],- )?;- Ok(deleted)- })-}--fn truncate_cron_output(output: &str) -> String {- if output.len() <= MAX_CRON_OUTPUT_BYTES {- return output.to_string();- }-- if MAX_CRON_OUTPUT_BYTES <= TRUNCATED_OUTPUT_MARKER.len() {- return TRUNCATED_OUTPUT_MARKER.to_string();- }-- let mut cutoff = MAX_CRON_OUTPUT_BYTES - TRUNCATED_OUTPUT_MARKER.len();- while cutoff > 0 && !output.is_char_boundary(cutoff) {- cutoff -= 1;- }-- let mut truncated = output[..cutoff].to_string();- truncated.push_str(TRUNCATED_OUTPUT_MARKER);- truncated-}--pub fn list_runs(config: &Config, job_id: &str, limit: usize) -> Result<Vec<CronRun>> {- with_connection(config, |conn| {- let lim = i64::try_from(limit.max(1)).context("Run history limit overflow")?;- let mut stmt = conn.prepare(- "SELECT id, job_id, started_at, finished_at, status, output, duration_ms- FROM cron_runs- WHERE job_id = ?1- ORDER BY started_at DESC, id DESC- LIMIT ?2",- )?;-- let rows = stmt.query_map(params![job_id, lim], |row| {- Ok(CronRun {- id: row.get(0)?,- job_id: row.get(1)?,- started_at: parse_rfc3339(&row.get::<_, String>(2)?)- .map_err(sql_conversion_error)?,- finished_at: parse_rfc3339(&row.get::<_, String>(3)?)- .map_err(sql_conversion_error)?,- status: row.get(4)?,- output: row.get(5)?,- duration_ms: row.get(6)?,- })- })?;-- let mut runs = Vec::new();- for row in rows {- runs.push(row?);- }- Ok(runs)- })-}diff --git a/crates/openhuman-core/src/cron/store/schema.rs b/crates/openhuman-core/src/cron/store/schema.rsdeleted file mode 100644index 8d9c869190..0000000000--- a/crates/openhuman-core/src/cron/store/schema.rs+++ /dev/null@@ -1,195 +0,0 @@-//! Row mapping, JSON decoding of stored schedules/delivery, and the SQLite-//! connection + schema-migration helpers shared by the cron store's job and-//! run-history modules.--use crate::config::Config;-use crate::cron::{CronJob, DeliveryConfig, JobType, Schedule, SessionTarget};-use anyhow::{Context, Result};-use chrono::{DateTime, Utc};-use rusqlite::Connection;--pub(super) fn map_cron_job_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<CronJob> {- let expression: String = row.get(1)?;- let schedule_raw: Option<String> = row.get(3)?;- let schedule =- decode_schedule(schedule_raw.as_deref(), &expression).map_err(sql_conversion_error)?;-- let delivery_raw: Option<String> = row.get(10)?;- let delivery = decode_delivery(delivery_raw.as_deref()).map_err(sql_conversion_error)?;-- let next_run_raw: String = row.get(13)?;- let last_run_raw: Option<String> = row.get(14)?;- let created_at_raw: String = row.get(12)?;-- Ok(CronJob {- id: row.get(0)?,- expression,- schedule,- command: row.get(2)?,- job_type: JobType::parse(&row.get::<_, String>(4)?),- prompt: row.get(5)?,- name: row.get(6)?,- session_target: SessionTarget::parse(&row.get::<_, String>(7)?),- model: row.get(8)?,- agent_id: row.get(17)?,- enabled: row.get::<_, i64>(9)? != 0,- delivery,- delete_after_run: row.get::<_, i64>(11)? != 0,- created_at: parse_rfc3339(&created_at_raw).map_err(sql_conversion_error)?,- next_run: parse_rfc3339(&next_run_raw).map_err(sql_conversion_error)?,- last_run: match last_run_raw {- Some(raw) => Some(parse_rfc3339(&raw).map_err(sql_conversion_error)?),- None => None,- },- last_status: row.get(15)?,- last_output: row.get(16)?,- })-}--fn decode_schedule(schedule_raw: Option<&str>, expression: &str) -> Result<Schedule> {- if let Some(raw) = schedule_raw {- let trimmed = raw.trim();- if !trimmed.is_empty() {- return serde_json::from_str(trimmed)- .with_context(|| format!("Failed to parse cron schedule JSON: {trimmed}"));- }- }-- if expression.trim().is_empty() {- anyhow::bail!("Missing schedule and legacy expression for cron job")- }-- Ok(Schedule::Cron {- expr: expression.to_string(),- tz: None,- active_hours: None,- })-}--fn decode_delivery(delivery_raw: Option<&str>) -> Result<DeliveryConfig> {- if let Some(raw) = delivery_raw {- let trimmed = raw.trim();- if !trimmed.is_empty() {- return serde_json::from_str(trimmed)- .with_context(|| format!("Failed to parse cron delivery JSON: {trimmed}"));- }- }- Ok(DeliveryConfig::default())-}--fn add_column_if_missing(conn: &Connection, name: &str, sql_type: &str) -> Result<()> {- let mut stmt = conn.prepare("PRAGMA table_info(cron_jobs)")?;- let mut rows = stmt.query([])?;- while let Some(row) = rows.next()? {- let col_name: String = row.get(1)?;- if col_name == name {- return Ok(());- }- }- // Drop the statement/rows before executing ALTER to release any locks- drop(rows);- drop(stmt);-- // Tolerate "duplicate column name" errors to handle the race where- // another process adds the column between our PRAGMA check and ALTER.- match conn.execute(- &format!("ALTER TABLE cron_jobs ADD COLUMN {name} {sql_type}"),- [],- ) {- Ok(_) => Ok(()),- Err(rusqlite::Error::SqliteFailure(err, Some(ref msg)))- if msg.contains("duplicate column name") =>- {- tracing::debug!("Column cron_jobs.{name} already exists (concurrent migration): {err}");- Ok(())- }- Err(e) => Err(e).with_context(|| format!("Failed to add cron_jobs.{name}")),- }-}--pub(super) fn with_connection<T>(- config: &Config,- f: impl FnOnce(&Connection) -> Result<T>,-) -> Result<T> {- let db_path = config.workspace_dir.join("cron").join("jobs.db");- if let Some(parent) = db_path.parent() {- std::fs::create_dir_all(parent)- .with_context(|| format!("Failed to create cron directory: {}", parent.display()))?;- }-- let conn = Connection::open(&db_path)- .with_context(|| format!("Failed to open cron DB: {}", db_path.display()))?;-- conn.execute_batch(- "PRAGMA foreign_keys = ON;- CREATE TABLE IF NOT EXISTS cron_jobs (- id TEXT PRIMARY KEY,- expression TEXT NOT NULL,- command TEXT NOT NULL,- schedule TEXT,- job_type TEXT NOT NULL DEFAULT 'shell',- prompt TEXT,- name TEXT,- session_target TEXT NOT NULL DEFAULT 'isolated',- model TEXT,- enabled INTEGER NOT NULL DEFAULT 1,- delivery TEXT,- delete_after_run INTEGER NOT NULL DEFAULT 0,- created_at TEXT NOT NULL,- next_run TEXT NOT NULL,- last_run TEXT,- last_status TEXT,- last_output TEXT- );- CREATE INDEX IF NOT EXISTS idx_cron_jobs_next_run ON cron_jobs(next_run);-- CREATE TABLE IF NOT EXISTS cron_runs (- id INTEGER PRIMARY KEY AUTOINCREMENT,- job_id TEXT NOT NULL,- started_at TEXT NOT NULL,- finished_at TEXT NOT NULL,- status TEXT NOT NULL,- output TEXT,- duration_ms INTEGER,- FOREIGN KEY (job_id) REFERENCES cron_jobs(id) ON DELETE CASCADE- );- CREATE INDEX IF NOT EXISTS idx_cron_runs_job_id ON cron_runs(job_id);- CREATE INDEX IF NOT EXISTS idx_cron_runs_started_at ON cron_runs(started_at);- CREATE INDEX IF NOT EXISTS idx_cron_runs_job_started ON cron_runs(job_id, started_at);-- -- Guards against duplicate flow-schedule cron bindings under a- -- concurrent `bind_schedule_trigger` (issue B2 CodeRabbit finding):- -- `flows::ops::bind_schedule_trigger` does check-then-act- -- (`find_flow_schedule_job` then `add_flow_schedule_job`), so two- -- racing binds for the same flow could otherwise each observe 'no- -- job' and insert a duplicate. Scoped to `job_type = 'flow'` via a- -- partial index so it can never constrain shell/agent jobs, which- -- may legitimately share a `command`.- CREATE UNIQUE INDEX IF NOT EXISTS idx_cron_jobs_flow_command- ON cron_jobs(command) WHERE job_type = 'flow';",- )- .context("Failed to initialize cron schema")?;-- add_column_if_missing(&conn, "schedule", "TEXT")?;- add_column_if_missing(&conn, "job_type", "TEXT NOT NULL DEFAULT 'shell'")?;- add_column_if_missing(&conn, "prompt", "TEXT")?;- add_column_if_missing(&conn, "name", "TEXT")?;- add_column_if_missing(&conn, "session_target", "TEXT NOT NULL DEFAULT 'isolated'")?;- add_column_if_missing(&conn, "model", "TEXT")?;- add_column_if_missing(&conn, "enabled", "INTEGER NOT NULL DEFAULT 1")?;- add_column_if_missing(&conn, "delivery", "TEXT")?;- add_column_if_missing(&conn, "delete_after_run", "INTEGER NOT NULL DEFAULT 0")?;- add_column_if_missing(&conn, "agent_id", "TEXT")?;-- f(&conn)-}--pub(super) fn parse_rfc3339(raw: &str) -> Result<DateTime<Utc>> {- let parsed = DateTime::parse_from_rfc3339(raw)- .with_context(|| format!("Invalid RFC3339 timestamp in cron DB: {raw}"))?;- Ok(parsed.with_timezone(&Utc))-}--pub(super) fn sql_conversion_error(err: anyhow::Error) -> rusqlite::Error {- rusqlite::Error::ToSqlConversionFailure(err.into())-}diff --git a/crates/openhuman-core/src/cron/store_agent_floor_tests.rs b/crates/openhuman-core/src/cron/store_agent_floor_tests.rsdeleted file mode 100644index 67c5ada0dd..0000000000--- a/crates/openhuman-core/src/cron/store_agent_floor_tests.rs+++ /dev/null@@ -1,144 +0,0 @@-use super::*;--use crate::cron::CronJob;-use crate::cron::CronJobPatch;-use crate::cron::Schedule;-use crate::cron::SessionTarget;-use anyhow::Result;-// ── 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/crates/openhuman-core/src/cron/store_tests.rs b/crates/openhuman-core/src/cron/store_tests.rsdeleted file mode 100644index c3d617b931..0000000000--- a/crates/openhuman-core/src/cron/store_tests.rs+++ /dev/null@@ -1,543 +0,0 @@-use super::*;-use crate::config::Config;-use crate::cron::ActiveHours;-use chrono::Duration as ChronoDuration;-use chrono::Utc;-use tempfile::TempDir;--use crate::cron::CronJobPatch;-use crate::cron::JobType;-use crate::cron::Schedule;-fn test_config(tmp: &TempDir) -> Config {- let config = Config {- workspace_dir: tmp.path().join("workspace"),- action_dir: tmp.path().join("workspace"),- config_path: tmp.path().join("config.toml"),- ..Config::default()- };- std::fs::create_dir_all(&config.workspace_dir).unwrap();- config-}--#[test]-fn add_job_accepts_five_field_expression() {- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);-- let job = add_job(&config, "*/5 * * * *", "echo ok").unwrap();- assert_eq!(job.expression, "*/5 * * * *");- assert_eq!(job.command, "echo ok");- assert!(matches!(job.schedule, Schedule::Cron { .. }));-}--#[test]-fn add_shell_job_persists_active_hours_schedule() {- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);- let active_hours = ActiveHours {- start: "09:00".into(),- end: "17:00".into(),- };-- let job = add_shell_job(- &config,- Some("business-hours".into()),- Schedule::Cron {- expr: "0 9 * * *".into(),- tz: Some("UTC".into()),- active_hours: Some(active_hours.clone()),- },- "echo ok",- )- .unwrap();-- let stored = get_job(&config, &job.id).unwrap();- assert_eq!(stored.expression, "0 9 * * *");- assert_eq!(- stored.schedule,- Schedule::Cron {- expr: "0 9 * * *".into(),- tz: Some("UTC".into()),- active_hours: Some(active_hours),- }- );-}--#[test]-fn add_list_remove_roundtrip() {- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);-- let job = add_job(&config, "*/10 * * * *", "echo roundtrip").unwrap();- let listed = list_jobs(&config).unwrap();- assert_eq!(listed.len(), 1);- assert_eq!(listed[0].id, job.id);-- remove_job(&config, &job.id).unwrap();- assert!(list_jobs(&config).unwrap().is_empty());-}--#[test]-fn due_jobs_filters_by_timestamp_and_enabled() {- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);-- let job = add_job(&config, "* * * * *", "echo due").unwrap();-- let before_next_run = job.next_run - ChronoDuration::seconds(1);- let due_before_next_run = due_jobs(&config, before_next_run).unwrap();- assert!(- due_before_next_run.is_empty(),- "job should not be due before its next_run timestamp"- );-- let due_at_next_run = due_jobs(&config, job.next_run).unwrap();- assert_eq!(due_at_next_run.len(), 1, "job should be due at next_run");-- let _ = update_job(- &config,- &job.id,- CronJobPatch {- enabled: Some(false),- ..CronJobPatch::default()- },- )- .unwrap();- let due_after_disable = due_jobs(&config, job.next_run).unwrap();- assert!(due_after_disable.is_empty());-}--#[test]-fn enabling_stale_disabled_job_refreshes_next_run() {- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);-- // Daily 7 AM job, then disable it (mimics a seeded opt-in morning briefing).- let job = add_job(&config, "0 7 * * *", "echo briefing").unwrap();- update_job(- &config,- &job.id,- CronJobPatch {- enabled: Some(false),- ..CronJobPatch::default()- },- )- .unwrap();-- // Force a stale next_run in the past, as if the user onboarded before the- // job's first scheduled fire and only opted in later (hours or days after).- let stale = Utc::now() - ChronoDuration::hours(2);- with_connection(&config, |conn| {- conn.execute(- "UPDATE cron_jobs SET next_run = ?1 WHERE id = ?2",- params![stale.to_rfc3339(), job.id],- )?;- Ok(())- })- .unwrap();-- // Opt in: disabled -> enabled, with the schedule unchanged.- let enabled = update_job(- &config,- &job.id,- CronJobPatch {- enabled: Some(true),- ..CronJobPatch::default()- },- )- .unwrap();-- assert!(enabled.enabled);- assert!(- enabled.next_run > Utc::now(),- "enabling a job with a stale next_run must refresh it to the future, got {}",- enabled.next_run- );- assert!(- due_jobs(&config, Utc::now()).unwrap().is_empty(),- "freshly opted-in job must not fire immediately on enable"- );-}--#[test]-fn enabling_job_with_future_next_run_preserves_it() {- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);-- let job = add_job(&config, "0 7 * * *", "echo briefing").unwrap();- update_job(- &config,- &job.id,- CronJobPatch {- enabled: Some(false),- ..CronJobPatch::default()- },- )- .unwrap();-- // A future next_run is still valid and must be left untouched on enable.- let future = Utc::now() + ChronoDuration::hours(3);- with_connection(&config, |conn| {- conn.execute(- "UPDATE cron_jobs SET next_run = ?1 WHERE id = ?2",- params![future.to_rfc3339(), job.id],- )?;- Ok(())- })- .unwrap();-- let enabled = update_job(- &config,- &job.id,- CronJobPatch {- enabled: Some(true),- ..CronJobPatch::default()- },- )- .unwrap();-- assert_eq!(- enabled.next_run.to_rfc3339(),- future.to_rfc3339(),- "enabling a job whose next_run is in the future must not reschedule it"- );-}--#[test]-fn due_jobs_respects_scheduler_max_tasks_limit() {- let tmp = TempDir::new().unwrap();- let mut config = test_config(&tmp);- config.scheduler.max_tasks = 2;-- let _ = add_job(&config, "* * * * *", "echo due-1").unwrap();- let _ = add_job(&config, "* * * * *", "echo due-2").unwrap();- let _ = add_job(&config, "* * * * *", "echo due-3").unwrap();-- let far_future = Utc::now() + ChronoDuration::days(365);- let due = due_jobs(&config, far_future).unwrap();- assert_eq!(due.len(), 2);-}--#[test]-fn reschedule_after_run_persists_last_status_and_last_run() {- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);-- let job = add_job(&config, "*/15 * * * *", "echo run").unwrap();- reschedule_after_run(&config, &job, false, "failed output").unwrap();-- let listed = list_jobs(&config).unwrap();- let stored = listed.iter().find(|j| j.id == job.id).unwrap();- assert_eq!(stored.last_status.as_deref(), Some("error"));- assert!(stored.last_run.is_some());- assert_eq!(stored.last_output.as_deref(), Some("failed output"));-}--#[test]-fn migration_falls_back_to_legacy_expression() {- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);-- with_connection(&config, |conn| {- conn.execute(- "INSERT INTO cron_jobs (id, expression, command, created_at, next_run)- VALUES (?1, ?2, ?3, ?4, ?5)",- params![- "legacy-id",- "*/5 * * * *",- "echo legacy",- Utc::now().to_rfc3339(),- (Utc::now() + ChronoDuration::minutes(5)).to_rfc3339(),- ],- )?;- conn.execute(- "UPDATE cron_jobs SET schedule = NULL WHERE id = 'legacy-id'",- [],- )?;- Ok(())- })- .unwrap();-- let job = get_job(&config, "legacy-id").unwrap();- assert!(matches!(job.schedule, Schedule::Cron { .. }));-}--#[test]-fn record_and_prune_runs() {- let tmp = TempDir::new().unwrap();- let mut config = test_config(&tmp);- config.cron.max_run_history = 2;- let job = add_job(&config, "*/5 * * * *", "echo ok").unwrap();- let base = Utc::now();-- for idx in 0..3 {- let start = base + ChronoDuration::seconds(idx);- let end = start + ChronoDuration::milliseconds(100);- record_run(&config, &job.id, start, end, "ok", Some("done"), 100).unwrap();- }-- let runs = list_runs(&config, &job.id, 10).unwrap();- assert_eq!(runs.len(), 2);-}--#[test]-fn remove_job_cascades_run_history() {- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);- let job = add_job(&config, "*/5 * * * *", "echo ok").unwrap();- let start = Utc::now();- record_run(- &config,- &job.id,- start,- start + ChronoDuration::milliseconds(5),- "ok",- Some("ok"),- 5,- )- .unwrap();-- remove_job(&config, &job.id).unwrap();- let runs = list_runs(&config, &job.id, 10).unwrap();- assert!(runs.is_empty());-}--#[test]-fn record_run_truncates_large_output() {- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);- let job = add_job(&config, "*/5 * * * *", "echo trunc").unwrap();- let output = "x".repeat(MAX_CRON_OUTPUT_BYTES + 512);-- record_run(- &config,- &job.id,- Utc::now(),- Utc::now(),- "ok",- Some(&output),- 1,- )- .unwrap();-- let runs = list_runs(&config, &job.id, 1).unwrap();- let stored = runs[0].output.as_deref().unwrap_or_default();- assert!(stored.ends_with(TRUNCATED_OUTPUT_MARKER));- assert!(stored.len() <= MAX_CRON_OUTPUT_BYTES);-}--#[test]-fn reschedule_after_run_truncates_last_output() {- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);- let job = add_job(&config, "*/5 * * * *", "echo trunc").unwrap();- let output = "y".repeat(MAX_CRON_OUTPUT_BYTES + 1024);-- reschedule_after_run(&config, &job, false, &output).unwrap();-- let stored = get_job(&config, &job.id).unwrap();- let last_output = stored.last_output.as_deref().unwrap_or_default();- assert!(last_output.ends_with(TRUNCATED_OUTPUT_MARKER));- assert!(last_output.len() <= MAX_CRON_OUTPUT_BYTES);-}--// ── dedup_named_jobs ─────────────────────────────────────────────--#[test]-fn dedup_named_jobs_no_op_on_empty_db() {- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);- let removed = dedup_named_jobs(&config).unwrap();- assert_eq!(removed, 0);-}--#[test]-fn dedup_named_jobs_no_op_when_no_duplicates() {- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);- add_shell_job(- &config,- Some("job_a".into()),- Schedule::Cron {- expr: "*/5 * * * *".into(),- tz: None,- active_hours: None,- },- "echo a",- )- .unwrap();- add_shell_job(- &config,- Some("job_b".into()),- Schedule::Cron {- expr: "*/10 * * * *".into(),- tz: None,- active_hours: None,- },- "echo b",- )- .unwrap();- let removed = dedup_named_jobs(&config).unwrap();- assert_eq!(removed, 0);- assert_eq!(list_jobs(&config).unwrap().len(), 2);-}--#[test]-fn dedup_named_jobs_removes_duplicates_keeping_history() {- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);-- // Insert two jobs with the same name directly — simulating the old double-seed bug.- let job_a = add_shell_job(- &config,- Some("morning_briefing".into()),- Schedule::Cron {- expr: "0 7 * * *".into(),- tz: None,- active_hours: None,- },- "echo briefing",- )- .unwrap();- let job_b = add_shell_job(- &config,- Some("morning_briefing".into()),- Schedule::Cron {- expr: "0 7 * * *".into(),- tz: None,- active_hours: None,- },- "echo briefing",- )- .unwrap();-- // Add run history to job_a — it should survive.- let now = Utc::now();- record_run(- &config,- &job_a.id,- now,- now + ChronoDuration::seconds(1),- "ok",- Some("output"),- 1000,- )- .unwrap();-- let removed = dedup_named_jobs(&config).unwrap();- assert_eq!(removed, 1);-- let remaining = list_jobs(&config).unwrap();- assert_eq!(remaining.len(), 1);- assert_eq!(- remaining[0].id, job_a.id,- "job with run history should be kept"- );- assert!(- get_job(&config, &job_b.id).is_err(),- "duplicate without history should be removed"- );-}--#[test]-fn dedup_named_jobs_keeps_earliest_when_history_tied() {- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);-- // Both jobs have no run history — tie broken by earliest created_at.- let job_a = add_shell_job(- &config,- Some("routine".into()),- Schedule::Cron {- expr: "0 8 * * *".into(),- tz: None,- active_hours: None,- },- "echo first",- )- .unwrap();- let job_b = add_shell_job(- &config,- Some("routine".into()),- Schedule::Cron {- expr: "0 8 * * *".into(),- tz: None,- active_hours: None,- },- "echo second",- )- .unwrap();-- let removed = dedup_named_jobs(&config).unwrap();- assert_eq!(removed, 1);-- let remaining = list_jobs(&config).unwrap();- assert_eq!(remaining.len(), 1);- // job_a was created first — it should win the tie.- assert_eq!(remaining[0].id, job_a.id, "earliest job should be kept");- assert!(get_job(&config, &job_b.id).is_err());-}--// ── add_flow_schedule_job race-safety (CodeRabbit finding A) ────────--#[test]-fn add_flow_schedule_job_twice_yields_a_single_row() {- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);- let schedule = Schedule::Cron {- expr: "0 9 * * *".into(),- tz: None,- active_hours: None,- };-- let first = add_flow_schedule_job(&config, "flow-1", schedule.clone()).unwrap();- let second = add_flow_schedule_job(&config, "flow-1", schedule).unwrap();-- // Calling it twice for the same flow must not create a duplicate — the- // second call returns the same row the first one created.- assert_eq!(first.id, second.id);-- let flow_jobs: Vec<_> = list_jobs(&config)- .unwrap()- .into_iter()- .filter(|j| j.job_type == JobType::Flow && j.command == "flow-1")- .collect();- assert_eq!(- flow_jobs.len(),- 1,- "exactly one job_type='flow' row should exist for flow-1"- );-}--#[test]-fn add_flow_schedule_job_unique_index_does_not_affect_shell_jobs() {- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);-- // Two shell jobs sharing the same command must both persist — the new- // partial unique index is scoped to job_type = 'flow' and must not- // constrain shell/agent jobs, which may legitimately share a command.- let shell_a = add_job(&config, "*/5 * * * *", "echo shared").unwrap();- let shell_b = add_job(&config, "*/10 * * * *", "echo shared").unwrap();-- assert!(get_job(&config, &shell_a.id).is_ok());- assert!(get_job(&config, &shell_b.id).is_ok());- assert_eq!(list_jobs(&config).unwrap().len(), 2);-}--#[test]-fn dedup_named_jobs_ignores_unnamed_jobs() {- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);-- // Unnamed jobs (name = NULL) — dedup should not touch them.- add_job(&config, "*/5 * * * *", "echo unnamed-1").unwrap();- add_job(&config, "*/5 * * * *", "echo unnamed-2").unwrap();-- let removed = dedup_named_jobs(&config).unwrap();- assert_eq!(removed, 0);- assert_eq!(list_jobs(&config).unwrap().len(), 2);-}--#[path = "store_agent_floor_tests.rs"]-mod agent_floor_tests;