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): persist job state across restarts
Steven Enamakelff377574c71e
diff --git a/crates/openhuman-core/src/cron/store.rs b/crates/openhuman-core/src/cron/store.rsindex 192b5b81b4..8353cdc5c9 100644--- a/crates/openhuman-core/src/cron/store.rs+++ b/crates/openhuman-core/src/cron/store.rs@@ -1,13 +1,15 @@-//! Cron persistence: a thin host wrapper over `tinyflows_sqlite::schedule`.+//! Cron persistence: a thin host binding of `tinyflows_drivers::schedule::CronDocuments`.//!-//! With a storage backend configured ([`crate::storage`]) every function is-//! served by `tinyflows_drivers::schedule::CronDocuments` instead, in the-//! acting agent's storage scope, with the same limits.+//! Jobs, run history and per-job policy live on the storage ports, in the+//! acting agent's scope of the installed backend ([`crate::storage`]) or, when+//! the host configured none, in a SQLite document store of their own+//! (`<workspace>/cron/schedule.db`, an embedded agent's under+//! `agents/<id>/cron/`). tinyflows no longer has a SQLite store of its own: the+//! `jobs.db` it wrote is imported once, read-only, on first use+//! ([`crate::storage::import`]).//!-//! 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`.+//! This module only turns the host [`Config`] into the store's limits+//! (run-history cap, due-job batch size), so callers keep passing `&Config`.use crate::config::Config;use anyhow::Result;@@ -19,33 +21,60 @@ use tinyflows_schedule::{};use super::limits;-use tinyflows_sqlite::schedule::{self as upstream, AgentJobSpec, CronStoreOptions};+pub use tinyflows_schedule::AgentJobSpec;-/// The job database for `config`: `<workspace>/cron/jobs.db`, or the agent's-/// own `<workspace>/agents/<id>/cron/jobs.db` under an embedded agent's-/// context, so an agent lists, edits and runs only the jobs it created.+/// The cron store's own database for `config`: `<workspace>/cron/schedule.db`,+/// or the agent's `<workspace>/agents/<id>/cron/schedule.db` under an embedded+/// agent's context, so an agent lists, edits and runs only the jobs it+/// created. Used only when no storage backend is installed.pub fn db_path(config: &Config) -> std::path::PathBuf {crate::core::runtime::agent_scope_dir(config).join("cron")- .join("jobs.db")+ .join("schedule.db")}-/// Builds the store options from the host config: [`db_path`],-/// `cron.max_run_history`, `scheduler.max_tasks`.-fn opts(config: &Config) -> CronStoreOptions {- CronStoreOptions {- db_path: db_path(config),- max_run_history: config.cron.max_run_history,- max_tasks: config.scheduler.max_tasks,- }+/// The cron database tinyflows used to write, imported on first use.+pub fn legacy_db_path(config: &Config) -> std::path::PathBuf {+ crate::storage::import::tinyflows::legacy_jobs_db(&crate::core::runtime::agent_scope_dir(+ config,+ ))+}++/// The cron job store for this call, in the acting agent's scope.+fn documents(config: &Config) -> Result<CronDocuments> {+ let opened = crate::storage::local::open_standing(+ &db_path(config),+ "cron::store",+ config,+ &|backend, scope, config| legacy_import(backend, scope, config),+ )?;+ Ok(CronDocuments::new(std::sync::Arc::clone(opened.scoped()?.documents()))+ .with_limits(config.cron.max_run_history, config.scheduler.max_tasks))+}++/// Brings `jobs.db` into a freshly opened per-store database (the default+/// layout; with a backend installed the boot-time import did it).+#[cfg(feature = "flows")]+fn legacy_import(+ backend: &std::sync::Arc<dyn crate::storage::StorageBackend>,+ scope: &crate::storage::Scope,+ config: &Config,+) -> Result<()> {+ let dir = crate::core::runtime::agent_scope_dir(config);+ crate::storage::import::tinyflows::import_cron(backend, scope, config, &dir, "")?;+ Ok(())}-/// The document store for this call when the host configured a backend.-fn documents(config: &Config) -> Result<Option<CronDocuments>> {- Ok(crate::storage::current_scoped()?.map(|scoped| {- CronDocuments::new(std::sync::Arc::clone(scoped.documents()))- .with_limits(config.cron.max_run_history, config.scheduler.max_tasks)- }))+#[cfg(not(feature = "flows"))]+fn legacy_import(+ _backend: &std::sync::Arc<dyn crate::storage::StorageBackend>,+ _scope: &crate::storage::Scope,+ config: &Config,+) -> Result<()> {+ if legacy_db_path(config).is_file() {+ tracing::warn!("[cron:store] built without `flows`; the legacy jobs.db is not imported");+ }+ Ok(())}/// Runs a document-store call from this synchronous API.@@ -62,11 +91,9 @@ pub fn add_job(config: &Config, expression: &str, command: &str) -> Result<CronJactive_hours: None,};limits::check_new(config, &JobType::Shell, &schedule, None)?;- if let Some(docs) = documents(config)? {- let (expression, command) = (expression.to_string(), command.to_string());- return run(async move { docs.add_job(&expression, &command).await });- }- upstream::add_job(&opts(config), expression, command)+ let docs = documents(config)?;+ let (expression, command) = (expression.to_string(), command.to_string());+ return run(async move { docs.add_job(&expression, &command).await })}pub fn add_shell_job(@@ -76,11 +103,9 @@ pub fn add_shell_job(command: &str,) -> Result<CronJob> {limits::check_new(config, &JobType::Shell, &schedule, None)?;- if let Some(docs) = documents(config)? {- let command = command.to_string();- return run(async move { docs.add_shell_job(name, schedule, &command).await });- }- upstream::add_shell_job(&opts(config), name, schedule, command)+ let docs = documents(config)?;+ let command = command.to_string();+ return run(async move { docs.add_shell_job(name, schedule, &command).await })}#[allow(clippy::too_many_arguments)]@@ -95,31 +120,20 @@ pub fn add_agent_job(delete_after_run: bool,) -> Result<CronJob> {limits::check_new(config, &JobType::Agent, &schedule, delivery.as_ref())?;- if let Some(docs) = documents(config)? {- let prompt = prompt.to_string();- return run(async move {- docs.add_agent_job(- name,- schedule,- &prompt,- session_target,- model,- delivery,- delete_after_run,- )- .await- });- }- upstream::add_agent_job(- &opts(config),- name,- schedule,- prompt,- session_target,- model,- delivery,- delete_after_run,- )+ let docs = documents(config)?;+ let prompt = prompt.to_string();+ return run(async move {+ docs.add_agent_job(+ name,+ schedule,+ &prompt,+ session_target,+ model,+ delivery,+ delete_after_run,+ )+ .await+ })}/// Like [`add_agent_job`] but accepts an optional built-in agent definition@@ -138,35 +152,22 @@ pub fn add_agent_job_with_definition(enabled: bool,) -> Result<CronJob> {limits::check_new(config, &JobType::Agent, &schedule, delivery.as_ref())?;- if let Some(docs) = documents(config)? {- let prompt = prompt.to_string();- return run(async move {- docs.add_agent_job_with_definition(- name,- schedule,- &prompt,- session_target,- model,- delivery,- delete_after_run,- agent_id,- enabled,- )- .await- });- }- upstream::add_agent_job_with_definition(- &opts(config),- name,- schedule,- prompt,- session_target,- model,- delivery,- delete_after_run,- agent_id,- enabled,- )+ let docs = documents(config)?;+ let prompt = prompt.to_string();+ return run(async move {+ docs.add_agent_job_with_definition(+ name,+ schedule,+ &prompt,+ session_target,+ model,+ delivery,+ delete_after_run,+ agent_id,+ enabled,+ )+ .await+ })}/// Adds an agent job described by `spec`, including its origin conversation.@@ -177,10 +178,8 @@ pub fn add_agent_job_from_spec(config: &Config, spec: AgentJobSpec) -> Result<Cr&spec.schedule,spec.delivery.as_ref(),)?;- if let Some(docs) = documents(config)? {- return run(async move { docs.add_agent_job_from_spec(spec).await });- }- upstream::add_agent_job_from_spec(&opts(config), spec)+ let docs = documents(config)?;+ return run(async move { docs.add_agent_job_from_spec(spec).await })}/// Registers (idempotently) the cron job that fires a flow's `schedule`@@ -191,52 +190,37 @@ pub fn add_flow_schedule_job(schedule: Schedule,) -> Result<CronJob> {limits::check_new(config, &JobType::Flow, &schedule, None)?;- if let Some(docs) = documents(config)? {- let flow_id = flow_id.to_string();- return run(async move { docs.add_flow_schedule_job(&flow_id, schedule).await });- }- upstream::add_flow_schedule_job(&opts(config), flow_id, schedule)+ let docs = documents(config)?;+ let flow_id = flow_id.to_string();+ return run(async move { docs.add_flow_schedule_job(&flow_id, schedule).await })}pub fn find_flow_schedule_job(config: &Config, flow_id: &str) -> Result<Option<CronJob>> {- if let Some(docs) = documents(config)? {- let flow_id = flow_id.to_string();- return run(async move { docs.find_flow_schedule_job(&flow_id).await });- }- upstream::find_flow_schedule_job(&opts(config), flow_id)+ let docs = documents(config)?;+ let flow_id = flow_id.to_string();+ return run(async move { docs.find_flow_schedule_job(&flow_id).await })}pub fn list_jobs(config: &Config) -> Result<Vec<CronJob>> {- if let Some(docs) = documents(config)? {- return run(async move { docs.list_jobs().await });- }- upstream::list_jobs(&opts(config))+ let docs = documents(config)?;+ return run(async move { docs.list_jobs().await })}pub fn get_job(config: &Config, job_id: &str) -> Result<CronJob> {- if let Some(docs) = documents(config)? {- let job_id = job_id.to_string();- return run(async move { docs.get_job(&job_id).await });- }- upstream::get_job(&opts(config), job_id)+ let docs = documents(config)?;+ let job_id = job_id.to_string();+ return run(async move { docs.get_job(&job_id).await })}pub fn remove_job(config: &Config, id: &str) -> Result<()> {- if let Some(docs) = documents(config)? {- let owned = id.to_string();- run(async move { docs.remove_job(&owned).await })?;- if let Err(error) = super::policy::clear_policy(config, id) {- tracing::warn!(job_id = id, %error, "[cron:store] removing job policy failed");- }- println!("✅ Removed cron job {id}");- return Ok(());- }- upstream::remove_job(&opts(config), id)?;+ let docs = documents(config)?;+ let owned = id.to_string();+ run(async move { docs.remove_job(&owned).await })?;if let Err(error) = super::policy::clear_policy(config, id) {tracing::warn!(job_id = id, %error, "[cron:store] removing job policy failed");}println!("✅ Removed cron job {id}");- Ok(())+ return Ok(())}/// Deletes every cron job in the workspace (E2E `openhuman.test_reset`).@@ -254,26 +238,20 @@ pub fn clear_all_jobs(config: &Config) -> Result<usize> {/// Removes duplicate jobs sharing a `name`, keeping the one with most history.pub fn dedup_named_jobs(config: &Config) -> Result<usize> {- if let Some(docs) = documents(config)? {- return run(async move { docs.dedup_named_jobs().await });- }- upstream::dedup_named_jobs(&opts(config))+ let docs = documents(config)?;+ return run(async move { docs.dedup_named_jobs().await })}pub fn due_jobs(config: &Config, now: DateTime<Utc>) -> Result<Vec<CronJob>> {- if let Some(docs) = documents(config)? {- return run(async move { docs.due_jobs(now).await });- }- upstream::due_jobs(&opts(config), now)+ let docs = documents(config)?;+ return run(async move { docs.due_jobs(now).await })}pub fn update_job(config: &Config, job_id: &str, patch: CronJobPatch) -> Result<CronJob> {limits::check_patch(config, &patch)?;- if let Some(docs) = documents(config)? {- let job_id = job_id.to_string();- return run(async move { docs.update_job(&job_id, patch).await });- }- upstream::update_job(&opts(config), job_id, patch)+ let docs = documents(config)?;+ let job_id = job_id.to_string();+ return run(async move { docs.update_job(&job_id, patch).await })}pub fn record_last_run(@@ -283,14 +261,12 @@ pub fn record_last_run(success: bool,output: &str,) -> Result<()> {- if let Some(docs) = documents(config)? {- let (job_id, output) = (job_id.to_string(), output.to_string());- return run(async move {- docs.record_last_run(&job_id, finished_at, success, &output)- .await- });- }- upstream::record_last_run(&opts(config), job_id, finished_at, success, output)+ let docs = documents(config)?;+ let (job_id, output) = (job_id.to_string(), output.to_string());+ return run(async move {+ docs.record_last_run(&job_id, finished_at, success, &output)+ .await+ })}pub fn reschedule_after_run(@@ -299,11 +275,9 @@ pub fn reschedule_after_run(success: bool,output: &str,) -> Result<()> {- if let Some(docs) = documents(config)? {- let (job, output) = (job.clone(), output.to_string());- return run(async move { docs.reschedule_after_run(&job, success, &output).await });- }- upstream::reschedule_after_run(&opts(config), job, success, output)+ let docs = documents(config)?;+ let (job, output) = (job.clone(), output.to_string());+ return run(async move { docs.reschedule_after_run(&job, success, &output).await })}pub fn record_run(@@ -315,33 +289,23 @@ pub fn record_run(output: Option<&str>,duration_ms: i64,) -> Result<()> {- if let Some(docs) = documents(config)? {- let (job_id, status, output) = (- job_id.to_string(),- status.to_string(),- output.map(str::to_string),- );- return run(async move {- docs.record_run(- &job_id,- started_at,- finished_at,- &status,- output.as_deref(),- duration_ms,- )- .await- });- }- upstream::record_run(- &opts(config),- job_id,- started_at,- finished_at,- status,- output,- duration_ms,- )+ let docs = documents(config)?;+ let (job_id, status, output) = (+ job_id.to_string(),+ status.to_string(),+ output.map(str::to_string),+ );+ return run(async move {+ docs.record_run(+ &job_id,+ started_at,+ finished_at,+ &status,+ output.as_deref(),+ duration_ms,+ )+ .await+ })}/// [`record_run`] plus the outcome of delivering the run's result.@@ -356,52 +320,37 @@ pub fn record_run_with_delivery(duration_ms: i64,delivery_status: Option<DeliveryStatus>,) -> Result<()> {- if let Some(docs) = documents(config)? {- let (job_id, status, output) = (- job_id.to_string(),- status.to_string(),- output.map(str::to_string),- );- return run(async move {- docs.record_run_with_delivery(- &job_id,- started_at,- finished_at,- &status,- output.as_deref(),- duration_ms,- delivery_status,- )- .await- });- }- upstream::record_run_with_delivery(- &opts(config),- job_id,- started_at,- finished_at,- status,- output,- duration_ms,- delivery_status,- )+ let docs = documents(config)?;+ let (job_id, status, output) = (+ job_id.to_string(),+ status.to_string(),+ output.map(str::to_string),+ );+ return run(async move {+ docs.record_run_with_delivery(+ &job_id,+ started_at,+ finished_at,+ &status,+ output.as_deref(),+ duration_ms,+ delivery_status,+ )+ .await+ })}/// Removes "queued" placeholder rows so only the real result row remains.pub fn delete_queued_runs(config: &Config, job_id: &str) -> Result<usize> {- if let Some(docs) = documents(config)? {- let job_id = job_id.to_string();- return run(async move { docs.delete_queued_runs(&job_id).await });- }- upstream::delete_queued_runs(&opts(config), job_id)+ let docs = documents(config)?;+ let job_id = job_id.to_string();+ return run(async move { docs.delete_queued_runs(&job_id).await })}pub fn list_runs(config: &Config, job_id: &str, limit: usize) -> Result<Vec<CronRun>> {- if let Some(docs) = documents(config)? {- let job_id = job_id.to_string();- return run(async move { docs.list_runs(&job_id, limit).await });- }- upstream::list_runs(&opts(config), job_id, limit)+ let docs = documents(config)?;+ let job_id = job_id.to_string();+ return run(async move { docs.list_runs(&job_id, limit).await })}#[cfg(test)]