aidaemon_work/scheduler/tasks.rs
1//! Stuck, blocked, retried and orphaned tasks.
2
3use super::*;
4
5impl GoalCycle {
6 /// Detect tasks that have been running/claimed longer than the timeout and mark them interrupted.
7 pub async fn detect_stuck_tasks(&self) {
8 match self.state.recover_expired_task_attempts().await {
9 Ok(tasks) if !tasks.is_empty() => {
10 warn!(
11 count = tasks.len(),
12 "Recovered tasks whose execution leases expired"
13 );
14 }
15 Ok(_) => {}
16 Err(error) => {
17 error!(%error, "Failed to recover expired execution leases");
18 return;
19 }
20 }
21 let stuck = match self
22 .state
23 .get_stuck_tasks(self.task_inactivity_timeout_secs)
24 .await
25 {
26 Ok(t) => t,
27 Err(e) => {
28 error!(error = %e, "Failed to get stuck tasks");
29 return;
30 }
31 };
32 for task in &stuck {
33 let last_activity = self
34 .state
35 .get_task_activities(&task.id)
36 .await
37 .ok()
38 .and_then(|acts| acts.last().map(|a| a.created_at.clone()));
39 let inactivity_secs = task_inactivity_secs(
40 last_activity.as_deref(),
41 task.started_at.as_deref().unwrap_or(&task.created_at),
42 chrono::Utc::now(),
43 );
44 warn!(
45 task_id = %task.id,
46 goal_id = %task.goal_id,
47 inactivity_secs,
48 "Marking stuck task as interrupted"
49 );
50 if let Err(e) = self.state.mark_task_interrupted(&task.id).await {
51 error!(task_id = %task.id, error = %e, "Failed to mark stuck task");
52 }
53 }
54 }
55
56 pub async fn block_pending_tasks_with_terminal_failed_dependencies(&self) {
57 let goals = match self.state.get_active_goals().await {
58 Ok(g) => g,
59 Err(e) => {
60 error!(error = %e, "Failed to get active goals for pending dependency cleanup");
61 return;
62 }
63 };
64
65 let now = chrono::Utc::now().to_rfc3339();
66 let terminal_failed = super::task_status_is_terminal_failure;
67
68 for goal in &goals {
69 let tasks = match self.state.get_tasks_for_goal(&goal.id).await {
70 Ok(t) => t,
71 Err(e) => {
72 error!(goal_id = %goal.id, error = %e, "Failed to get tasks for pending dependency cleanup");
73 continue;
74 }
75 };
76 let graph = match crate::traits::task_execution_graph(&tasks) {
77 Ok(graph) => graph,
78 Err(error) => {
79 error!(goal_id = %goal.id, %error, "Invalid task dependency graph; leaving tasks unclaimed");
80 continue;
81 }
82 };
83 let by_id: std::collections::HashMap<&str, &crate::traits::Task> =
84 tasks.iter().map(|t| (t.id.as_str(), t)).collect();
85
86 for task in tasks.iter().filter(|t| t.status == "pending") {
87 let Some(failed_dep) = graph
88 .unresolved_dependencies(&task.id)
89 .iter()
90 .filter_map(|dependency| by_id.get(dependency.id.as_str()))
91 .find(|dep| terminal_failed(&dep.status))
92 else {
93 continue;
94 };
95
96 let mut updated = task.clone();
97 updated.status = "blocked".to_string();
98 updated.blocker = Some(format!(
99 "Dependency {} ended with status {} before this task could run.",
100 failed_dep.id, failed_dep.status
101 ));
102 updated.completed_at = Some(now.clone());
103 if let Err(e) = self.state.update_task(&updated).await {
104 error!(
105 task_id = %task.id,
106 goal_id = %goal.id,
107 dependency_id = %failed_dep.id,
108 error = %e,
109 "Failed to block pending task with terminal failed dependency"
110 );
111 } else {
112 warn!(
113 task_id = %task.id,
114 goal_id = %goal.id,
115 dependency_id = %failed_dep.id,
116 dependency_status = %failed_dep.status,
117 "Blocked pending task with terminal failed dependency"
118 );
119 }
120 }
121 }
122 }
123
124 /// Auto-retry failed idempotent tasks that haven't exceeded their max retries.
125 /// Resets them to "pending" so they get picked up by dispatch_pending_tasks.
126 pub async fn auto_retry_failed_tasks(&self) {
127 let goals = match self.state.get_active_goals().await {
128 Ok(g) => g,
129 Err(e) => {
130 error!(error = %e, "Failed to get active goals for auto-retry");
131 return;
132 }
133 };
134
135 let mut retried = 0;
136 for goal in &goals {
137 // Only retry within active orchestration goals.
138 if goal.status != "active" {
139 continue;
140 }
141
142 // The active task lead owns retries for its run. Promoting one of
143 // its freshly-failed tasks back to pending here can race the lead's
144 // own completion accounting and manufacture an orphaned run.
145 if self
146 .goal_token_registry
147 .as_ref()
148 .is_some_and(|registry| registry.is_run_active(&goal.id))
149 {
150 continue;
151 }
152
153 let tasks = match self.state.get_tasks_for_goal(&goal.id).await {
154 Ok(t) => t,
155 Err(_) => continue,
156 };
157 let schedules = self
158 .state
159 .get_schedules_for_goal(&goal.id)
160 .await
161 .unwrap_or_default();
162 let scheduled_run = if schedules.is_empty() {
163 None
164 } else {
165 self.state
166 .get_scheduled_run_state(&goal.id)
167 .await
168 .ok()
169 .flatten()
170 };
171
172 // Scheduled goals intentionally stay active between runs. Without
173 // an active run record there is no retryable cycle, regardless of
174 // whether old child tasks were individually marked idempotent.
175 if !schedules.is_empty() && scheduled_run.is_none() {
176 continue;
177 }
178
179 for task in &tasks {
180 if scheduled_run
181 .as_ref()
182 .is_some_and(|run| !timestamp_is_at_or_after(&task.created_at, &run.created_at))
183 {
184 continue;
185 }
186 if task.status == "failed" && task.idempotent && task.retry_count < task.max_retries
187 {
188 let mut retry_task = task.clone();
189 retry_task.status = "pending".to_string();
190 retry_task.retry_count += 1;
191 retry_task.result = None;
192 retry_task.error = None;
193 retry_task.blocker = None;
194 retry_task.agent_id = None;
195 retry_task.started_at = None;
196 retry_task.completed_at = None;
197
198 if let Err(e) = self.state.update_task(&retry_task).await {
199 error!(task_id = %task.id, error = %e, "Failed to auto-retry failed task");
200 } else {
201 retried += 1;
202 info!(
203 task_id = %task.id,
204 goal_id = %goal.id,
205 retry = retry_task.retry_count,
206 max_retries = retry_task.max_retries,
207 "Auto-retried failed idempotent task"
208 );
209
210 // Notify user that a retry is in progress
211 let task_desc: String = task.description.chars().take(160).collect();
212 let goal_desc: String = goal.description.chars().take(120).collect();
213 let msg = format!(
214 "Retrying task (attempt {}/{}): {} (goal: {})",
215 retry_task.retry_count, retry_task.max_retries, task_desc, goal_desc
216 );
217 let entry = crate::traits::NotificationEntry::new(
218 &goal.id,
219 &goal.session_id,
220 "status_update",
221 &msg,
222 );
223 if let Err(error) = self.state.enqueue_notification(&entry).await {
224 warn!(
225 task_id = %task.id,
226 %error,
227 "Failed to enqueue task retry notification"
228 );
229 }
230 }
231 }
232 }
233 }
234
235 if retried > 0 {
236 info!(count = retried, "Auto-retried failed idempotent tasks");
237 }
238 }
239
240 /// Dispatch orphaned pending tasks by atomically claiming them and spawning task leads.
241 ///
242 /// For each active goal with pending tasks but no running agent:
243 /// 1. Atomically claim a task via `claim_task` (prevents duplicate dispatch)
244 /// 2. Spawn a background task lead gated by the semaphore
245 /// 3. The task lead picks up all pending tasks for the goal
246 ///
247 /// Falls back to notification if no agent reference is available.
248 pub async fn dispatch_pending_tasks(&self) {
249 let pending = match self.state.get_pending_tasks_by_priority(20).await {
250 Ok(t) => t,
251 Err(e) => {
252 error!(error = %e, "Failed to get pending tasks");
253 return;
254 }
255 };
256 if pending.is_empty() {
257 return;
258 }
259
260 // Group pending tasks by goal_id
261 let mut goals_with_pending: std::collections::HashMap<String, Vec<&crate::traits::Task>> =
262 std::collections::HashMap::new();
263 for task in &pending {
264 goals_with_pending
265 .entry(task.goal_id.clone())
266 .or_default()
267 .push(task);
268 }
269
270 for (goal_id, tasks) in &goals_with_pending {
271 let mut goal = match self.state.get_goal(goal_id).await {
272 Ok(Some(g)) => g,
273 _ => continue,
274 };
275
276 // Self-heal the impossible state produced by older run_now code:
277 // a manual run with a pending root task attached to a stalled goal.
278 // The task dispatcher normally filters non-active goals, so without
279 // this invariant repair the run can say "running" forever despite
280 // never having acquired a worker.
281 if goal.status == "stalled" {
282 let stranded_run = match self.state.get_current_goal_run(goal_id).await {
283 Ok(Some(run)) => {
284 let run_tasks = self
285 .state
286 .get_tasks_for_goal_run(&run.id)
287 .await
288 .unwrap_or_default();
289 stranded_manual_run_matches_pending_tasks(&run, &run_tasks, tasks)
290 .then_some(run)
291 }
292 _ => None,
293 };
294 if let Some(run) = stranded_run {
295 goal.status = "active".to_string();
296 goal.completed_at = None;
297 goal.updated_at = chrono::Utc::now().to_rfc3339();
298 if let Err(error) = self.state.update_goal(&goal).await {
299 error!(goal_id, %error, "Failed to reactivate stranded manual run");
300 continue;
301 }
302 warn!(
303 goal_id,
304 run_id = %run.id,
305 pending_count = tasks.len(),
306 "Reactivated stranded manual run before dispatch"
307 );
308 let message = format!(
309 "Recovered the existing manual run `{}`; it had been queued behind a stalled goal and never started. No duplicate was created. Starting it now, with progress updates enabled.",
310 run.id
311 );
312 let entry = crate::traits::NotificationEntry::new(
313 goal_id,
314 &goal.session_id,
315 "status_update",
316 &message,
317 );
318 if let Err(error) = self.state.enqueue_notification(&entry).await {
319 warn!(goal_id, %error, "Failed to enqueue manual-run recovery update");
320 }
321 }
322 }
323
324 // Only active goals are dispatchable. Stalled non-manual work is
325 // intentionally left alone for explicit recovery.
326 if goal.status != "active" {
327 continue;
328 }
329
330 // A live task lead is authoritative for this goal even during a
331 // brief interval where none of its task rows are marked running.
332 // Do not let orphan recovery claim a pending task during that gap.
333 if self
334 .goal_token_registry
335 .as_ref()
336 .is_some_and(|registry| registry.is_run_active(goal_id))
337 {
338 continue;
339 }
340
341 // Mandate controllers are not ordinary unscheduled goals. Generic
342 // orphan recovery may provide a fallback for the exact pending root
343 // of the current mandate run, but it must never promote a model-
344 // authored non-root action task into a task lead. Such tasks remain
345 // owned by mandate finalization/orphan reconciliation.
346 let mandate_controller = match self.state.get_mandate_for_goal(goal_id).await {
347 Ok(mandate) => mandate.is_some(),
348 Err(error) => {
349 warn!(
350 goal_id,
351 %error,
352 "Skipping orphan dispatch because mandate ownership could not be resolved"
353 );
354 continue;
355 }
356 };
357 let current_mandate_root_task_id = if mandate_controller {
358 self.state
359 .get_current_goal_run(goal_id)
360 .await
361 .ok()
362 .flatten()
363 .filter(mandate_run_may_dispatch_root)
364 .and_then(|run| run.root_task_id)
365 } else {
366 None
367 };
368
369 let schedules_for_goal = self.state.get_schedules_for_goal(goal_id).await.ok();
370 let goal_runs = self.state.get_goal_runs(goal_id).await.unwrap_or_default();
371 let is_scheduled_goal = schedules_for_goal
372 .as_ref()
373 .is_some_and(|schedules| !schedules.is_empty())
374 || goal_runs.iter().any(|run| run.trigger_type == "scheduled");
375 let active_scheduled_run = if is_scheduled_goal {
376 self.state
377 .get_scheduled_run_state(goal_id)
378 .await
379 .ok()
380 .flatten()
381 } else {
382 None
383 };
384 // A goal run is the durable isolation boundary for one scheduled or
385 // explicit manual firing. In particular, `trigger_now` starts a new
386 // goal run without advancing the cron schedule's `last_run_at`, so
387 // using only the schedule timestamp here would let a mutation from
388 // the previous run suppress the newly requested run. Prefer the
389 // scheduled-run projection's root-task relationship: legacy runs
390 // may have been created before trigger provenance was typed, but
391 // the root task still identifies their exact owning run.
392 let projected_goal_run = if let Some(scheduled_run) = active_scheduled_run.as_ref() {
393 self.state
394 .get_goal_run_for_task(&scheduled_run.root_task_id)
395 .await
396 .ok()
397 .flatten()
398 .filter(|run| {
399 run.goal_id == *goal_id
400 && matches!(run.status.as_str(), "pending" | "running" | "blocked")
401 })
402 } else {
403 None
404 };
405 let current_goal_run = if is_scheduled_goal {
406 match projected_goal_run {
407 Some(run) => Some(run),
408 None => self
409 .state
410 .get_current_goal_run(goal_id)
411 .await
412 .ok()
413 .flatten()
414 // An automatic recovery occurrence, and a run the owner
415 // started now (Run now, Try again), are valid current
416 // cycles of a scheduled objective: their root task must
417 // be dispatched, never retired as a stale child (live
418 // 2026-11-15: every Run now was retired and failed).
419 .filter(|run| {
420 matches!(
421 run.trigger_type.as_str(),
422 "scheduled" | "recovery" | "manual"
423 )
424 })
425 // Legacy/repair-created open runs can contain old child
426 // rows without an execution root. They are not a valid
427 // current scheduled cycle and must keep using the stale
428 // child retirement fallback below.
429 .filter(|run| run.root_task_id.is_some()),
430 }
431 } else {
432 None
433 };
434 let current_goal_run_task_ids = if let Some(run) = current_goal_run.as_ref() {
435 self.state
436 .get_tasks_for_goal_run(&run.id)
437 .await
438 .ok()
439 .map(|tasks| {
440 tasks
441 .into_iter()
442 .map(|task| task.id)
443 .collect::<HashSet<_>>()
444 })
445 } else {
446 None
447 };
448 let mut eligible_tasks: Vec<&crate::traits::Task> = Vec::with_capacity(tasks.len());
449 for task in tasks.iter().copied() {
450 let eligible = if mandate_controller {
451 current_mandate_root_task_id.as_deref() == Some(task.id.as_str())
452 } else if !is_scheduled_goal {
453 true
454 } else if let Some(run_task_ids) = current_goal_run_task_ids.as_ref() {
455 // Durable run membership is authoritative and avoids
456 // timestamp races between task construction and the run
457 // row created milliseconds later.
458 run_task_ids.contains(&task.id)
459 } else if let Some(run) = active_scheduled_run.as_ref() {
460 timestamp_is_at_or_after(&task.created_at, &run.created_at)
461 } else {
462 // No typed current-run identity means ownership is
463 // indeterminate. Do not infer it from task prose.
464 false
465 };
466 if eligible {
467 eligible_tasks.push(task);
468 continue;
469 }
470
471 if mandate_controller {
472 // Non-root mandate tasks are intentionally invisible to
473 // generic orphan recovery. Leave their state untouched for
474 // the mandate finalizer/reconciler that owns this run.
475 continue;
476 }
477
478 let mut retired = task.clone();
479 retired.status = "cancelled".to_string();
480 retired.idempotent = false;
481 retired.max_retries = 0;
482 retired.error = Some(
483 "Cancelled stale task from a closed scheduled run; a future schedule fire \
484 will create a fresh root task."
485 .to_string(),
486 );
487 retired.completed_at = Some(chrono::Utc::now().to_rfc3339());
488 if let Err(error) = self.state.update_task(&retired).await {
489 warn!(
490 task_id = %task.id,
491 goal_id = %goal_id,
492 %error,
493 "Failed to retire stale scheduled-run task"
494 );
495 } else {
496 info!(
497 task_id = %task.id,
498 goal_id = %goal_id,
499 "Retired stale task from closed scheduled run"
500 );
501 }
502 }
503 if eligible_tasks.is_empty() {
504 continue;
505 }
506
507 // Daily budget is admission control for scheduled runs, not a reason
508 // to abandon already-pending scheduled work.
509 if !is_scheduled_goal {
510 let budget_today = chrono::Utc::now().date_naive().to_string();
511 if daily_budget_exhausted(
512 goal.budget_daily,
513 goal.tokens_used_today,
514 &goal.tokens_used_day,
515 &budget_today,
516 ) {
517 tracing::info!(
518 goal_id = %goal.id,
519 tokens_used = goal.tokens_used_today,
520 budget = ?goal.budget_daily,
521 "Skipping pending-task dispatch — today's goal daily budget exhausted"
522 );
523 continue;
524 }
525 }
526
527 // Check if any tasks are still running (task lead is alive)
528 let all_tasks = match self.state.get_tasks_for_goal(goal_id).await {
529 Ok(t) => t,
530 Err(_) => continue,
531 };
532 // Only consider a task as actively running if it was started/claimed
533 // within the last 10 minutes. Stale claimed tasks (executor crashed)
534 // should not block dispatch forever.
535 let stale_threshold_secs: i64 = 600; // 10 minutes
536 let has_active_nonstale = all_tasks.iter().any(|t| {
537 let belongs_to_current_run = if mandate_controller {
538 current_mandate_root_task_id.as_deref() == Some(t.id.as_str())
539 } else if !is_scheduled_goal {
540 true
541 } else if let Some(run_task_ids) = current_goal_run_task_ids.as_ref() {
542 run_task_ids.contains(&t.id)
543 } else if let Some(run) = active_scheduled_run.as_ref() {
544 timestamp_is_at_or_after(&t.created_at, &run.created_at)
545 } else {
546 false
547 };
548 if !belongs_to_current_run {
549 return false;
550 }
551 if t.status != "running" && t.status != "claimed" {
552 return false;
553 }
554 let timestamp = t.started_at.as_deref().unwrap_or(&t.created_at);
555 chrono::DateTime::parse_from_rfc3339(timestamp)
556 .map(|dt| {
557 let age = chrono::Utc::now() - dt.with_timezone(&chrono::Utc);
558 age.num_seconds() < stale_threshold_secs
559 })
560 .unwrap_or(false)
561 });
562
563 if has_active_nonstale {
564 // Task lead is still working (recently active) — it'll pick up the pending tasks
565 continue;
566 }
567
568 // Orphaned: active goal with pending tasks but nothing running.
569 // Only consider tasks orphaned if they've been pending for > 60 seconds.
570 // This prevents racing with a task lead that just created the tasks
571 // but hasn't started dispatching them yet.
572 let min_age_secs = 60;
573 let all_too_new = eligible_tasks.iter().all(|t| {
574 chrono::DateTime::parse_from_rfc3339(&t.created_at)
575 .map(|dt| {
576 let age = chrono::Utc::now() - dt.with_timezone(&chrono::Utc);
577 age.num_seconds() < min_age_secs
578 })
579 .unwrap_or(false)
580 });
581 if all_too_new {
582 continue;
583 }
584
585 // Idempotency backstop: these pending tasks are orphaned (nothing's
586 // actively running, and they've sat >60s), which is exactly the
587 // situation that let a scheduled goal's side effect get repeated —
588 // e.g. a task lead posts a tweet, a downstream step (verification,
589 // task tracking) hiccups, the run ends up interrupted, and a fresh
590 // task lead gets dispatched here for what looks like unfinished
591 // work but whose real-world action already succeeded. Before
592 // reclaiming, check whether this exact goal run already has a
593 // successful mutating (non-GET) http_request logged; if so, the
594 // run's job is done — close out the leftover pending tasks instead
595 // of spawning another attempt. Never use a prior run's receipt:
596 // an explicit manual run is a new authorized execution even when
597 // the recurring schedule's `last_run_at` has not advanced.
598 // See docs/2026-06-30-telegram-edge-case-findings.md (2026-07-04
599 // escalation: 5 duplicate tweets from repeated goal dispatch).
600 if is_scheduled_goal && let Some(current_run) = current_goal_run.as_ref() {
601 let mutating_success_task_ids =
602 self.goal_run_mutating_success_tasks(¤t_run.id).await;
603 if !mutating_success_task_ids.is_empty() {
604 info!(
605 goal_id = %goal_id,
606 run_id = %current_run.id,
607 pending_count = eligible_tasks.len(),
608 "Goal run already has a successful mutating action; \
609 closing out orphaned pending tasks instead of re-dispatching"
610 );
611 // The receipt is authoritative evidence that the task's
612 // external mutation succeeded, even if a downstream
613 // verification/tracking hiccup left its task status as
614 // interrupted or failed.
615 for task_id in &mutating_success_task_ids {
616 let Ok(Some(mut done)) = self.state.get_task(task_id).await else {
617 continue;
618 };
619 if !done.satisfies_run_completion() {
620 done.status = "completed".to_string();
621 done.error = None;
622 done.blocker = None;
623 done.result = Some(
624 "Auto-reconciled: this task has a successful mutating \
625 tool receipt in the current goal run."
626 .to_string(),
627 );
628 done.completed_at = Some(chrono::Utc::now().to_rfc3339());
629 let _ = self.state.update_task(&done).await;
630 }
631 }
632 for task in &eligible_tasks {
633 let mut done = (*task).clone();
634 done.status = "completed".to_string();
635 done.result = Some(
636 "Auto-closed: a mutating action for this goal's current cycle \
637 already succeeded (see task_activity log); skipped to avoid a \
638 duplicate side effect."
639 .to_string(),
640 );
641 done.completed_at = Some(chrono::Utc::now().to_rfc3339());
642 let _ = self.state.update_task(&done).await;
643 }
644 if self
645 .state
646 .get_tasks_for_goal_run(¤t_run.id)
647 .await
648 .is_ok_and(|run_tasks| {
649 !run_tasks.is_empty()
650 && run_tasks.iter().all(|task| task.satisfies_run_completion())
651 })
652 {
653 let _ = self
654 .state
655 .finish_goal_run(
656 ¤t_run.id,
657 "completed",
658 Some(
659 "Auto-reconciled from a successful mutating receipt in \
660 this goal run; duplicate dispatch was suppressed.",
661 ),
662 )
663 .await;
664 }
665 continue;
666 }
667 }
668
669 // Try to atomically claim the first pending task and spawn a task lead.
670 let first_task = eligible_tasks[0];
671 let agent_id = format!("heartbeat-dispatch-{}", uuid::Uuid::new_v4());
672
673 let attempt = match self
674 .state
675 .claim_task_with_lease(&first_task.id, &agent_id, Some("profile-task-lead"), 180)
676 .await
677 {
678 Ok(Some(attempt)) => attempt,
679 Ok(None) => continue,
680 Err(e) => {
681 error!(task_id = %first_task.id, error = %e, "Failed to claim task for dispatch");
682 continue;
683 }
684 };
685
686 info!(
687 goal_id = %goal_id,
688 task_id = %first_task.id,
689 pending_count = eligible_tasks.len(),
690 "Claimed orphaned task, dispatching task lead"
691 );
692
693 // Try to spawn a task lead via the agent runtime
694 if let Some(agent_arc) = self.live_agent() {
695 // Register cancellation token for this goal if not already present
696 if let Some(ref registry) = self.goal_token_registry {
697 registry.register(&goal.id).await;
698 }
699
700 // The host's task lead runs in its own task. Semaphore gating
701 // happens in the runtime during LLM calls. Use the actual
702 // pending task description as TaskLead input. Passing a
703 // generic "resume orphaned tasks" string causes the TaskLead
704 // to re-scope work away from the user's goal.
705 let dispatch_task_text = if first_task.description.trim().is_empty() {
706 goal.description.clone()
707 } else {
708 first_task.description.clone()
709 };
710
711 agent_arc.spawn_task_lead(
712 goal.clone(),
713 dispatch_task_text,
714 first_task.id.clone(),
715 None,
716 );
717 continue;
718 }
719
720 // No agent available — revert claimed task back to pending so it's
721 // not stranded, then enqueue a stalled notification.
722 warn!(
723 goal_id = %goal_id,
724 task_id = %first_task.id,
725 pending_count = eligible_tasks.len(),
726 "No agent available for dispatch — reverting claim and notifying user"
727 );
728 let patch = crate::traits::TaskAttemptPatch {
729 status: "cancelled".to_string(),
730 error: Some("No agent was available for dispatch.".to_string()),
731 ..Default::default()
732 };
733 let released = self
734 .state
735 .patch_task_from_attempt(&attempt.id, &attempt.lease_token, &patch)
736 .await
737 .unwrap_or(false);
738 if released {
739 let _ = self
740 .state
741 .retry_work_task(&first_task.id, "heartbeat", None)
742 .await;
743 }
744
745 let msg = format!(
746 "{} \"{}\" has {} pending task(s) but no active agent. \
747 You can re-trigger this by asking me about it again.",
748 aidaemon_channels::presentation::GOAL_STALLED_LEAD,
749 goal.description.chars().take(200).collect::<String>(),
750 eligible_tasks.len(),
751 );
752 let entry =
753 crate::traits::NotificationEntry::new(goal_id, &goal.session_id, "stalled", &msg);
754 if let Err(error) = self.state.enqueue_notification(&entry).await {
755 error!(
756 goal_id,
757 %error,
758 "Failed to enqueue stalled-goal notification"
759 );
760 }
761 }
762 }
763
764 /// Idempotency backstop for scheduled goals: returns the tasks in one
765 /// durable goal run that have a logged, successful, mutating (non-GET)
766 /// `http_request` activity.
767 ///
768 /// This is a defense-in-depth check, not the primary fix — it exists so
769 /// that *whatever* caused a scheduled goal's task to look unfinished
770 /// (timeout, tool cooldown, orchestrator misjudgment, a bug nobody's hit
771 /// yet) can never turn into a repeated real-world side effect. It reads
772 /// task_activity rows that are already logged for every tool call
773 /// (`src/agent/turn/tool_execution/run.rs`), so it needs no schema change.
774 /// Fails closed toward "don't block" on any parse/lookup miss — a false
775 /// negative here just falls back to prior behavior, never a false positive
776 /// that would wrongly skip real unfinished work. Scoping by `goal_run_id`
777 /// is what prevents a successful prior run from suppressing a new manual
778 /// trigger.
779 pub async fn goal_run_mutating_success_tasks(&self, run_id: &str) -> Vec<String> {
780 let tasks = match self.state.get_tasks_for_goal_run(run_id).await {
781 Ok(t) => t,
782 Err(_) => return Vec::new(),
783 };
784
785 let mut successful_task_ids = Vec::new();
786 for task in &tasks {
787 let activities = match self.state.get_task_activities(&task.id).await {
788 Ok(a) => a,
789 Err(_) => continue,
790 };
791 // The dispatcher's typed record of an external change, made
792 // from the call's own effects whatever the tool.
793 if activities.iter().any(|activity| {
794 activity.activity_type == crate::traits::REMOTE_CHANGE_ACTIVITY
795 && activity.success == Some(true)
796 }) {
797 successful_task_ids.push(task.id.clone());
798 }
799 }
800 successful_task_ids
801 }
802}
803
804/// A mandate run whose root may be dispatched. `pending` counts: when the
805/// immediate claim finds no free slot, the run stays pending and this is the
806/// only path that can still start it.
807fn mandate_run_may_dispatch_root(run: &crate::traits::GoalRun) -> bool {
808 run.trigger_type == "mandate" && matches!(run.status.as_str(), "pending" | "running")
809}
810
811#[cfg(test)]
812mod mandate_dispatch_tests {
813 use super::*;
814
815 fn run(trigger: &str, status: &str) -> crate::traits::GoalRun {
816 let mut run = crate::traits::GoalRun::new("goal", "project", trigger);
817 run.status = status.to_string();
818 run
819 }
820
821 #[test]
822 fn a_review_whose_first_claim_failed_can_still_start() {
823 assert!(mandate_run_may_dispatch_root(&run("mandate", "pending")));
824 assert!(mandate_run_may_dispatch_root(&run("mandate", "running")));
825 assert!(!mandate_run_may_dispatch_root(&run("mandate", "blocked")));
826 assert!(!mandate_run_may_dispatch_root(&run("scheduled", "pending")));
827 }
828}