1use super::*;
4
5impl GoalCycle {
6 pub async fn deliver_notifications(&self) {
10 self.enqueue_goal_notifications().await;
12
13 self.process_notification_queue().await;
15
16 match self.state.cleanup_expired_notifications().await {
18 Ok(count) if count > 0 => {
19 info!(count, "Cleaned up expired status_update notifications");
20 }
21 Err(e) => {
22 error!(error = %e, "Failed to cleanup expired notifications");
23 }
24 _ => {}
25 }
26 }
27
28 pub async fn enqueue_goal_notifications(&self) {
30 let goals = match self.state.get_goals_needing_notification().await {
31 Ok(g) => g,
32 Err(e) => {
33 error!(error = %e, "Failed to get goals needing notification");
34 return;
35 }
36 };
37 for goal in &goals {
38 let (notification_type, msg) = match goal.status.as_str() {
39 "completed" => {
40 let latest_run = self
44 .state
45 .get_goal_runs(&goal.id)
46 .await
47 .unwrap_or_default()
48 .into_iter()
49 .next();
50 let latest_root_task_id = latest_run
51 .as_ref()
52 .and_then(|run| run.root_task_id.as_deref())
53 .map(str::to_string);
54 let latest_run_unsuccessful = latest_run
57 .as_ref()
58 .is_some_and(|run| matches!(run.status.as_str(), "failed" | "blocked"));
59 let completed_tasks = match latest_run {
60 Some(run) => self
61 .state
62 .get_tasks_for_goal_run(&run.id)
63 .await
64 .unwrap_or_default(),
65 None => self
66 .state
67 .get_tasks_for_goal(&goal.id)
68 .await
69 .unwrap_or_default(),
70 };
71 let fallback_summary: String = goal.description.chars().take(300).collect();
72 let task_results_summary = self.presenter.goal_task_results(
73 &completed_tasks,
74 latest_root_task_id.as_deref(),
75 &fallback_summary,
76 );
77
78 if latest_run_unsuccessful
79 || (!completed_tasks.is_empty()
80 && !crate::goals::tasks_satisfy_goal_completion(&completed_tasks))
81 {
82 let mut corrected = goal.clone();
83 corrected.status = "failed".to_string();
84 corrected.completed_at = Some(chrono::Utc::now().to_rfc3339());
85 corrected.updated_at = chrono::Utc::now().to_rfc3339();
86 if let Err(error) = self.state.update_goal(&corrected).await {
87 error!(goal_id = %goal.id, %error, "Failed to repair inconsistent completed goal state");
88 }
89 (
90 "failed",
91 format!(
92 "Goal incomplete: required tasks did not finish successfully.\n\n{}",
93 task_results_summary.chars().take(4000).collect::<String>()
94 ),
95 )
96 } else {
97 let partial_info = goal
99 .context
100 .as_deref()
101 .and_then(|ctx| serde_json::from_str::<serde_json::Value>(ctx).ok())
102 .filter(|v| {
103 v.get("partial_success")
104 .and_then(|p| p.as_bool())
105 .unwrap_or(false)
106 });
107
108 if let Some(summary) = partial_info {
109 let completed = summary
110 .get("completed")
111 .and_then(|v| v.as_u64())
112 .unwrap_or(0);
113 let failed =
114 summary.get("failed").and_then(|v| v.as_u64()).unwrap_or(0);
115 let blocked =
116 summary.get("blocked").and_then(|v| v.as_u64()).unwrap_or(0);
117 let total = summary.get("total").and_then(|v| v.as_u64()).unwrap_or(0);
118 (
119 "failed",
120 format!(
121 "Goal partially completed ({}/{} tasks succeeded, {} failed, {} blocked):\n\n{}",
122 completed,
123 total,
124 failed,
125 blocked,
126 task_results_summary.chars().take(4000).collect::<String>()
127 ),
128 )
129 } else {
130 (
131 "completed",
132 format!(
133 "{}\n\n{}",
134 goal_completion_header(&completed_tasks),
135 task_results_summary.chars().take(4000).collect::<String>()
136 ),
137 )
138 }
139 }
140 }
141 "failed" => (
142 "failed",
143 format!(
144 "{} {}",
145 aidaemon_channels::presentation::GOAL_FAILED_LEAD,
146 goal.description.chars().take(300).collect::<String>()
147 ),
148 ),
149 _ => continue,
150 };
151
152 let entry = crate::traits::NotificationEntry::new(
156 &goal.id,
157 &goal.session_id,
158 notification_type,
159 &msg,
160 )
161 .with_untrusted(true);
162
163 if let Err(e) = self.state.enqueue_goal_notification(&entry).await {
164 error!(goal_id = %goal.id, error = %e, "Failed to atomically enqueue notification");
165 }
166 }
167 }
168
169 pub async fn record_delivered_notification(
173 &self,
174 entry: &crate::traits::NotificationEntry,
175 delivered_text: &str,
176 ) {
177 let Some(agent) = self.live_agent() else {
178 return;
179 };
180 let turn_id = if entry.untrusted {
184 match agent.tainted_note_turn(&entry.session_id).await {
185 Ok(turn_id) => Some(turn_id),
186 Err(error) => {
187 warn!(
188 notification_id = %entry.id,
189 %error,
190 "Untrusted notification not recorded in owner history: its taint could not be recorded"
191 );
192 return;
193 }
194 }
195 } else {
196 None
197 };
198 if let Err(error) = agent
199 .record_parent_visible_result_note_in_turn(
200 &entry.session_id,
201 QUEUED_NOTIFICATION_NOTE_PREFIX,
202 delivered_text,
203 turn_id.as_deref(),
204 )
205 .await
206 {
207 warn!(
208 notification_id = %entry.id,
209 %error,
210 "Failed to record delivered notification in owner history"
211 );
212 }
213 if notice_accepts_mandate_answer(&entry.notification_type) {
214 self.bind_mandate_answer_context(agent.as_ref(), entry)
215 .await;
216 }
217 }
218
219 pub async fn bind_mandate_answer_context(
224 &self,
225 agent: &dyn TaskLeadHost,
226 entry: &crate::traits::NotificationEntry,
227 ) {
228 let mandate = match self.state.get_mandate_for_goal(&entry.goal_id).await {
229 Ok(Some(mandate)) => mandate,
230 Ok(None) => return,
231 Err(error) => {
232 warn!(
233 goal_id = %entry.goal_id,
234 notification_id = %entry.id,
235 %error,
236 "Failed to load mandate after delivering queued question notice"
237 );
238 return;
239 }
240 };
241 let answerable = match entry.notification_type.as_str() {
242 "mandate_ask" => mandate.status == MandateStatus::AwaitingInput,
243 _ => !mandate.status.is_terminal(),
244 };
245 if !answerable {
246 return;
247 }
248 if let Err(error) = agent
249 .record_mandate_owner_input_context(
250 &entry.session_id,
251 &mandate.id,
252 mandate.version,
253 entry.action_token.as_deref().unwrap_or(&entry.id),
254 )
255 .await
256 {
257 warn!(
258 mandate_id = %mandate.id,
259 notification_id = %entry.id,
260 %error,
261 "Failed to bind queued mandate question to owner dialogue state"
262 );
263 }
264 }
265
266 const OWNER_AWAKE_WINDOW_MINUTES: i64 = 30;
270
271 async fn owner_awake_in<'a>(
274 &self,
275 session_id: &'a str,
276 known: &mut std::collections::HashMap<&'a str, bool>,
277 ) -> bool {
278 if let Some(awake) = known.get(session_id) {
279 return *awake;
280 }
281 let since = Utc::now() - chrono::Duration::minutes(Self::OWNER_AWAKE_WINDOW_MINUTES);
282 let awake = match self.hub.as_ref() {
283 Some(hub) => hub.owner_active_since(session_id, since).await,
284 None => false,
285 };
286 known.insert(session_id, awake);
287 awake
288 }
289
290 async fn review_failure_superseded(&self, entry: &crate::traits::NotificationEntry) -> bool {
295 if entry.notification_type != "mandate_review_failed" {
297 return false;
298 }
299 let Ok(told_at) = chrono::DateTime::parse_from_rfc3339(&entry.created_at) else {
300 return false;
301 };
302 let Ok(runs) = self.state.get_goal_runs(&entry.goal_id).await else {
303 return false;
304 };
305 runs.iter().any(|run| {
306 run.trigger_type == "mandate"
307 && run.status == "completed"
308 && run
309 .completed_at
310 .as_deref()
311 .and_then(|at| chrono::DateTime::parse_from_rfc3339(at).ok())
312 .is_some_and(|finished| finished > told_at)
313 })
314 }
315
316 pub async fn process_notification_queue(&self) {
318 let pending = match self.state.get_pending_notifications(100).await {
321 Ok(n) => n,
322 Err(e) => {
323 error!(error = %e, "Failed to get pending notifications");
324 return;
325 }
326 };
327
328 let mut delivery_attempts = 0usize;
329 let mut awake: std::collections::HashMap<&str, bool> = std::collections::HashMap::new();
330 for entry in &pending {
331 if self.review_failure_superseded(entry).await {
332 if let Err(error) = self.state.mark_notification_delivered(&entry.id).await {
333 warn!(
334 notification_id = %entry.id,
335 error = %error,
336 "Failed to close a superseded review-failure notice"
337 );
338 }
339 continue;
340 }
341 let local_hour = chrono::Timelike::hour(&chrono::Local::now());
342 if !entry.should_deliver_at_local_hour(local_hour)
343 && !self.owner_awake_in(&entry.session_id, &mut awake).await
344 {
345 tracing::debug!(
346 notification_id = %entry.id,
347 notification_type = %entry.notification_type,
348 local_hour,
349 "Deferring recoverable notification during quiet hours"
350 );
351 continue;
352 }
353 if delivery_attempts >= 20 {
354 break;
355 }
356 delivery_attempts = delivery_attempts.saturating_add(1);
357 if entry.notification_type == "escalation"
358 && let Some(task_id) = entry.task_id.as_deref()
359 {
360 if !task_escalation_has_settled(&entry.created_at, Utc::now()) {
365 continue;
366 }
367 match self.state.get_task(task_id).await {
368 Ok(Some(task)) if task.status == "blocked" => {}
369 Ok(_) => {
370 if let Err(error) = self.state.mark_notification_delivered(&entry.id).await
371 {
372 warn!(
373 notification_id = %entry.id,
374 task_id,
375 error = %error,
376 "Failed to close stale task escalation"
377 );
378 }
379 continue;
380 }
381 Err(error) => {
382 warn!(
383 notification_id = %entry.id,
384 task_id,
385 error = %error,
386 "Deferred task escalation because task state could not be verified"
387 );
388 continue;
389 }
390 }
391 }
392 let sanitized = self.presenter.user_facing(&entry.message);
393 let delivered = if let Some(hub) = self.hub.clone() {
394 let message = self
395 .presenter
396 .notification(&entry.notification_type, &sanitized);
397 match tokio::time::timeout(
401 Duration::from_secs(15),
402 hub.send_text(&entry.session_id, &message),
403 )
404 .await
405 {
406 Ok(result) => result.is_ok(),
407 Err(_) => {
408 warn!(
409 notification_id = %entry.id,
410 session_id = %entry.session_id,
411 "Notification delivery timed out"
412 );
413 false
414 }
415 }
416 } else {
417 false
418 };
419
420 if delivered {
421 self.record_delivered_notification(entry, &sanitized).await;
422 if let Err(e) = self.state.mark_notification_delivered(&entry.id).await {
423 error!(notification_id = %entry.id, error = %e, "Failed to mark notification delivered");
424 }
425 } else {
426 if let Err(e) = self.state.increment_notification_attempt(&entry.id).await {
429 error!(notification_id = %entry.id, error = %e, "Failed to increment notification attempt");
430 }
431 }
432 }
433 }
434}