Skip to main content

aidaemon_work/scheduler/
mod.rs

1//! The scheduler's goal cycle: due mandate reviews, scheduled goals and
2//! reminders, stuck and orphaned tasks, recovery runs and goal
3//! notifications. One pass is [`GoalCycle::tick`]; [`GoalCycleService`] runs
4//! it on an [`aidaemon_core::ServiceHost`].
5//!
6//! The host gives what is its own: the agent runtime that runs a task lead
7//! ([`TaskLeadHost`]), the channels that carry a notice to the owner
8//! ([`NoticeDelivery`]) and how text is shown to the owner ([`WorkPresenter`]).
9
10use std::collections::HashSet;
11use std::sync::Arc;
12use std::sync::atomic::{AtomicBool, Ordering};
13use std::time::{Duration, Instant, SystemTime};
14
15use aidaemon_core::{Schedule, Service, ServiceContext, ServiceError};
16use async_trait::async_trait;
17use chrono::{DateTime, Utc};
18use tracing::{error, info, warn};
19
20use crate::goal_tokens::GoalTokenRegistry;
21use crate::traits::{GoalSchedule, Mandate, MandateStatus};
22
23mod mandates;
24pub mod needs_model;
25mod notifications;
26mod schedules;
27mod tasks;
28
29/// The stores the goal cycle reads and writes.
30pub trait SchedulerStore:
31    crate::traits::GoalStore
32    + crate::traits::TaskStore
33    + crate::traits::GoalScheduleStore
34    + crate::traits::GoalBudgetStore
35    + crate::traits::ScheduledRunStore
36    + crate::traits::TaskDispatchStore
37    + crate::traits::GoalNotificationStore
38    + crate::traits::NotificationStore
39    + crate::traits::MandateStore
40    + crate::traits::WorkCoordinationStore
41    + aidaemon_tools::services::SettingsStore
42{
43}
44
45impl<T> SchedulerStore for T where
46    T: crate::traits::GoalStore
47        + crate::traits::TaskStore
48        + crate::traits::GoalScheduleStore
49        + crate::traits::GoalBudgetStore
50        + crate::traits::ScheduledRunStore
51        + crate::traits::TaskDispatchStore
52        + crate::traits::GoalNotificationStore
53        + crate::traits::NotificationStore
54        + crate::traits::MandateStore
55        + crate::traits::WorkCoordinationStore
56        + aidaemon_tools::services::SettingsStore
57{
58}
59
60/// The agent runtime, as the goal cycle hands it work.
61#[async_trait]
62pub trait TaskLeadHost: Send + Sync {
63    /// Whether the runtime is still there to take work.
64    fn available(&self) -> bool;
65
66    /// Whether a model is connected. With none, a scheduled task or mandate
67    /// that comes due is skipped for that firing and its owner told once.
68    /// Default: true.
69    fn has_model(&self) -> bool {
70        true
71    }
72
73    /// Start a background task lead for `goal` on its root task `task_id`,
74    /// already claimed for it, as the owner on an internal channel.
75    /// `running_surface_id` is a message the lead may edit with progress.
76    fn spawn_task_lead(
77        &self,
78        goal: crate::traits::Goal,
79        task_text: String,
80        task_id: String,
81        running_surface_id: Option<String>,
82    );
83
84    /// When some configured model can answer again, if none can now.
85    fn next_model_answer_at(&self) -> Option<SystemTime>;
86
87    /// Re-run requests deferred by a provider outage; how many ran.
88    async fn retry_deferred_provider_requests(&self) -> usize;
89
90    /// Record a tainted turn in `session_id` for an untrusted notice; its id.
91    async fn tainted_note_turn(&self, session_id: &str) -> anyhow::Result<String>;
92
93    /// Keep a delivered notice in the owner's history, in `turn_id` if given.
94    async fn record_parent_visible_result_note_in_turn(
95        &self,
96        session_id: &str,
97        prefix: &str,
98        text: &str,
99        turn_id: Option<&str>,
100    ) -> anyhow::Result<()>;
101
102    /// Bind the owner's next reply in `session_id` to a mandate question.
103    async fn record_mandate_owner_input_context(
104        &self,
105        session_id: &str,
106        mandate_id: &str,
107        mandate_version: i64,
108        action_token: &str,
109    ) -> anyhow::Result<()>;
110}
111
112/// The channels a notice reaches the owner through.
113#[async_trait]
114pub trait NoticeDelivery: Send + Sync {
115    /// Send `text` to `session_id`.
116    async fn send_text(&self, session_id: &str, text: &str) -> anyhow::Result<()>;
117
118    /// Send `text` and return an id the sender can later edit, if the
119    /// channel has one.
120    async fn send_text_tracked(
121        &self,
122        session_id: &str,
123        text: &str,
124    ) -> anyhow::Result<Option<String>>;
125
126    /// Whether the owner sent a message in `session_id` at or after
127    /// `since`: they are awake there, so quiet hours do not hold its
128    /// notices. Default: not known, quiet hours hold.
129    async fn owner_active_since(&self, _session_id: &str, _since: DateTime<Utc>) -> bool {
130        false
131    }
132}
133
134/// How the host shows work to the owner.
135pub trait WorkPresenter: Send + Sync {
136    /// A short label for a goal's description.
137    fn goal_label(&self, description: &str) -> String;
138
139    /// `text` made safe to show the owner.
140    fn user_facing(&self, text: &str) -> String;
141
142    /// A notification of kind `notification_type` as the channel shows it.
143    fn notification(&self, notification_type: &str, text: &str) -> String;
144
145    /// The summary of a goal's task results sent when it ends.
146    fn goal_task_results(
147        &self,
148        tasks: &[crate::traits::Task],
149        root_task_id: Option<&str>,
150        fallback: &str,
151    ) -> String;
152}
153
154pub const TASK_ESCALATION_SETTLE_SECS: i64 = 8;
155/// History prefix for notices delivered from the notification queue; matches
156/// the direct goal-notification path so both read the same to the agent.
157pub const QUEUED_NOTIFICATION_NOTE_PREFIX: &str = "Parent-visible result (goal notification)";
158
159/// Notices after which the owner's next reply may answer a mandate question:
160/// the ASK itself, and the timeout notice that says it can still be answered.
161pub fn notice_accepts_mandate_answer(notification_type: &str) -> bool {
162    matches!(notification_type, "mandate_ask" | "mandate_ask_timeout")
163}
164pub const MANDATE_REVIEW_LEASE_SECS: i64 = 30 * 60;
165pub const MANDATE_REVIEW_BATCH_SIZE: i64 = 20;
166pub const MANDATE_DISPATCH_BUSY_RETRIES: u32 = 5;
167pub const MANDATE_DISPATCH_BUSY_RETRY_SECS: i64 = 30;
168
169pub fn mandate_retry_at(mandate: &Mandate, requested_secs: Option<i64>) -> String {
170    let delay = mandate.clamp_review_secs(requested_secs);
171    (chrono::Utc::now() + chrono::Duration::seconds(delay)).to_rfc3339()
172}
173
174pub fn mandate_budget_retry_at(mandate: &Mandate, now: chrono::DateTime<Utc>) -> String {
175    let next_day = now
176        .date_naive()
177        .succ_opt()
178        .expect("the next UTC date is representable")
179        .and_hms_opt(0, 0, 0)
180        .expect("UTC midnight is representable");
181    let mut retry_at = chrono::DateTime::<Utc>::from_naive_utc_and_offset(next_day, Utc);
182    if let Some(expiry) = mandate
183        .expires_at
184        .as_deref()
185        .and_then(|value| chrono::DateTime::parse_from_rfc3339(value).ok())
186        .map(|value| value.with_timezone(&Utc))
187    {
188        retry_at = retry_at.min(expiry);
189    }
190    retry_at.to_rfc3339()
191}
192
193pub fn mandate_transient_retry_at(mandate: &Mandate, now: chrono::DateTime<Utc>) -> String {
194    let mut retry_at = now + chrono::Duration::seconds(MANDATE_DISPATCH_BUSY_RETRY_SECS);
195    if let Some(expiry) = mandate
196        .expires_at
197        .as_deref()
198        .and_then(|value| chrono::DateTime::parse_from_rfc3339(value).ok())
199        .map(|value| value.with_timezone(&Utc))
200    {
201        retry_at = retry_at.min(expiry);
202    }
203    retry_at.to_rfc3339()
204}
205
206/// Run `op` until it succeeds, retrying up to `max_retries` times after
207/// SQLite contention ([`is_sqlite_busy_error`]) with a doubling wait from
208/// 25 ms. Any other error, or contention past the last retry, is returned.
209/// `what` names the operation in the retry log.
210pub async fn retry_on_busy<T, F, Fut>(
211    what: &str,
212    max_retries: usize,
213    mut op: F,
214) -> anyhow::Result<T>
215where
216    F: FnMut() -> Fut,
217    Fut: std::future::Future<Output = anyhow::Result<T>>,
218{
219    let mut retry = 0_usize;
220    loop {
221        match op().await {
222            Err(error) if retry < max_retries && is_sqlite_busy_error(&error) => {
223                let delay_ms = 25_u64 << retry;
224                retry += 1;
225                tracing::warn!(what, retry, delay_ms, %error, "SQLite busy; retrying");
226                tokio::time::sleep(std::time::Duration::from_millis(delay_ms)).await;
227            }
228            result => return result,
229        }
230    }
231}
232
233/// Whether an error is SQLite contention (`SQLITE_BUSY` or `SQLITE_LOCKED`,
234/// including their extended codes), read from the driver's typed database
235/// error anywhere in the chain. The message is never read: an error that was
236/// flattened to text, or merely mentions "database is locked", is not
237/// retried as contention.
238pub fn is_sqlite_busy_error(error: &anyhow::Error) -> bool {
239    const SQLITE_BUSY: i32 = 5;
240    const SQLITE_LOCKED: i32 = 6;
241    error.chain().any(|cause| {
242        let Some(sqlx::Error::Database(database)) = cause.downcast_ref::<sqlx::Error>() else {
243            return false;
244        };
245        database
246            .code()
247            .and_then(|code| code.parse::<i32>().ok())
248            .is_some_and(|code| matches!(code & 0xff, SQLITE_BUSY | SQLITE_LOCKED))
249    })
250}
251
252pub fn mandate_review_task_description(mandate: &Mandate, goal_run_id: &str) -> String {
253    // Owner text and authority targets intentionally do not enter ordinary
254    // task prose. The isolated mandate system prompt loads the exact current
255    // policy from durable state and labels its JSON fields as policy or data.
256    format!(
257        "Run one bounded autonomous review for mandate {} version {} in goal run {}. \
258         Use only the isolated built-in mandate protocol and immutable policy supplied \
259         by the runtime.",
260        mandate.id, mandate.version, goal_run_id
261    )
262}
263
264pub fn mandate_review_task_context(mandate: &Mandate) -> String {
265    serde_json::json!({
266        "mandate_id": mandate.id,
267        "mandate_version": mandate.version,
268        "provenance": "runtime_mandate_fence_only",
269    })
270    .to_string()
271}
272
273pub fn timestamp_is_at_or_after(value: &str, lower_bound: &str) -> bool {
274    match (
275        chrono::DateTime::parse_from_rfc3339(value),
276        chrono::DateTime::parse_from_rfc3339(lower_bound),
277    ) {
278        (Ok(value), Ok(lower_bound)) => value >= lower_bound,
279        _ => value >= lower_bound,
280    }
281}
282
283/// Whether a goal's daily token budget is exhausted *for today*. Only usage
284/// recorded on the current UTC day counts: stale `tokens_used_today` from a
285/// previous day (before the daily reset has run) must NOT block a goal, or an
286/// expensive run can deadlock the goal across the day boundary (the budget gate
287/// keeps deferring it, so it never fires, so it never resets).
288/// Header for the goal-completion notification, derived from the ACTUAL task
289/// rows rather than metadata the task lead may never have written (a
290/// watchdog-killed lead leaves `partial_success` unset). "Goal completed:"
291/// must never accompany incomplete tasks — name what's missing instead.
292pub fn goal_completion_header(tasks: &[crate::traits::Task]) -> String {
293    if tasks.is_empty() {
294        return aidaemon_channels::presentation::GOAL_COMPLETED_LEAD.to_string();
295    }
296    let total = tasks.len();
297    let done = tasks.iter().filter(|t| t.status == "completed").count();
298    if done == total {
299        return aidaemon_channels::presentation::GOAL_COMPLETED_LEAD.to_string();
300    }
301    let missing: Vec<String> = tasks
302        .iter()
303        .filter(|t| t.status != "completed")
304        .map(|t| {
305            format!(
306                "• {} ({})",
307                t.description.chars().take(80).collect::<String>(),
308                t.status
309            )
310        })
311        .collect();
312    format!(
313        "Goal partially completed ({done}/{total} tasks). Not completed:\n{}\n",
314        missing.join("\n")
315    )
316}
317
318pub fn daily_budget_exhausted(
319    budget_daily: Option<i64>,
320    tokens_used_today: i64,
321    tokens_used_day: &str,
322    today: &str,
323) -> bool {
324    match budget_daily {
325        Some(budget) => tokens_used_day == today && tokens_used_today >= budget,
326        None => false,
327    }
328}
329
330pub fn daily_budget_has_run_capacity(
331    budget_daily: Option<i64>,
332    budget_per_check: Option<i64>,
333    tokens_used_today: i64,
334    tokens_used_day: &str,
335    today: &str,
336) -> bool {
337    let (Some(daily), Some(per_run)) = (budget_daily, budget_per_check) else {
338        return true;
339    };
340    if tokens_used_day != today {
341        return true;
342    }
343    daily.saturating_sub(tokens_used_today) >= per_run.max(0)
344}
345
346/// Seconds since a task's most recent activity (or its `started_at` when it has
347/// no activity rows). Used to tag stuck-task interrupts so the inactivity
348/// threshold can be tuned from data. Returns 0 if no timestamp parses (never
349/// panics). Both inputs are RFC3339 or SQLite-datetime strings.
350/// Parses a timestamp that may be either RFC3339 (`2026-07-04T13:10:45+00:00`,
351/// how application code writes it) or SQLite's own `datetime()`-coerced form
352/// (`2026-07-04 13:10:45`, space-separated, no offset, second precision —
353/// what columns wrapped in `datetime(?)` at INSERT time read back as, e.g.
354/// `task_activity.created_at`). Returns `None` for anything else rather than
355/// panicking or guessing.
356pub fn parse_datetime_flexible(s: &str) -> Option<chrono::DateTime<chrono::Utc>> {
357    chrono::DateTime::parse_from_rfc3339(s)
358        .map(|d| d.with_timezone(&chrono::Utc))
359        .ok()
360        .or_else(|| {
361            chrono::NaiveDateTime::parse_from_str(s, "%Y-%m-%d %H:%M:%S")
362                .ok()
363                .map(|nd| nd.and_utc())
364        })
365}
366
367pub fn task_escalation_has_settled(created_at: &str, now: chrono::DateTime<chrono::Utc>) -> bool {
368    parse_datetime_flexible(created_at)
369        .is_none_or(|created_at| (now - created_at).num_seconds() >= TASK_ESCALATION_SETTLE_SECS)
370}
371
372pub fn task_inactivity_secs(
373    last_activity: Option<&str>,
374    started_at: &str,
375    now: chrono::DateTime<chrono::Utc>,
376) -> i64 {
377    let reference = last_activity
378        .and_then(parse_datetime_flexible)
379        .or_else(|| parse_datetime_flexible(started_at));
380    match reference {
381        Some(ts) => (now - ts).num_seconds().max(0),
382        None => 0,
383    }
384}
385
386/// A task status that ends it without success: work depending on it can
387/// never run.
388pub fn task_status_is_terminal_failure(status: &str) -> bool {
389    matches!(
390        status,
391        "failed" | "blocked" | "interrupted" | "cancelled" | "abandoned"
392    )
393}
394
395/// Whether a blocked task is blocked because a task it depends on ended
396/// without success, judged from the dependency graph (`depends_on` and the
397/// dependencies' statuses among `run_tasks`), never from the blocker's
398/// wording: a blocker text that merely reads like a dependency message does
399/// not count.
400pub fn task_is_blocked_by_terminal_dependency(
401    task: &crate::traits::Task,
402    run_tasks: &[crate::traits::Task],
403) -> bool {
404    task.status == "blocked"
405        && task.dependency_ids().is_ok_and(|dependencies| {
406            dependencies.iter().any(|dependency| {
407                run_tasks.iter().any(|other| {
408                    other.id == *dependency && task_status_is_terminal_failure(&other.status)
409                })
410            })
411        })
412}
413
414pub fn task_blocks_schedule_fire(
415    task: &crate::traits::Task,
416    run_tasks: &[crate::traits::Task],
417) -> bool {
418    matches!(task.status.as_str(), "pending" | "claimed" | "running")
419        || (task.status == "blocked" && !task_is_blocked_by_terminal_dependency(task, run_tasks))
420}
421
422pub fn task_blocks_later_schedule_fire(
423    run: &crate::traits::GoalRun,
424    task: &crate::traits::Task,
425    run_tasks: &[crate::traits::Task],
426) -> bool {
427    // Backpressure belongs to one active occurrence. Historical task rows are
428    // audit records after their parent run reaches a terminal state and can no
429    // longer suppress later schedule occurrences.
430    if !matches!(run.status.as_str(), "pending" | "running" | "blocked") {
431        return false;
432    }
433    // A blocked run has no active worker and terminates that occurrence,
434    // whatever triggered it (scheduled, manual, or recovery). Keeping it
435    // resumable is useful for explicit recovery, but it must not suppress
436    // every later occurrence of a recurring schedule. Blockers inside a
437    // still-running occurrence remain open.
438    run.status != "blocked" && task_blocks_schedule_fire(task, run_tasks)
439}
440
441pub fn task_is_terminal_schedule_failure(task: &crate::traits::Task) -> bool {
442    matches!(
443        task.status.as_str(),
444        "failed" | "interrupted" | "cancelled" | "blocked"
445    )
446}
447
448/// Reconcile an open scheduled occurrence from its authoritative task graph.
449/// A blocked child is a terminal failure of this occurrence, not a second
450/// meaning for the run's `blocked` waiting state. Autonomous recovery is a
451/// later linked run rather than an indefinitely open scheduled occurrence.
452pub fn scheduled_run_reconciliation_status(
453    run: &crate::traits::GoalRun,
454    tasks: &[crate::traits::Task],
455) -> Option<&'static str> {
456    if !matches!(
457        run.trigger_type.as_str(),
458        "scheduled" | "manual" | "recovery"
459    ) || !matches!(run.status.as_str(), "pending" | "running")
460        || tasks.is_empty()
461    {
462        return None;
463    }
464    // A blocked child terminates a scheduled occurrence. In a manual or
465    // recovery occurrence the lead may still be waiting on an owner decision,
466    // so only hard task failures reconcile it; the run-level `blocked` state
467    // (the lead already ended the occurrence) is handled at fire time.
468    let terminal_failure = tasks.iter().any(|task| {
469        if run.trigger_type == "scheduled" {
470            task_is_terminal_schedule_failure(task)
471        } else {
472            matches!(task.status.as_str(), "failed" | "interrupted" | "cancelled")
473        }
474    });
475    if terminal_failure {
476        Some("failed")
477    } else if tasks
478        .iter()
479        .all(crate::traits::Task::satisfies_run_completion)
480    {
481        Some("completed")
482    } else {
483        None
484    }
485}
486
487pub fn stranded_manual_run_matches_pending_tasks(
488    run: &crate::traits::GoalRun,
489    run_tasks: &[crate::traits::Task],
490    pending_tasks: &[&crate::traits::Task],
491) -> bool {
492    run.trigger_type == "manual"
493        && matches!(run.status.as_str(), "pending" | "running")
494        && pending_tasks
495            .iter()
496            .any(|pending| run_tasks.iter().any(|task| task.id == pending.id))
497}
498
499/// The goal cycle and what it needs between passes.
500pub struct GoalCycle {
501    pub(crate) state: Arc<dyn SchedulerStore>,
502    pub(crate) agent: Option<Arc<dyn TaskLeadHost>>,
503    pub(crate) hub: Option<Arc<dyn NoticeDelivery>>,
504    pub(crate) presenter: Arc<dyn WorkPresenter>,
505    pub(crate) goal_token_registry: Option<GoalTokenRegistry>,
506    deferred_retry_running: Arc<AtomicBool>,
507    last_stale_goal_cleanup: Option<Instant>,
508    /// Seconds of no task activity before `detect_stuck_tasks` interrupts a
509    /// running/claimed task. Defaults to 300.
510    pub task_inactivity_timeout_secs: i64,
511    /// Goals told they need a model, so each is told once (across
512    /// restarts); cleared when a model is connected.
513    no_model_noticed: Arc<needs_model::NeedsModelNotices>,
514}
515
516/// The notice an automation that came due with no model gets, once.
517pub fn needs_model_notice(name: &str) -> String {
518    format!("{name} needs a model to run. Connect one in Settings.")
519}
520
521impl GoalCycle {
522    /// Wait between an escalation (or the previous automatic attempt) and the
523    /// next automatic recovery run. Long enough for a transient external
524    /// cause to clear; short enough that a daily objective is not lost for a
525    /// week.
526    const ESCALATED_RECOVERY_COOLDOWN_SECS: i64 = 6 * 3600;
527    /// Automatic recovery attempts per escalation before the objective waits
528    /// for the owner.
529    const ESCALATED_RECOVERY_MAX_ATTEMPTS: u16 = 3;
530
531    pub fn new(
532        state: Arc<dyn SchedulerStore>,
533        presenter: Arc<dyn WorkPresenter>,
534        goal_token_registry: Option<GoalTokenRegistry>,
535    ) -> Self {
536        Self {
537            state,
538            agent: None,
539            hub: None,
540            presenter,
541            goal_token_registry,
542            deferred_retry_running: Arc::new(AtomicBool::new(false)),
543            last_stale_goal_cleanup: None,
544            task_inactivity_timeout_secs: 300,
545            no_model_noticed: Arc::new(needs_model::NeedsModelNotices::new(needs_model::GOALS_KEY)),
546        }
547    }
548
549    /// Whether the runtime has no model connected now (an absent runtime is
550    /// not known to lack one). A connected model forgets the goals told.
551    pub(crate) async fn without_model(&self) -> bool {
552        let without = self.agent.as_ref().is_some_and(|agent| !agent.has_model());
553        if !without {
554            self.no_model_noticed.clear(self.state.as_ref()).await;
555        }
556        without
557    }
558
559    /// The goals told they need a model, for clearing the moment a model
560    /// is connected ([`needs_model::clear_on_connect`]), not only at the
561    /// next pass.
562    pub fn needs_model_notices(&self) -> Arc<needs_model::NeedsModelNotices> {
563        self.no_model_noticed.clone()
564    }
565
566    /// Tell `goal`'s owner once that it needs a model; later firings with no
567    /// model say nothing.
568    pub(crate) async fn notice_needs_model(&self, goal: &crate::traits::Goal) {
569        if !self
570            .no_model_noticed
571            .first(self.state.as_ref(), &goal.id)
572            .await
573        {
574            return;
575        }
576        let entry = crate::traits::NotificationEntry::new(
577            &goal.id,
578            &goal.session_id,
579            "evergreen_alert",
580            &needs_model_notice(&self.presenter.goal_label(&goal.description)),
581        );
582        if let Err(error) = self.state.enqueue_notification(&entry).await {
583            warn!(goal_id = %goal.id, %error, "Failed to enqueue the needs-a-model notice");
584        }
585    }
586
587    /// Override the stuck-task inactivity timeout.
588    pub fn set_task_inactivity_timeout(&mut self, secs: u64) {
589        self.task_inactivity_timeout_secs = secs as i64;
590    }
591
592    /// The channels notices go out through.
593    pub fn set_delivery(&mut self, delivery: Option<Arc<dyn NoticeDelivery>>) {
594        self.hub = delivery;
595    }
596
597    /// The agent runtime that runs task leads.
598    pub fn set_agent(&mut self, agent: Option<Arc<dyn TaskLeadHost>>) {
599        self.agent = agent;
600    }
601
602    /// The runtime, while it can take work.
603    fn live_agent(&self) -> Option<Arc<dyn TaskLeadHost>> {
604        self.agent.clone().filter(|agent| agent.available())
605    }
606
607    /// One-time recovery after startup: mark interrupted tasks, rebuild token registry.
608    pub async fn startup_recovery(&self) {
609        info!("Running startup recovery");
610
611        match self.state.recover_expired_task_attempts().await {
612            Ok(tasks) if !tasks.is_empty() => {
613                info!(
614                    count = tasks.len(),
615                    "Startup recovery processed expired execution leases"
616                );
617            }
618            Ok(_) => {}
619            Err(error) => {
620                error!(%error, "Failed to recover expired execution leases");
621            }
622        }
623
624        // Mark any tasks stuck in running/claimed as interrupted,
625        // then auto-retry idempotent ones ONLY if their parent goal is still active.
626        // We do NOT aggressively fail goals here — the progress-based circuit breaker
627        // in spawn_background_task_lead handles stale goals on next dispatch.
628        match self.state.get_stuck_tasks(0).await {
629            Ok(tasks) => {
630                let mut interrupted = 0;
631                let mut auto_retried = 0;
632                for task in &tasks {
633                    if let Err(e) = self.state.mark_task_interrupted(&task.id).await {
634                        error!(task_id = %task.id, error = %e, "Failed to mark task interrupted");
635                        continue;
636                    }
637                    interrupted += 1;
638
639                    // Check if the parent goal is still active/non-stalled before retrying
640                    let goal_active = match self.state.get_goal(&task.goal_id).await {
641                        Ok(Some(g)) => g.status == "active",
642                        _ => false,
643                    };
644
645                    if !goal_active {
646                        // Goal is failed/completed/stalled — don't retry, just leave interrupted.
647                        continue;
648                    }
649
650                    // A recurring goal remains active between fires, so goal
651                    // status alone is not enough to authorize recovery. Only
652                    // retry work that belongs to its explicitly persisted
653                    // active run. Otherwise a restart can resurrect a child
654                    // from a closed/cancelled cycle and repeat side effects.
655                    let schedules = self
656                        .state
657                        .get_schedules_for_goal(&task.goal_id)
658                        .await
659                        .unwrap_or_default();
660                    if !schedules.is_empty() {
661                        let active_run = self
662                            .state
663                            .get_scheduled_run_state(&task.goal_id)
664                            .await
665                            .ok()
666                            .flatten();
667                        if active_run.as_ref().is_none_or(|run| {
668                            !timestamp_is_at_or_after(&task.created_at, &run.created_at)
669                        }) {
670                            continue;
671                        }
672                    }
673
674                    // Auto-retry idempotent tasks that haven't exceeded max retries
675                    if task.idempotent && task.retry_count < task.max_retries {
676                        let mut retry_task = task.clone();
677                        retry_task.status = "pending".to_string();
678                        retry_task.retry_count += 1;
679                        retry_task.result = None;
680                        retry_task.error = None;
681                        retry_task.blocker = None;
682                        retry_task.agent_id = None;
683                        retry_task.started_at = None;
684                        retry_task.completed_at = None;
685                        if let Err(e) = self.state.update_task(&retry_task).await {
686                            error!(task_id = %task.id, error = %e, "Failed to auto-retry task");
687                        } else {
688                            auto_retried += 1;
689                            info!(task_id = %task.id, retry = retry_task.retry_count, "Auto-retried idempotent task");
690                        }
691                    }
692                    // Non-retryable tasks stay interrupted — the circuit breaker will
693                    // detect no progress on next dispatch and eventually stall the goal.
694                }
695
696                if interrupted > 0 {
697                    info!(
698                        count = interrupted,
699                        auto_retried, "Startup recovery: marked interrupted tasks"
700                    );
701                }
702            }
703            Err(e) => {
704                error!(error = %e, "Failed to get stuck tasks during recovery");
705            }
706        }
707
708        // Mark stale active goals as abandoned/failed.
709        // Finite goals stuck active for >2 hours are clearly orphaned.
710        match self.state.cleanup_stale_goals(2).await {
711            Ok(count) if count > 0 => {
712                info!(count, "Startup recovery: cleaned up stale goals");
713            }
714            Err(e) => {
715                error!(error = %e, "Failed to cleanup stale goals during recovery");
716            }
717            _ => {}
718        }
719
720        // Rebuild goal token registry from active goals
721        if let Some(ref registry) = self.goal_token_registry {
722            match self.state.get_active_goals().await {
723                Ok(goals) => {
724                    registry.rebuild_from_goals(&goals).await;
725                    info!(
726                        count = goals.len(),
727                        "Rebuilt goal token registry from active goals"
728                    );
729                }
730                Err(e) => {
731                    error!(error = %e, "Failed to rebuild goal token registry");
732                }
733            }
734        }
735
736        info!("Startup recovery complete");
737    }
738
739    /// One pass of the goal cycle. Periodic jobs and the database check are
740    /// the host's.
741    pub async fn tick(&mut self) -> anyhow::Result<()> {
742        let now = Instant::now();
743        // With no model connected no task lead can run: pending work waits
744        // (it is not failed) until one is, and due automations are skipped.
745        let without_model = self.without_model().await;
746
747        // Phase 1d: Pending tasks whose dependencies reached terminal failure
748        // can never dispatch. Mark them blocked before schedule coalescing so
749        // stale dependent work does not suppress future scheduled runs forever.
750        self.block_pending_tasks_with_terminal_failed_dependencies()
751            .await;
752
753        // Phase 2a: Review due owner mandates. Mandates have their own durable
754        // wake clock and lease; they must never flow through goal_schedules or
755        // acquire scheduled-run provenance.
756        self.check_due_mandates().await;
757
758        // Phase 2b: Reconcile scheduled lifecycle state independently of the
759        // next fire time. A completed/failed task graph must not remain
760        // observably "running" until tomorrow's recurrence happens to wake it.
761        self.reconcile_open_scheduled_runs().await;
762
763        // Phase 2b': Escalated scheduled objectives get a bounded, cooled-down
764        // automatic recovery run. Escalation pauses the cron so it cannot
765        // keep failing; without this phase nothing would ever run again.
766        if !without_model {
767            self.launch_escalated_recoveries().await;
768        }
769
770        // Phase 2c: Fire due schedules (recurring + one-shot)
771        self.check_due_goal_schedules().await;
772
773        // Phase 3: Detect stuck tasks
774        self.detect_stuck_tasks().await;
775
776        // Phase 3b: Cleanup stale pending confirmations (1 hour timeout)
777        match self
778            .state
779            .cancel_stale_pending_confirmation_goals(3600)
780            .await
781        {
782            Ok(count) if count > 0 => {
783                info!(count, "Cancelled stale pending_confirmation goals");
784            }
785            Err(e) => {
786                error!(error = %e, "Failed to cancel stale pending_confirmation goals");
787            }
788            _ => {}
789        }
790
791        // Phase 3c: Periodically cleanup stale goals (every 30 minutes)
792        let should_cleanup_goals = match self.last_stale_goal_cleanup {
793            None => true,
794            Some(last) => now.duration_since(last) >= Duration::from_secs(1800),
795        };
796        if should_cleanup_goals {
797            self.last_stale_goal_cleanup = Some(now);
798            match self.state.cleanup_stale_goals(2).await {
799                Ok(count) if count > 0 => {
800                    info!(count, "Periodic cleanup: marked stale goals");
801                }
802                Err(e) => {
803                    error!(error = %e, "Failed to cleanup stale goals");
804                }
805                _ => {}
806            }
807        }
808
809        // Phase 3d: Auto-retry failed idempotent tasks
810        if !without_model {
811            self.auto_retry_failed_tasks().await;
812        }
813
814        // Phase 4: Dispatch orphaned pending tasks
815        if !without_model {
816            self.dispatch_pending_tasks().await;
817        }
818
819        // Phase 5: Deliver notifications for completed/failed goals
820        self.deliver_notifications().await;
821
822        // Phase 6: Re-run user requests that failed only because the model
823        // provider was unavailable before any tool work committed.
824        // Each is a whole agent turn, so they run beside the cycle: schedules,
825        // mandates and stuck-task checks must not wait for them.
826        if let Some(agent) = self.live_agent().filter(|_| !without_model)
827            && !self.deferred_retry_running.swap(true, Ordering::AcqRel)
828        {
829            let running = self.deferred_retry_running.clone();
830            tokio::spawn(async move {
831                let dispatched = agent.retry_deferred_provider_requests().await;
832                running.store(false, Ordering::Release);
833                if dispatched > 0 {
834                    info!(dispatched, "Re-ran requests deferred by a provider outage");
835                }
836            });
837        }
838
839        Ok(())
840    }
841}
842
843/// The goal cycle as one service: its phases depend on their order.
844pub struct GoalCycleService {
845    cycle: tokio::sync::Mutex<GoalCycle>,
846}
847
848impl GoalCycleService {
849    pub fn new(cycle: GoalCycle) -> Self {
850        Self {
851            cycle: tokio::sync::Mutex::new(cycle),
852        }
853    }
854}
855
856#[async_trait]
857impl Service for GoalCycleService {
858    fn name(&self) -> &str {
859        "goal_cycle"
860    }
861
862    fn schedule(&self) -> Schedule {
863        Schedule::EveryTick
864    }
865
866    async fn start(&self, _ctx: &ServiceContext) -> Result<(), ServiceError> {
867        self.cycle.lock().await.startup_recovery().await;
868        Ok(())
869    }
870
871    async fn run(&self, _ctx: &ServiceContext) -> Result<(), ServiceError> {
872        self.cycle
873            .lock()
874            .await
875            .tick()
876            .await
877            .map_err(|e| ServiceError::new(e.to_string()))
878    }
879}
880
881#[cfg(test)]
882mod sqlite_busy_tests {
883    use super::is_sqlite_busy_error;
884    use sqlx::sqlite::SqliteConnectOptions;
885    use sqlx::{ConnectOptions, Connection};
886    use std::str::FromStr;
887
888    #[tokio::test]
889    async fn contention_is_read_from_the_typed_driver_error() {
890        let file = tempfile::NamedTempFile::new().unwrap();
891        let url = format!("sqlite://{}", file.path().display());
892        let options = SqliteConnectOptions::from_str(&url)
893            .unwrap()
894            .busy_timeout(std::time::Duration::ZERO);
895        let mut holder = options.connect().await.unwrap();
896        sqlx::query("CREATE TABLE t (x INTEGER)")
897            .execute(&mut holder)
898            .await
899            .unwrap();
900        sqlx::query("BEGIN EXCLUSIVE")
901            .execute(&mut holder)
902            .await
903            .unwrap();
904        let mut writer = options.connect().await.unwrap();
905        let busy = sqlx::query("INSERT INTO t VALUES (1)")
906            .execute(&mut writer)
907            .await
908            .unwrap_err();
909        let busy = anyhow::Error::from(busy).context("claiming the task");
910        assert!(is_sqlite_busy_error(&busy), "{busy:#}");
911
912        // Text that only reads like contention is not contention.
913        assert!(!is_sqlite_busy_error(&anyhow::anyhow!(
914            "error returned from database: (code: 5) database is locked"
915        )));
916        assert!(!is_sqlite_busy_error(&anyhow::anyhow!("SQLITE_BUSY")));
917        holder.close().await.unwrap();
918        let missing = sqlx::query("SELECT * FROM missing_table")
919            .execute(&mut writer)
920            .await
921            .unwrap_err();
922        assert!(!is_sqlite_busy_error(&anyhow::Error::from(missing)));
923        writer.close().await.unwrap();
924    }
925}