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