Skip to main content

aidaemon_work/scheduler/
schedules.rs

1//! Firing and reconciling scheduled goals.
2
3use super::*;
4
5/// How soon a one-shot that failed to fire is tried again.
6const ONE_SHOT_RETRY_SECS: i64 = 60;
7
8/// What a missed run's record says, as the owner reads it in History.
9const MISSED_RUN_SUMMARY: &str = "The daemon wasn't running when this was due.";
10
11impl GoalCycle {
12    /// Check for due schedules across active orchestration goals and enqueue tasks.
13    ///
14    /// Scheduling is per-schedule (`goal_schedules`) rather than a goal column.
15    pub async fn check_due_goal_schedules(&self) {
16        let due = match self.state.get_due_goal_schedules(50).await {
17            Ok(s) => s,
18            Err(e) => {
19                error!(error = %e, "Failed to get due goal schedules");
20                return;
21            }
22        };
23
24        if due.is_empty() {
25            return;
26        }
27
28        info!(count = due.len(), "Found due goal schedules");
29        for schedule in due {
30            let schedule_id = schedule.id.clone();
31            let goal_id = schedule.goal_id.clone();
32            let is_one_shot = schedule.is_one_shot;
33            if let Err(e) = self.fire_due_schedule(schedule).await {
34                error!(
35                    schedule_id = %schedule_id,
36                    goal_id = %goal_id,
37                    error = %e,
38                    "Failed to fire due schedule"
39                );
40                if is_one_shot {
41                    self.retry_one_shot_soon(&schedule_id).await;
42                }
43            }
44        }
45    }
46
47    /// Back off a failed, uncommitted one-shot; a committed occurrence has
48    /// consumed its schedule and already has durable work.
49    async fn retry_one_shot_soon(&self, schedule_id: &str) {
50        let schedule = match self.state.get_goal_schedule(schedule_id).await {
51            Ok(Some(schedule)) => schedule,
52            // A delivered reminder has already removed its schedule.
53            _ => return,
54        };
55        let mut schedule = schedule;
56        schedule.next_run_at =
57            (chrono::Utc::now() + chrono::Duration::seconds(ONE_SHOT_RETRY_SECS)).to_rfc3339();
58        if let Err(error) = self.state.update_goal_schedule(&schedule).await {
59            warn!(schedule_id, %error, "Could not reschedule a one-shot that failed to fire");
60        }
61    }
62
63    pub async fn reconcile_open_scheduled_runs(&self) {
64        let mut goals = match self.state.get_scheduled_goals().await {
65            Ok(goals) => goals,
66            Err(error) => {
67                error!(%error, "Failed to enumerate scheduled goals for lifecycle reconciliation");
68                return;
69            }
70        };
71        // Consuming a one-shot removes its schedule, not its run lifecycle.
72        match self.state.get_goals_with_open_scheduled_runs().await {
73            Ok(open_run_goals) => goals.extend(open_run_goals),
74            Err(error) => {
75                error!(%error, "Failed to enumerate goals with open scheduled runs");
76            }
77        }
78        let mut seen = HashSet::new();
79        for goal in goals {
80            if !seen.insert(goal.id.clone()) {
81                continue;
82            }
83            if let Err(error) = self.reconcile_open_scheduled_runs_for_goal(&goal.id).await {
84                error!(goal_id = %goal.id, %error, "Failed to reconcile scheduled goal lifecycle");
85            }
86        }
87    }
88
89    pub async fn reconcile_open_scheduled_runs_for_goal(
90        &self,
91        goal_id: &str,
92    ) -> anyhow::Result<Vec<crate::traits::GoalRun>> {
93        let candidate_open_runs = self
94            .state
95            .get_goal_runs(goal_id)
96            .await?
97            .into_iter()
98            .filter(|run| matches!(run.status.as_str(), "pending" | "running" | "blocked"))
99            .collect::<Vec<_>>();
100        let mut open_runs = Vec::new();
101        for run in candidate_open_runs {
102            // While any worker holds a live execution lease on this run, that
103            // worker owns the outcome: a supervising task lead may still
104            // salvage a transiently failed child (observed live: the lead
105            // re-completed a research task seconds after its child attempt
106            // failed). Reconciliation is for orphaned runs; it must not race
107            // a live lead, so it defers until every lease is gone.
108            if self.state.goal_run_has_live_attempt(&run.id).await? {
109                open_runs.push(run);
110                continue;
111            }
112            let run_tasks = self.state.get_tasks_for_goal_run(&run.id).await?;
113            if let Some(status) = scheduled_run_reconciliation_status(&run, &run_tasks) {
114                self.state
115                    .finish_goal_run(
116                        &run.id,
117                        status,
118                        Some("Reconciled from the scheduled run's authoritative task graph."),
119                    )
120                    .await?;
121                info!(
122                    goal_id,
123                    run_id = %run.id,
124                    prior_status = %run.status,
125                    reconciled_status = status,
126                    "Reconciled split-brain scheduled run from task lifecycle"
127                );
128                continue;
129            }
130            open_runs.push(run);
131        }
132        Ok(open_runs)
133    }
134
135    /// Launch one automatic recovery run per escalated objective once its
136    /// cool-down has elapsed, up to a fixed attempt cap. The recovery run is
137    /// the same typed recovery lineage the task lead creates inline
138    /// (`terminal_recovery` + `recovery_for_run`), so a verified success
139    /// resets the failure budget and resumes the paused schedules through
140    /// `finish_goal_run`, and a failure lands in the same budget accounting.
141    /// The paused schedules stay paused during recovery so the cron cannot
142    /// double-fire.
143    pub async fn launch_escalated_recoveries(&self) {
144        let candidates = match self
145            .state
146            .list_escalated_recovery_candidates(
147                Self::ESCALATED_RECOVERY_COOLDOWN_SECS,
148                Self::ESCALATED_RECOVERY_MAX_ATTEMPTS,
149            )
150            .await
151        {
152            Ok(candidates) => candidates,
153            Err(error) => {
154                error!(%error, "Failed to list escalated recovery candidates");
155                return;
156            }
157        };
158        for recovery in candidates {
159            let goal_id = recovery.goal_id.clone();
160            let Ok(Some(goal)) = self.state.get_goal(&goal_id).await else {
161                continue;
162            };
163            if goal.status != "active" {
164                continue;
165            }
166            // Automatic recovery is admission-controlled by the owner's daily
167            // budget exactly like a scheduled fire; it never spends past it.
168            let budget_today = chrono::Utc::now().date_naive().to_string();
169            if daily_budget_exhausted(
170                goal.budget_daily,
171                goal.tokens_used_today,
172                &goal.tokens_used_day,
173                &budget_today,
174            ) || !daily_budget_has_run_capacity(
175                goal.budget_daily,
176                goal.budget_per_check,
177                goal.tokens_used_today,
178                &goal.tokens_used_day,
179                &budget_today,
180            ) {
181                info!(
182                    goal_id = %goal_id,
183                    tokens_used = goal.tokens_used_today,
184                    budget = ?goal.budget_daily,
185                    "Deferring automatic recovery — today's goal daily budget cannot admit a run"
186                );
187                continue;
188            }
189            // An open occurrence (of any trigger type) means work is still in
190            // flight or wedged; reconcile first and try again next tick.
191            match self.reconcile_open_scheduled_runs_for_goal(&goal_id).await {
192                Ok(open_runs) if !open_runs.is_empty() => {
193                    let mut stale = true;
194                    for run in &open_runs {
195                        // A recovery run whose task never got created (a crash
196                        // between the two writes) has nothing left to finish.
197                        let no_work = match run.root_task_id.as_deref() {
198                            Some(root) if run.trigger_type == "recovery" => {
199                                matches!(self.state.get_task(root).await, Ok(None))
200                            }
201                            _ => false,
202                        };
203                        stale &= run.status == "blocked" || no_work;
204                    }
205                    if !stale {
206                        continue;
207                    }
208                    for run in &open_runs {
209                        let _ = self
210                            .state
211                            .finish_goal_run(
212                                &run.id,
213                                "failed",
214                                Some("Closed before automatic recovery."),
215                            )
216                            .await;
217                    }
218                }
219                Ok(_) => {}
220                Err(error) => {
221                    warn!(goal_id = %goal_id, %error, "Could not reconcile before recovery");
222                    continue;
223                }
224            }
225            // Bump the attempt counter before creating any work so a crash
226            // between the two cannot hot-loop recovery launches.
227            if let Err(error) = self.state.record_scheduled_recovery_attempt(&goal_id).await {
228                warn!(goal_id = %goal_id, %error, "Failed to record recovery attempt");
229                continue;
230            }
231            let attempt = recovery.recovery_attempts.saturating_add(1);
232            let now = chrono::Utc::now().to_rfc3339();
233            let recovery_task_id = uuid::Uuid::new_v4().to_string();
234            let mut context = goal
235                .context
236                .as_deref()
237                .and_then(|raw| serde_json::from_str::<serde_json::Value>(raw).ok())
238                .filter(serde_json::Value::is_object)
239                .unwrap_or_else(|| serde_json::json!({}));
240            context["recovery_for_run"] = serde_json::json!(recovery.last_failed_run_id);
241            context["terminal_recovery"] = serde_json::json!(true);
242            context["recovery_attempt"] = serde_json::json!(attempt);
243            context["recovery_cause"] = serde_json::json!(
244                recovery
245                    .latest_failure_kind
246                    .map(crate::traits::ScheduledFailureKind::as_str)
247            );
248            let task = crate::traits::Task {
249                id: recovery_task_id.clone(),
250                goal_id: goal_id.clone(),
251                description: format!(
252                    "Directly recover and finish: {} [SYSTEM: automatic recovery attempt {attempt} of {} after {} consecutive failed runs (typed cause {}). The schedule is paused until this run completes with verified receipts. Earlier failures recorded in the ledger are historical evidence from a previous environment, not proof that their cause persists: re-run the previously failing step once in this attempt and judge from its fresh receipt before concluding that recovery is exhausted. If the objective's repository or workspace is not present in the attempt workspace, locate it with search_files and bind it with manage_automations bind_workspace before reporting a blocker.]",
253                    goal.description,
254                    Self::ESCALATED_RECOVERY_MAX_ATTEMPTS,
255                    recovery.consecutive_failures,
256                    recovery
257                        .latest_failure_kind
258                        .map_or("unknown", crate::traits::ScheduledFailureKind::as_str),
259                ),
260                status: "pending".to_string(),
261                priority: "high".to_string(),
262                task_order: 0,
263                parallel_group: None,
264                depends_on: None,
265                agent_id: None,
266                context: Some(context.to_string()),
267                result: None,
268                error: None,
269                blocker: None,
270                idempotent: false,
271                retry_count: 0,
272                max_retries: 0,
273                created_at: now,
274                started_at: None,
275                completed_at: None,
276            };
277            let recovery_run = match self
278                .state
279                .start_goal_run(&goal_id, "recovery", None, Some(&recovery_task_id))
280                .await
281            {
282                Ok(run) => run,
283                Err(error) => {
284                    warn!(goal_id = %goal_id, %error, "Failed to start automatic recovery run");
285                    continue;
286                }
287            };
288            match self.state.create_task(&task).await {
289                Ok(()) => info!(
290                    goal_id = %goal_id,
291                    task_id = %recovery_task_id,
292                    attempt,
293                    max_attempts = Self::ESCALATED_RECOVERY_MAX_ATTEMPTS,
294                    "Launched automatic recovery run for escalated scheduled objective"
295                ),
296                Err(error) => {
297                    warn!(goal_id = %goal_id, %error, "Failed to create automatic recovery task");
298                    // A run with no work would hold the objective forever.
299                    let _ = self
300                        .state
301                        .finish_goal_run(
302                            &recovery_run.id,
303                            "failed",
304                            Some("The recovery task could not be created."),
305                        )
306                        .await;
307                }
308            }
309        }
310    }
311
312    pub async fn fire_due_schedule(&self, mut schedule: GoalSchedule) -> anyhow::Result<()> {
313        let now = chrono::Utc::now();
314        let now_ts = now.to_rfc3339();
315
316        let Some(mut goal) = self.state.get_goal(&schedule.goal_id).await? else {
317            return Ok(());
318        };
319
320        // A stored zone this cannot read is never guessed as the owner's
321        // clock: the schedule is paused and the owner told, once.
322        if let Err(error) = crate::schedule::ScheduleZone::from_stored(&schedule.tz) {
323            warn!(
324                schedule_id = %schedule.id,
325                goal_id = %schedule.goal_id,
326                tz = %schedule.tz,
327                %error,
328                "Paused a schedule whose stored time zone is unknown"
329            );
330            schedule.is_paused = true;
331            schedule.updated_at = now_ts.clone();
332            self.state.update_goal_schedule(&schedule).await?;
333            let msg = format!(
334                "Paused the schedule of \"{}\": its time zone '{}' is not one this can read. \
335                 Change its schedule to run it again.",
336                self.presenter.goal_label(&goal.description),
337                schedule.tz,
338            );
339            let entry = crate::traits::NotificationEntry::new(
340                &goal.id,
341                &goal.session_id,
342                "evergreen_alert",
343                &msg,
344            );
345            if let Err(error) = self.state.enqueue_notification(&entry).await {
346                warn!(goal_id = %goal.id, %error, "Failed to enqueue unknown-zone notice");
347            }
348            return Ok(());
349        }
350
351        // Safety: only active orchestration goals should fire.
352        if goal.domain != "orchestration" || goal.status != "active" {
353            return Ok(());
354        }
355
356        // A recurring run long past its time (the daemon was off) is not
357        // started late: it is skipped, the schedule moves to its next run,
358        // and the owner is told, so a morning digest never lands at night
359        // and a missed run is never silent. A one-shot still fires: a late
360        // reminder beats none.
361        if !schedule.is_one_shot
362            && let Ok(due) = chrono::DateTime::parse_from_rfc3339(&schedule.next_run_at)
363        {
364            let due = due.with_timezone(&chrono::Utc);
365            if let Some(window) =
366                crate::schedule::catch_up_window_in(&schedule.cron_expr, &schedule.tz, due)
367                && now - due > window
368                && let Ok(next) =
369                    crate::schedule::compute_next_run_in(&schedule.cron_expr, &schedule.tz)
370            {
371                schedule.next_run_at = next.to_rfc3339();
372                schedule.updated_at = now_ts.clone();
373                self.state.update_goal_schedule(&schedule).await?;
374                // The miss is part of the automation's history (its History
375                // and last-run line), not only a notice: a run that was due
376                // and never ran must stay provable. It is recorded closed and
377                // apart from the failure budget: a miss is not a failure.
378                if let Err(error) = self
379                    .state
380                    .record_missed_goal_run(
381                        &goal.id,
382                        Some(&schedule.id),
383                        &due.to_rfc3339(),
384                        MISSED_RUN_SUMMARY,
385                    )
386                    .await
387                {
388                    warn!(goal_id = %goal.id, %error, "Failed to record the missed run");
389                }
390                let msg = format!(
391                    "Missed the {} run of \"{}\": the daemon wasn't running then, and it is \
392                     too late to be useful now. Next run: {}.",
393                    crate::schedule::owner_time(&due.with_timezone(&chrono::Local)),
394                    self.presenter.goal_label(&goal.description),
395                    crate::schedule::owner_time(&next.with_timezone(&chrono::Local)),
396                );
397                let entry = crate::traits::NotificationEntry::new(
398                    &goal.id,
399                    &goal.session_id,
400                    "missed_run",
401                    &msg,
402                );
403                if let Err(error) = self.state.enqueue_notification(&entry).await {
404                    warn!(goal_id = %goal.id, %error, "Failed to enqueue missed-run notice");
405                }
406                info!(
407                    goal_id = %goal.id,
408                    schedule_id = %schedule.id,
409                    due = %due,
410                    "Skipped a scheduled run past its catch-up window"
411                );
412                return Ok(());
413            }
414        }
415
416        // No model connected: this firing is skipped (a recurring schedule
417        // moves to its next run; a one-shot waits a little and tries again)
418        // and the owner is told once. A typed reminder needs no model: it
419        // still goes out by its fast path below.
420        if crate::reminders::fire_text_for_goal(goal.context.as_deref()).is_none()
421            && self.without_model().await
422        {
423            if schedule.is_one_shot {
424                schedule.next_run_at =
425                    (now + chrono::Duration::seconds(ONE_SHOT_RETRY_SECS)).to_rfc3339();
426            } else {
427                schedule.next_run_at =
428                    crate::schedule::compute_next_run_in(&schedule.cron_expr, &schedule.tz)?
429                        .to_rfc3339();
430            }
431            schedule.updated_at = now_ts.clone();
432            self.state.update_goal_schedule(&schedule).await?;
433            tracing::debug!(
434                goal_id = %goal.id,
435                schedule_id = %schedule.id,
436                "Skipped a scheduled run: no model is connected"
437            );
438            self.notice_needs_model(&goal).await;
439            return Ok(());
440        }
441
442        // A continuous goal idle >30 days has likely stopped doing useful
443        // work. We KEEP firing it (so it can recover on its own once it starts
444        // succeeding again), but surface a one-time alert so a silently-dead
445        // goal becomes visible instead of being skipped forever. The alert is
446        // gated on `notified_at` so we don't re-alert on every tick while the
447        // goal stays idle (e.g. blocked by an open task via coalescing).
448        if goal.goal_type == "continuous"
449            && goal.notified_at.is_none()
450            && let Some(ref last_action) = goal.last_useful_action
451            && let Ok(ts) = chrono::DateTime::parse_from_rfc3339(last_action)
452        {
453            let days_idle = (chrono::Utc::now() - ts.with_timezone(&chrono::Utc)).num_days();
454            if days_idle > 30 {
455                warn!(
456                    goal_id = %goal.id,
457                    description = %goal.description,
458                    days_idle,
459                    "Continuous goal idle >30 days; alerting user and continuing to fire"
460                );
461                let msg = format!(
462                    "Heads up: your recurring goal \"{}\" hasn't made progress in {} days. \
463                             It's still scheduled and will keep trying — reply if you'd like to pause or cancel it.",
464                    self.presenter.goal_label(&goal.description),
465                    days_idle
466                );
467                let entry = crate::traits::NotificationEntry::new(
468                    &goal.id,
469                    &goal.session_id,
470                    "evergreen_alert",
471                    &msg,
472                );
473                match self.state.enqueue_goal_notification(&entry).await {
474                    Ok(_) => {
475                        // Keep the in-memory copy consistent so the later
476                        // update_goal (after task creation) doesn't clobber
477                        // notified_at back to NULL and re-alert next tick.
478                        goal.notified_at = Some(now_ts.clone());
479                    }
480                    Err(error) => {
481                        warn!(
482                            goal_id = %goal.id,
483                            %error,
484                            "Failed to atomically enqueue idle-goal alert"
485                        );
486                    }
487                }
488            }
489        }
490
491        // Only work belonging to an open goal run can apply backpressure to a
492        // new scheduled firing. Historical blocked tasks are intentionally
493        // retained as audit records after their run is closed; counting all
494        // tasks for the goal would make those records suppress every future
495        // coalesced firing forever.
496        let open_runs = self
497            .reconcile_open_scheduled_runs_for_goal(&goal.id)
498            .await?;
499        let mut open_count = 0;
500        for run in &open_runs {
501            let run_tasks = self.state.get_tasks_for_goal_run(&run.id).await?;
502            open_count += run_tasks
503                .iter()
504                .filter(|task| task_blocks_later_schedule_fire(run, task, &run_tasks))
505                .count();
506        }
507
508        let fire_policy = schedule.fire_policy.as_str();
509        let coalesce = fire_policy != "always_fire";
510        const ALWAYS_FIRE_OPEN_TASK_CAP: usize = 3;
511
512        // Backpressure: coalesce by default; always_fire only up to a cap.
513        if (coalesce && open_count > 0) || (!coalesce && open_count >= ALWAYS_FIRE_OPEN_TASK_CAP) {
514            if schedule.is_one_shot {
515                // Keep the one-shot due, but avoid hot-looping while open work exists.
516                schedule.next_run_at = (now + chrono::Duration::minutes(5)).to_rfc3339();
517            } else if let Ok(next) =
518                crate::schedule::compute_next_run_in(&schedule.cron_expr, &schedule.tz)
519            {
520                schedule.next_run_at = next.to_rfc3339();
521            }
522            schedule.updated_at = now_ts.clone();
523            let _ = self.state.update_goal_schedule(&schedule).await;
524            info!(
525                goal_id = %goal.id,
526                schedule_id = %schedule.id,
527                fire_policy,
528                open_run_count = open_runs.len(),
529                open_task_count = open_count,
530                "Deferred schedule fire because open goal-run work is still active"
531            );
532            return Ok(());
533        }
534
535        // Budget check: skip if *today's* daily budget is exhausted, but back off
536        // schedule to avoid hot-loop. Stale prior-day usage must not count, or the
537        // goal deadlocks across the day boundary (it would defer forever and never
538        // fire, so its counter would never reset).
539        let budget_today = now.date_naive().to_string();
540        let effective_daily_budget = if let Some(configured_budget) = goal.budget_daily {
541            crate::goal_tokens::load_goal_daily_budget_override(
542                self.state.as_ref(),
543                &goal.id,
544                configured_budget,
545                crate::goal_tokens::SCHEDULED_AUTONOMOUS_HARD_TOKEN_CAP,
546            )
547            .await
548            .map(|value| value.budget_daily)
549            .or(Some(configured_budget))
550        } else {
551            None
552        };
553        if daily_budget_exhausted(
554            effective_daily_budget,
555            goal.tokens_used_today,
556            &goal.tokens_used_day,
557            &budget_today,
558        ) {
559            schedule.last_run_at = Some(now_ts.clone());
560            schedule.next_run_at = if schedule.is_one_shot {
561                (now + chrono::Duration::hours(24)).to_rfc3339()
562            } else if let Ok(next) =
563                crate::schedule::compute_next_run_in(&schedule.cron_expr, &schedule.tz)
564            {
565                next.to_rfc3339()
566            } else {
567                (now + chrono::Duration::hours(24)).to_rfc3339()
568            };
569            schedule.updated_at = now_ts.clone();
570            let _ = self.state.update_goal_schedule(&schedule).await;
571            let msg = format!(
572                "Skipped the scheduled run for \"{}\" because today's daily token budget \
573                 ({}) is exhausted by cumulative usage across this goal's runs today, not by \
574                 this unstarted run alone. No work was started. The schedule remains active and \
575                 will try again at its next normal fire after the counter resets.",
576                self.presenter.goal_label(&goal.description),
577                effective_daily_budget.unwrap_or_default(),
578            );
579            let entry = crate::traits::NotificationEntry::new(
580                &goal.id,
581                &goal.session_id,
582                "token_alert",
583                &msg,
584            );
585            if let Err(error) = self.state.enqueue_notification(&entry).await {
586                error!(
587                    goal_id = %goal.id,
588                    %error,
589                    "Failed to enqueue daily-budget notification"
590                );
591            }
592            return Ok(());
593        }
594        if !daily_budget_has_run_capacity(
595            effective_daily_budget,
596            goal.budget_per_check,
597            goal.tokens_used_today,
598            &goal.tokens_used_day,
599            &budget_today,
600        ) {
601            let remaining = effective_daily_budget
602                .unwrap_or_default()
603                .saturating_sub(goal.tokens_used_today)
604                .max(0);
605            let required = goal.budget_per_check.unwrap_or_default().max(0);
606            schedule.last_run_at = Some(now_ts.clone());
607            schedule.next_run_at = if schedule.is_one_shot {
608                (now + chrono::Duration::minutes(15)).to_rfc3339()
609            } else if let Ok(next) =
610                crate::schedule::compute_next_run_in(&schedule.cron_expr, &schedule.tz)
611            {
612                next.to_rfc3339()
613            } else {
614                (now + chrono::Duration::hours(24)).to_rfc3339()
615            };
616            schedule.updated_at = now_ts.clone();
617            let _ = self.state.update_goal_schedule(&schedule).await;
618
619            let msg = format!(
620                "Skipped the scheduled run for \"{}\" because only {} daily-budget tokens \
621                 remain and a full run is allowed up to {}. No work was started. The schedule \
622                 remains active and will try again at its next normal fire after the daily \
623                 counter resets.",
624                self.presenter.goal_label(&goal.description),
625                remaining,
626                required,
627            );
628            let entry = crate::traits::NotificationEntry::new(
629                &goal.id,
630                &goal.session_id,
631                "token_alert",
632                &msg,
633            );
634            if let Err(error) = self.state.enqueue_notification(&entry).await {
635                error!(
636                    goal_id = %goal.id,
637                    %error,
638                    "Failed to enqueue remaining-budget notification"
639                );
640            }
641            info!(
642                goal_id = %goal.id,
643                remaining,
644                required,
645                "Skipped scheduled run before admission because remaining daily budget cannot fund one full run"
646            );
647            return Ok(());
648        }
649
650        // Compute the next occurrence; persistence is atomic with its work below.
651        let advanced_next_run = if schedule.is_one_shot {
652            schedule.next_run_at.clone()
653        } else {
654            crate::schedule::compute_next_run_in(&schedule.cron_expr, &schedule.tz)?.to_rfc3339()
655        };
656
657        let run_root_task_id = uuid::Uuid::new_v4().to_string();
658        if coalesce && let Some(open_run) = self.state.get_current_goal_run(&goal.id).await? {
659            let run_tasks = self.state.get_tasks_for_goal_run(&open_run.id).await?;
660            if !run_tasks.is_empty() {
661                let active_or_human_blocked = run_tasks
662                    .iter()
663                    .any(|task| task_blocks_later_schedule_fire(&open_run, task, &run_tasks));
664                if active_or_human_blocked {
665                    warn!(
666                        goal_id = %goal.id,
667                        run_id = %open_run.id,
668                        "Skipped schedule fire because the previous goal run is still open"
669                    );
670                    return Ok(());
671                }
672                let status = if run_tasks.iter().any(task_is_terminal_schedule_failure) {
673                    "failed"
674                } else {
675                    "completed"
676                };
677                // A blocked child of the superseded occurrence is an
678                // audit record now; mark it so it never reads as open
679                // work waiting on an owner.
680                for task in run_tasks.iter().filter(|task| task.status == "blocked") {
681                    let mut superseded = task.clone();
682                    superseded.status = "superseded".to_string();
683                    superseded.completed_at = Some(chrono::Utc::now().to_rfc3339());
684                    superseded.result = Some(format!(
685                        "Superseded by the next scheduled occurrence. Prior blocker: {}",
686                        task.blocker.as_deref().unwrap_or("none")
687                    ));
688                    if let Err(error) = self.state.update_task(&superseded).await {
689                        warn!(task_id = %task.id, %error, "Failed to supersede blocked task");
690                    }
691                }
692                let _ = self
693                    .state
694                    .finish_goal_run(
695                        &open_run.id,
696                        status,
697                        Some("Closed before the next scheduled firing."),
698                    )
699                    .await?;
700            }
701        }
702        // Create a pending task for this scheduled run.
703        let task = crate::traits::Task {
704            id: run_root_task_id.clone(),
705            goal_id: goal.id.clone(),
706            description: if schedule.is_one_shot || goal.goal_type == "finite" {
707                format!(
708                    "Execute scheduled goal: {} [SYSTEM: already scheduled and firing now; do not reschedule.]",
709                    goal.description
710                )
711            } else {
712                format!(
713                    "Scheduled check: {} [SYSTEM: already scheduled and firing now; do not reschedule.]",
714                    goal.description
715                )
716            },
717            status: "pending".to_string(),
718            priority: if goal.goal_type == "continuous" {
719                "low".to_string()
720            } else {
721                "medium".to_string()
722            },
723            task_order: 0,
724            parallel_group: None,
725            depends_on: None,
726            agent_id: None,
727            context: goal.context.clone(),
728            result: None,
729            error: None,
730            blocker: None,
731            // A scheduled root can perform externally visible writes. Retrying
732            // the whole orchestration after an ambiguous failure can duplicate
733            // those writes, so only individual, explicitly idempotent child
734            // tasks may be retried.
735            idempotent: false,
736            retry_count: 0,
737            max_retries: 0,
738            created_at: now_ts.clone(),
739            started_at: None,
740            completed_at: None,
741        };
742
743        let Some(goal_run) = self
744            .state
745            .enqueue_scheduled_occurrence(
746                &schedule,
747                &advanced_next_run,
748                &goal,
749                &task,
750                effective_daily_budget,
751            )
752            .await?
753        else {
754            return Ok(());
755        };
756
757        // ── Plain-reminder fast path: the only deliverable is a message back
758        // to the user, so deliver after committing its root, bypassing
759        // the task-lead pipeline (which adds a minute-plus of dispatch and
760        // LLM latency). Falls through to the normal pipeline if the message
761        // can't be delivered.
762        if let Some(fire_text) = crate::reminders::fire_text_for_goal(goal.context.as_deref()) {
763            let delivered = if let Some(hub_arc) = self.hub.clone() {
764                hub_arc
765                    .send_text(&goal.session_id, &fire_text)
766                    .await
767                    .is_ok()
768            } else {
769                false
770            };
771            if delivered {
772                // Record a completed task so history/diagnostics show the run.
773                let task = crate::traits::Task {
774                    id: run_root_task_id.clone(),
775                    goal_id: goal.id.clone(),
776                    description: format!("Deliver reminder: {}", goal.description),
777                    status: "completed".to_string(),
778                    priority: "medium".to_string(),
779                    task_order: 0,
780                    parallel_group: None,
781                    depends_on: None,
782                    agent_id: Some("reminder-fast-path".to_string()),
783                    context: None,
784                    result: Some(fire_text),
785                    error: None,
786                    blocker: None,
787                    idempotent: false,
788                    retry_count: 0,
789                    max_retries: 1,
790                    created_at: now_ts.clone(),
791                    started_at: Some(now_ts.clone()),
792                    completed_at: Some(now_ts.clone()),
793                };
794                self.state.update_task(&task).await?;
795                let _ = self
796                    .state
797                    .finish_goal_run(
798                        &goal_run.id,
799                        "completed",
800                        Some("Reminder delivered successfully."),
801                    )
802                    .await?;
803
804                let mut updated = goal.clone();
805                if schedule.is_one_shot {
806                    updated.status = "completed".to_string();
807                    updated.completed_at = Some(now_ts.clone());
808                    // The reminder itself is the notification — suppress the
809                    // generic "Goal completed" follow-up.
810                    updated.notified_at = Some(now_ts.clone());
811                }
812                updated.last_useful_action = Some(now_ts.clone());
813                updated.updated_at = now_ts.clone();
814                let _ = self.state.update_goal(&updated).await;
815
816                info!(
817                    goal_id = %goal.id,
818                    one_shot = schedule.is_one_shot,
819                    "Delivered plain reminder via fast path"
820                );
821                return Ok(());
822            }
823            warn!(
824                goal_id = %goal.id,
825                "Reminder fast path could not deliver; falling back to task pipeline"
826            );
827        }
828
829        info!(
830            goal_id = %goal.id,
831            schedule_id = %schedule.id,
832            task_id = %task.id,
833            "Enqueued scheduled task"
834        );
835
836        // Notify user that the scheduled goal is executing (DMs only —
837        // group channels just get the results without progress noise).
838        // Post the "Running scheduled task" announcement as a TRACKED surface so
839        // the task lead's progress heartbeat can edit it in place — one self-
840        // updating message instead of a separate announcement + progress stream.
841        let mut running_surface_id: Option<String> = None;
842        let local_hour = chrono::Timelike::hour(&chrono::Local::now());
843        if !aidaemon_events::session::is_group_session(&goal.session_id)
844            && crate::traits::NotificationEntry::routine_delivery_allowed_at_local_hour(local_hour)
845            && let Some(hub_arc) = self.hub.clone()
846        {
847            let short_desc = self.presenter.goal_label(&goal.description);
848            running_surface_id = hub_arc
849                .send_text_tracked(
850                    &goal.session_id,
851                    &format!("⏳ **Scheduled run in progress**\n\n{}", short_desc),
852                )
853                .await
854                .ok()
855                .flatten();
856        }
857
858        // Dispatch immediately instead of waiting for the orphan-recovery pass
859        // (which only picks up tasks older than 60s, so every scheduled run
860        // used to start at least a minute late). If no agent is available the
861        // orphan dispatcher still picks the task up on a later tick.
862        if let Some(agent_arc) = self.live_agent() {
863            let agent_id = format!("heartbeat-schedule-fire-{}", uuid::Uuid::new_v4());
864            match self
865                .state
866                .claim_task_with_lease(&task.id, &agent_id, Some("profile-task-lead"), 180)
867                .await
868            {
869                Ok(Some(_)) => {
870                    if let Some(ref registry) = self.goal_token_registry {
871                        registry.register(&goal.id).await;
872                    }
873                    agent_arc.spawn_task_lead(
874                        goal.clone(),
875                        task.description.clone(),
876                        task.id.clone(),
877                        running_surface_id,
878                    );
879                }
880                Ok(None) => {}
881                Err(e) => {
882                    warn!(
883                        task_id = %task.id,
884                        error = %e,
885                        "Failed to claim scheduled task for immediate dispatch"
886                    );
887                }
888            }
889        }
890
891        Ok(())
892    }
893}
894
895#[cfg(test)]
896#[path = "schedules_tests.rs"]
897mod tests;