use std::collections::HashSet;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant, SystemTime};
use aidaemon_core::{Schedule, Service, ServiceContext, ServiceError};
use async_trait::async_trait;
use chrono::Utc;
use tracing::{error, info, warn};
use crate::goal_tokens::GoalTokenRegistry;
use crate::traits::{GoalSchedule, Mandate, MandateStatus};
mod mandates;
mod notifications;
mod schedules;
mod tasks;
pub trait SchedulerStore:
crate::traits::GoalStore
+ crate::traits::TaskStore
+ crate::traits::GoalScheduleStore
+ crate::traits::GoalBudgetStore
+ crate::traits::ScheduledRunStore
+ crate::traits::TaskDispatchStore
+ crate::traits::GoalNotificationStore
+ crate::traits::NotificationStore
+ crate::traits::MandateStore
+ crate::traits::WorkCoordinationStore
+ aidaemon_tools::services::SettingsStore
{
}
impl<T> SchedulerStore for T where
T: crate::traits::GoalStore
+ crate::traits::TaskStore
+ crate::traits::GoalScheduleStore
+ crate::traits::GoalBudgetStore
+ crate::traits::ScheduledRunStore
+ crate::traits::TaskDispatchStore
+ crate::traits::GoalNotificationStore
+ crate::traits::NotificationStore
+ crate::traits::MandateStore
+ crate::traits::WorkCoordinationStore
+ aidaemon_tools::services::SettingsStore
{
}
#[async_trait]
pub trait TaskLeadHost: Send + Sync {
fn available(&self) -> bool;
fn spawn_task_lead(
&self,
goal: crate::traits::Goal,
task_text: String,
task_id: String,
running_surface_id: Option<String>,
);
fn next_model_answer_at(&self) -> Option<SystemTime>;
async fn retry_deferred_provider_requests(&self) -> usize;
async fn tainted_note_turn(&self, session_id: &str) -> anyhow::Result<String>;
async fn record_parent_visible_result_note_in_turn(
&self,
session_id: &str,
prefix: &str,
text: &str,
turn_id: Option<&str>,
) -> anyhow::Result<()>;
async fn record_mandate_owner_input_context(
&self,
session_id: &str,
mandate_id: &str,
mandate_version: i64,
action_token: &str,
) -> anyhow::Result<()>;
}
#[async_trait]
pub trait NoticeDelivery: Send + Sync {
async fn send_text(&self, session_id: &str, text: &str) -> anyhow::Result<()>;
async fn send_text_tracked(
&self,
session_id: &str,
text: &str,
) -> anyhow::Result<Option<String>>;
}
pub trait WorkPresenter: Send + Sync {
fn goal_label(&self, description: &str) -> String;
fn user_facing(&self, text: &str) -> String;
fn notification(&self, notification_type: &str, text: &str) -> String;
fn goal_task_results(
&self,
tasks: &[crate::traits::Task],
root_task_id: Option<&str>,
fallback: &str,
) -> String;
}
pub const TASK_ESCALATION_SETTLE_SECS: i64 = 8;
pub const QUEUED_NOTIFICATION_NOTE_PREFIX: &str = "Parent-visible result (goal notification)";
pub fn notice_accepts_mandate_answer(notification_type: &str) -> bool {
matches!(notification_type, "mandate_ask" | "mandate_ask_timeout")
}
pub const MANDATE_REVIEW_LEASE_SECS: i64 = 30 * 60;
pub const MANDATE_REVIEW_BATCH_SIZE: i64 = 20;
pub const MANDATE_DISPATCH_BUSY_RETRIES: u32 = 5;
pub const MANDATE_DISPATCH_BUSY_RETRY_SECS: i64 = 30;
pub fn mandate_retry_at(mandate: &Mandate, requested_secs: Option<i64>) -> String {
let delay = mandate.clamp_review_secs(requested_secs);
(chrono::Utc::now() + chrono::Duration::seconds(delay)).to_rfc3339()
}
pub fn mandate_budget_retry_at(mandate: &Mandate, now: chrono::DateTime<Utc>) -> String {
let next_day = now
.date_naive()
.succ_opt()
.expect("the next UTC date is representable")
.and_hms_opt(0, 0, 0)
.expect("UTC midnight is representable");
let mut retry_at = chrono::DateTime::<Utc>::from_naive_utc_and_offset(next_day, Utc);
if let Some(expiry) = mandate
.expires_at
.as_deref()
.and_then(|value| chrono::DateTime::parse_from_rfc3339(value).ok())
.map(|value| value.with_timezone(&Utc))
{
retry_at = retry_at.min(expiry);
}
retry_at.to_rfc3339()
}
pub fn mandate_transient_retry_at(mandate: &Mandate, now: chrono::DateTime<Utc>) -> String {
let mut retry_at = now + chrono::Duration::seconds(MANDATE_DISPATCH_BUSY_RETRY_SECS);
if let Some(expiry) = mandate
.expires_at
.as_deref()
.and_then(|value| chrono::DateTime::parse_from_rfc3339(value).ok())
.map(|value| value.with_timezone(&Utc))
{
retry_at = retry_at.min(expiry);
}
retry_at.to_rfc3339()
}
pub fn is_sqlite_busy_error(error: &anyhow::Error) -> bool {
const SQLITE_BUSY: i32 = 5;
const SQLITE_LOCKED: i32 = 6;
error.chain().any(|cause| {
let Some(sqlx::Error::Database(database)) = cause.downcast_ref::<sqlx::Error>() else {
return false;
};
database
.code()
.and_then(|code| code.parse::<i32>().ok())
.is_some_and(|code| matches!(code & 0xff, SQLITE_BUSY | SQLITE_LOCKED))
})
}
pub fn mandate_review_task_description(mandate: &Mandate, goal_run_id: &str) -> String {
format!(
"Run one bounded autonomous review for mandate {} version {} in goal run {}. \
Use only the isolated built-in mandate protocol and immutable policy supplied \
by the runtime.",
mandate.id, mandate.version, goal_run_id
)
}
pub fn mandate_review_task_context(mandate: &Mandate) -> String {
serde_json::json!({
"mandate_id": mandate.id,
"mandate_version": mandate.version,
"provenance": "runtime_mandate_fence_only",
})
.to_string()
}
pub fn timestamp_is_at_or_after(value: &str, lower_bound: &str) -> bool {
match (
chrono::DateTime::parse_from_rfc3339(value),
chrono::DateTime::parse_from_rfc3339(lower_bound),
) {
(Ok(value), Ok(lower_bound)) => value >= lower_bound,
_ => value >= lower_bound,
}
}
pub fn goal_completion_header(tasks: &[crate::traits::Task]) -> String {
if tasks.is_empty() {
return aidaemon_channels::presentation::GOAL_COMPLETED_LEAD.to_string();
}
let total = tasks.len();
let done = tasks.iter().filter(|t| t.status == "completed").count();
if done == total {
return aidaemon_channels::presentation::GOAL_COMPLETED_LEAD.to_string();
}
let missing: Vec<String> = tasks
.iter()
.filter(|t| t.status != "completed")
.map(|t| {
format!(
"• {} ({})",
t.description.chars().take(80).collect::<String>(),
t.status
)
})
.collect();
format!(
"Goal partially completed ({done}/{total} tasks). Not completed:\n{}\n",
missing.join("\n")
)
}
pub fn daily_budget_exhausted(
budget_daily: Option<i64>,
tokens_used_today: i64,
tokens_used_day: &str,
today: &str,
) -> bool {
match budget_daily {
Some(budget) => tokens_used_day == today && tokens_used_today >= budget,
None => false,
}
}
pub fn daily_budget_has_run_capacity(
budget_daily: Option<i64>,
budget_per_check: Option<i64>,
tokens_used_today: i64,
tokens_used_day: &str,
today: &str,
) -> bool {
let (Some(daily), Some(per_run)) = (budget_daily, budget_per_check) else {
return true;
};
if tokens_used_day != today {
return true;
}
daily.saturating_sub(tokens_used_today) >= per_run.max(0)
}
pub fn parse_datetime_flexible(s: &str) -> Option<chrono::DateTime<chrono::Utc>> {
chrono::DateTime::parse_from_rfc3339(s)
.map(|d| d.with_timezone(&chrono::Utc))
.ok()
.or_else(|| {
chrono::NaiveDateTime::parse_from_str(s, "%Y-%m-%d %H:%M:%S")
.ok()
.map(|nd| nd.and_utc())
})
}
pub fn task_escalation_has_settled(created_at: &str, now: chrono::DateTime<chrono::Utc>) -> bool {
parse_datetime_flexible(created_at)
.is_none_or(|created_at| (now - created_at).num_seconds() >= TASK_ESCALATION_SETTLE_SECS)
}
pub fn task_inactivity_secs(
last_activity: Option<&str>,
started_at: &str,
now: chrono::DateTime<chrono::Utc>,
) -> i64 {
let reference = last_activity
.and_then(parse_datetime_flexible)
.or_else(|| parse_datetime_flexible(started_at));
match reference {
Some(ts) => (now - ts).num_seconds().max(0),
None => 0,
}
}
pub fn task_status_is_terminal_failure(status: &str) -> bool {
matches!(
status,
"failed" | "blocked" | "interrupted" | "cancelled" | "abandoned"
)
}
pub fn task_is_blocked_by_terminal_dependency(
task: &crate::traits::Task,
run_tasks: &[crate::traits::Task],
) -> bool {
task.status == "blocked"
&& task.dependency_ids().is_ok_and(|dependencies| {
dependencies.iter().any(|dependency| {
run_tasks.iter().any(|other| {
other.id == *dependency && task_status_is_terminal_failure(&other.status)
})
})
})
}
pub fn task_blocks_schedule_fire(
task: &crate::traits::Task,
run_tasks: &[crate::traits::Task],
) -> bool {
matches!(task.status.as_str(), "pending" | "claimed" | "running")
|| (task.status == "blocked" && !task_is_blocked_by_terminal_dependency(task, run_tasks))
}
pub fn task_blocks_later_schedule_fire(
run: &crate::traits::GoalRun,
task: &crate::traits::Task,
run_tasks: &[crate::traits::Task],
) -> bool {
if !matches!(run.status.as_str(), "pending" | "running" | "blocked") {
return false;
}
run.status != "blocked" && task_blocks_schedule_fire(task, run_tasks)
}
pub fn task_is_terminal_schedule_failure(task: &crate::traits::Task) -> bool {
matches!(
task.status.as_str(),
"failed" | "interrupted" | "cancelled" | "blocked"
)
}
pub fn scheduled_run_reconciliation_status(
run: &crate::traits::GoalRun,
tasks: &[crate::traits::Task],
) -> Option<&'static str> {
if !matches!(
run.trigger_type.as_str(),
"scheduled" | "manual" | "recovery"
) || !matches!(run.status.as_str(), "pending" | "running")
|| tasks.is_empty()
{
return None;
}
let terminal_failure = tasks.iter().any(|task| {
if run.trigger_type == "scheduled" {
task_is_terminal_schedule_failure(task)
} else {
matches!(task.status.as_str(), "failed" | "interrupted" | "cancelled")
}
});
if terminal_failure {
Some("failed")
} else if tasks
.iter()
.all(crate::traits::Task::satisfies_run_completion)
{
Some("completed")
} else {
None
}
}
pub fn stranded_manual_run_matches_pending_tasks(
run: &crate::traits::GoalRun,
run_tasks: &[crate::traits::Task],
pending_tasks: &[&crate::traits::Task],
) -> bool {
run.trigger_type == "manual"
&& matches!(run.status.as_str(), "pending" | "running")
&& pending_tasks
.iter()
.any(|pending| run_tasks.iter().any(|task| task.id == pending.id))
}
pub struct GoalCycle {
pub(crate) state: Arc<dyn SchedulerStore>,
pub(crate) agent: Option<Arc<dyn TaskLeadHost>>,
pub(crate) hub: Option<Arc<dyn NoticeDelivery>>,
pub(crate) presenter: Arc<dyn WorkPresenter>,
pub(crate) goal_token_registry: Option<GoalTokenRegistry>,
deferred_retry_running: Arc<AtomicBool>,
last_stale_goal_cleanup: Option<Instant>,
pub task_inactivity_timeout_secs: i64,
}
impl GoalCycle {
const ESCALATED_RECOVERY_COOLDOWN_SECS: i64 = 6 * 3600;
const ESCALATED_RECOVERY_MAX_ATTEMPTS: u16 = 3;
pub fn new(
state: Arc<dyn SchedulerStore>,
presenter: Arc<dyn WorkPresenter>,
goal_token_registry: Option<GoalTokenRegistry>,
) -> Self {
Self {
state,
agent: None,
hub: None,
presenter,
goal_token_registry,
deferred_retry_running: Arc::new(AtomicBool::new(false)),
last_stale_goal_cleanup: None,
task_inactivity_timeout_secs: 300,
}
}
pub fn set_task_inactivity_timeout(&mut self, secs: u64) {
self.task_inactivity_timeout_secs = secs as i64;
}
pub fn set_delivery(&mut self, delivery: Option<Arc<dyn NoticeDelivery>>) {
self.hub = delivery;
}
pub fn set_agent(&mut self, agent: Option<Arc<dyn TaskLeadHost>>) {
self.agent = agent;
}
fn live_agent(&self) -> Option<Arc<dyn TaskLeadHost>> {
self.agent.clone().filter(|agent| agent.available())
}
pub async fn startup_recovery(&self) {
info!("Running startup recovery");
match self.state.recover_expired_task_attempts().await {
Ok(tasks) if !tasks.is_empty() => {
info!(
count = tasks.len(),
"Startup recovery processed expired execution leases"
);
}
Ok(_) => {}
Err(error) => {
error!(%error, "Failed to recover expired execution leases");
}
}
match self.state.get_stuck_tasks(0).await {
Ok(tasks) => {
let mut interrupted = 0;
let mut auto_retried = 0;
for task in &tasks {
if let Err(e) = self.state.mark_task_interrupted(&task.id).await {
error!(task_id = %task.id, error = %e, "Failed to mark task interrupted");
continue;
}
interrupted += 1;
let goal_active = match self.state.get_goal(&task.goal_id).await {
Ok(Some(g)) => g.status == "active",
_ => false,
};
if !goal_active {
continue;
}
let schedules = self
.state
.get_schedules_for_goal(&task.goal_id)
.await
.unwrap_or_default();
if !schedules.is_empty() {
let active_run = self
.state
.get_scheduled_run_state(&task.goal_id)
.await
.ok()
.flatten();
if active_run.as_ref().is_none_or(|run| {
!timestamp_is_at_or_after(&task.created_at, &run.created_at)
}) {
continue;
}
}
if task.idempotent && task.retry_count < task.max_retries {
let mut retry_task = task.clone();
retry_task.status = "pending".to_string();
retry_task.retry_count += 1;
retry_task.result = None;
retry_task.error = None;
retry_task.blocker = None;
retry_task.agent_id = None;
retry_task.started_at = None;
retry_task.completed_at = None;
if let Err(e) = self.state.update_task(&retry_task).await {
error!(task_id = %task.id, error = %e, "Failed to auto-retry task");
} else {
auto_retried += 1;
info!(task_id = %task.id, retry = retry_task.retry_count, "Auto-retried idempotent task");
}
}
}
if interrupted > 0 {
info!(
count = interrupted,
auto_retried, "Startup recovery: marked interrupted tasks"
);
}
}
Err(e) => {
error!(error = %e, "Failed to get stuck tasks during recovery");
}
}
match self.state.cleanup_stale_goals(2).await {
Ok(count) if count > 0 => {
info!(count, "Startup recovery: cleaned up stale goals");
}
Err(e) => {
error!(error = %e, "Failed to cleanup stale goals during recovery");
}
_ => {}
}
if let Some(ref registry) = self.goal_token_registry {
match self.state.get_active_goals().await {
Ok(goals) => {
registry.rebuild_from_goals(&goals).await;
info!(
count = goals.len(),
"Rebuilt goal token registry from active goals"
);
}
Err(e) => {
error!(error = %e, "Failed to rebuild goal token registry");
}
}
}
info!("Startup recovery complete");
}
pub async fn tick(&mut self) -> anyhow::Result<()> {
let now = Instant::now();
self.block_pending_tasks_with_terminal_failed_dependencies()
.await;
self.check_due_mandates().await;
self.reconcile_open_scheduled_runs().await;
self.launch_escalated_recoveries().await;
self.check_due_goal_schedules().await;
self.detect_stuck_tasks().await;
match self
.state
.cancel_stale_pending_confirmation_goals(3600)
.await
{
Ok(count) if count > 0 => {
info!(count, "Cancelled stale pending_confirmation goals");
}
Err(e) => {
error!(error = %e, "Failed to cancel stale pending_confirmation goals");
}
_ => {}
}
let should_cleanup_goals = match self.last_stale_goal_cleanup {
None => true,
Some(last) => now.duration_since(last) >= Duration::from_secs(1800),
};
if should_cleanup_goals {
self.last_stale_goal_cleanup = Some(now);
match self.state.cleanup_stale_goals(2).await {
Ok(count) if count > 0 => {
info!(count, "Periodic cleanup: marked stale goals");
}
Err(e) => {
error!(error = %e, "Failed to cleanup stale goals");
}
_ => {}
}
}
self.auto_retry_failed_tasks().await;
self.dispatch_pending_tasks().await;
self.deliver_notifications().await;
if let Some(agent) = self.live_agent()
&& !self.deferred_retry_running.swap(true, Ordering::AcqRel)
{
let running = self.deferred_retry_running.clone();
tokio::spawn(async move {
let dispatched = agent.retry_deferred_provider_requests().await;
running.store(false, Ordering::Release);
if dispatched > 0 {
info!(dispatched, "Re-ran requests deferred by a provider outage");
}
});
}
Ok(())
}
}
pub struct GoalCycleService {
cycle: tokio::sync::Mutex<GoalCycle>,
}
impl GoalCycleService {
pub fn new(cycle: GoalCycle) -> Self {
Self {
cycle: tokio::sync::Mutex::new(cycle),
}
}
}
#[async_trait]
impl Service for GoalCycleService {
fn name(&self) -> &str {
"goal_cycle"
}
fn schedule(&self) -> Schedule {
Schedule::EveryTick
}
async fn start(&self, _ctx: &ServiceContext) -> Result<(), ServiceError> {
self.cycle.lock().await.startup_recovery().await;
Ok(())
}
async fn run(&self, _ctx: &ServiceContext) -> Result<(), ServiceError> {
self.cycle
.lock()
.await
.tick()
.await
.map_err(|e| ServiceError::new(e.to_string()))
}
}
#[cfg(test)]
mod sqlite_busy_tests {
use super::is_sqlite_busy_error;
use sqlx::sqlite::SqliteConnectOptions;
use sqlx::{ConnectOptions, Connection};
use std::str::FromStr;
#[tokio::test]
async fn contention_is_read_from_the_typed_driver_error() {
let file = tempfile::NamedTempFile::new().unwrap();
let url = format!("sqlite://{}", file.path().display());
let options = SqliteConnectOptions::from_str(&url)
.unwrap()
.busy_timeout(std::time::Duration::ZERO);
let mut holder = options.connect().await.unwrap();
sqlx::query("CREATE TABLE t (x INTEGER)")
.execute(&mut holder)
.await
.unwrap();
sqlx::query("BEGIN EXCLUSIVE")
.execute(&mut holder)
.await
.unwrap();
let mut writer = options.connect().await.unwrap();
let busy = sqlx::query("INSERT INTO t VALUES (1)")
.execute(&mut writer)
.await
.unwrap_err();
let busy = anyhow::Error::from(busy).context("claiming the task");
assert!(is_sqlite_busy_error(&busy), "{busy:#}");
assert!(!is_sqlite_busy_error(&anyhow::anyhow!(
"error returned from database: (code: 5) database is locked"
)));
assert!(!is_sqlite_busy_error(&anyhow::anyhow!("SQLITE_BUSY")));
holder.close().await.unwrap();
let missing = sqlx::query("SELECT * FROM missing_table")
.execute(&mut writer)
.await
.unwrap_err();
assert!(!is_sqlite_busy_error(&anyhow::Error::from(missing)));
writer.close().await.unwrap();
}
}