1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
//! Delivering goal results to their chats.
use super::*;
impl GoalCycle {
/// Phase 5a: Scan goals that completed/failed and enqueue notifications.
/// Phase 5b: Process notification queue — attempt delivery.
/// Phase 5c: Cleanup expired status_update notifications.
pub async fn deliver_notifications(&self) {
// Phase 5a: Enqueue notifications for goals that need them
self.enqueue_goal_notifications().await;
// Phase 5b: Process notification queue
self.process_notification_queue().await;
// Phase 5c: Cleanup expired status_update notifications (24h TTL)
match self.state.cleanup_expired_notifications().await {
Ok(count) if count > 0 => {
info!(count, "Cleaned up expired status_update notifications");
}
Err(e) => {
error!(error = %e, "Failed to cleanup expired notifications");
}
_ => {}
}
}
/// Scan for goals needing notification and enqueue them.
pub async fn enqueue_goal_notifications(&self) {
let goals = match self.state.get_goals_needing_notification().await {
Ok(g) => g,
Err(e) => {
error!(error = %e, "Failed to get goals needing notification");
return;
}
};
for goal in &goals {
let (notification_type, msg) = match goal.status.as_str() {
"completed" => {
// Prefer the latest run's task state. Historical failed runs
// remain valuable audit data but cannot invalidate a later,
// successfully tracked recovery run.
let latest_run = self
.state
.get_goal_runs(&goal.id)
.await
.unwrap_or_default()
.into_iter()
.next();
let latest_root_task_id = latest_run
.as_ref()
.and_then(|run| run.root_task_id.as_deref())
.map(str::to_string);
// The run's typed terminal status is the outcome; the
// wording of its summary never is.
let latest_run_unsuccessful = latest_run
.as_ref()
.is_some_and(|run| matches!(run.status.as_str(), "failed" | "blocked"));
let completed_tasks = match latest_run {
Some(run) => self
.state
.get_tasks_for_goal_run(&run.id)
.await
.unwrap_or_default(),
None => self
.state
.get_tasks_for_goal(&goal.id)
.await
.unwrap_or_default(),
};
let fallback_summary: String = goal.description.chars().take(300).collect();
let task_results_summary = self.presenter.goal_task_results(
&completed_tasks,
latest_root_task_id.as_deref(),
&fallback_summary,
);
if latest_run_unsuccessful
|| (!completed_tasks.is_empty()
&& !crate::goals::tasks_satisfy_goal_completion(&completed_tasks))
{
let mut corrected = goal.clone();
corrected.status = "failed".to_string();
corrected.completed_at = Some(chrono::Utc::now().to_rfc3339());
corrected.updated_at = chrono::Utc::now().to_rfc3339();
if let Err(error) = self.state.update_goal(&corrected).await {
error!(goal_id = %goal.id, %error, "Failed to repair inconsistent completed goal state");
}
(
"failed",
format!(
"Goal incomplete: required tasks did not finish successfully.\n\n{}",
task_results_summary.chars().take(4000).collect::<String>()
),
)
} else {
// Check for partial success metadata in context
let partial_info = goal
.context
.as_deref()
.and_then(|ctx| serde_json::from_str::<serde_json::Value>(ctx).ok())
.filter(|v| {
v.get("partial_success")
.and_then(|p| p.as_bool())
.unwrap_or(false)
});
if let Some(summary) = partial_info {
let completed = summary
.get("completed")
.and_then(|v| v.as_u64())
.unwrap_or(0);
let failed =
summary.get("failed").and_then(|v| v.as_u64()).unwrap_or(0);
let blocked =
summary.get("blocked").and_then(|v| v.as_u64()).unwrap_or(0);
let total = summary.get("total").and_then(|v| v.as_u64()).unwrap_or(0);
(
"failed",
format!(
"Goal partially completed ({}/{} tasks succeeded, {} failed, {} blocked):\n\n{}",
completed,
total,
failed,
blocked,
task_results_summary.chars().take(4000).collect::<String>()
),
)
} else {
(
"completed",
format!(
"{}\n\n{}",
goal_completion_header(&completed_tasks),
task_results_summary.chars().take(4000).collect::<String>()
),
)
}
}
}
"failed" => (
"failed",
format!(
"{} {}",
aidaemon_channels::presentation::GOAL_FAILED_LEAD,
goal.description.chars().take(300).collect::<String>()
),
),
_ => continue,
};
// The message carries the goal's task results: text its runs
// wrote after reading whatever they read. It reaches the owner's
// history as untrusted, so the next turn there starts tainted.
let entry = crate::traits::NotificationEntry::new(
&goal.id,
&goal.session_id,
notification_type,
&msg,
)
.with_untrusted(true);
if let Err(e) = self.state.enqueue_goal_notification(&entry).await {
error!(goal_id = %goal.id, error = %e, "Failed to atomically enqueue notification");
}
}
}
/// Queue delivery bypasses `deliver_parent_text_result`, so persist every
/// delivered notice in owner history: a reply to it must reach an agent
/// that can see what it answers.
pub async fn record_delivered_notification(
&self,
entry: &crate::traits::NotificationEntry,
delivered_text: &str,
) {
let Some(agent) = self.live_agent() else {
return;
};
// An untrusted notice joins a turn recorded tainted before the note
// exists; if the record cannot be written the note is not written
// either (it would read as clean).
let turn_id = if entry.untrusted {
match agent.tainted_note_turn(&entry.session_id).await {
Ok(turn_id) => Some(turn_id),
Err(error) => {
warn!(
notification_id = %entry.id,
%error,
"Untrusted notification not recorded in owner history: its taint could not be recorded"
);
return;
}
}
} else {
None
};
if let Err(error) = agent
.record_parent_visible_result_note_in_turn(
&entry.session_id,
QUEUED_NOTIFICATION_NOTE_PREFIX,
delivered_text,
turn_id.as_deref(),
)
.await
{
warn!(
notification_id = %entry.id,
%error,
"Failed to record delivered notification in owner history"
);
}
if notice_accepts_mandate_answer(&entry.notification_type) {
self.bind_mandate_answer_context(agent.as_ref(), entry)
.await;
}
}
/// Bind the owner's next reply to a delivered mandate question so a bare
/// "yes" reaches `answer_question` instead of an agent with no referent.
/// A timed-out ASK has already resumed, so any non-terminal mandate that
/// still carries the question qualifies; the answer lands as late guidance.
pub async fn bind_mandate_answer_context(
&self,
agent: &dyn TaskLeadHost,
entry: &crate::traits::NotificationEntry,
) {
let mandate = match self.state.get_mandate_for_goal(&entry.goal_id).await {
Ok(Some(mandate)) => mandate,
Ok(None) => return,
Err(error) => {
warn!(
goal_id = %entry.goal_id,
notification_id = %entry.id,
%error,
"Failed to load mandate after delivering queued question notice"
);
return;
}
};
let answerable = match entry.notification_type.as_str() {
"mandate_ask" => mandate.status == MandateStatus::AwaitingInput,
_ => !mandate.status.is_terminal(),
};
if !answerable {
return;
}
if let Err(error) = agent
.record_mandate_owner_input_context(
&entry.session_id,
&mandate.id,
mandate.version,
entry.action_token.as_deref().unwrap_or(&entry.id),
)
.await
{
warn!(
mandate_id = %mandate.id,
notification_id = %entry.id,
%error,
"Failed to bind queued mandate question to owner dialogue state"
);
}
}
/// How recently an owner message in a chat counts as the owner being
/// awake there (a restart notice for a job they were just talking
/// about, sent at 12:15 AM, is not held until 7 AM).
const OWNER_AWAKE_WINDOW_MINUTES: i64 = 30;
/// Whether the owner wrote in `session_id` within the awake window,
/// asked once per chat per pass.
async fn owner_awake_in<'a>(
&self,
session_id: &'a str,
known: &mut std::collections::HashMap<&'a str, bool>,
) -> bool {
if let Some(awake) = known.get(session_id) {
return *awake;
}
let since = Utc::now() - chrono::Duration::minutes(Self::OWNER_AWAKE_WINDOW_MINUTES);
let awake = match self.hub.as_ref() {
Some(hub) => hub.owner_active_since(session_id, since).await,
None => false,
};
known.insert(session_id, awake);
awake
}
/// Process the notification queue: attempt delivery, track attempts.
pub async fn process_notification_queue(&self) {
// Read past the normal delivery batch so quiet-hour routine entries at
// the front of the queue cannot hide a later owner-action request.
let pending = match self.state.get_pending_notifications(100).await {
Ok(n) => n,
Err(e) => {
error!(error = %e, "Failed to get pending notifications");
return;
}
};
let mut delivery_attempts = 0usize;
let mut awake: std::collections::HashMap<&str, bool> = std::collections::HashMap::new();
for entry in &pending {
let local_hour = chrono::Timelike::hour(&chrono::Local::now());
if !entry.should_deliver_at_local_hour(local_hour)
&& !self.owner_awake_in(&entry.session_id, &mut awake).await
{
tracing::debug!(
notification_id = %entry.id,
notification_type = %entry.notification_type,
local_hour,
"Deferring recoverable notification during quiet hours"
);
continue;
}
if delivery_attempts >= 20 {
break;
}
delivery_attempts = delivery_attempts.saturating_add(1);
if entry.notification_type == "escalation"
&& let Some(task_id) = entry.task_id.as_deref()
{
// Give the coordinator a brief chance to reconcile the
// executor handoff, then verify the linked task is still
// blocked. This prevents a stale critical notification
// from racing a same-turn unblock or completion.
if !task_escalation_has_settled(&entry.created_at, Utc::now()) {
continue;
}
match self.state.get_task(task_id).await {
Ok(Some(task)) if task.status == "blocked" => {}
Ok(_) => {
if let Err(error) = self.state.mark_notification_delivered(&entry.id).await
{
warn!(
notification_id = %entry.id,
task_id,
error = %error,
"Failed to close stale task escalation"
);
}
continue;
}
Err(error) => {
warn!(
notification_id = %entry.id,
task_id,
error = %error,
"Deferred task escalation because task state could not be verified"
);
continue;
}
}
}
let sanitized = self.presenter.user_facing(&entry.message);
let delivered = if let Some(hub) = self.hub.clone() {
let message = self
.presenter
.notification(&entry.notification_type, &sanitized);
// A channel adapter is external I/O. It must never be allowed to
// pin the heartbeat forever because this same loop admits due
// schedules and dispatches pending tasks on the next tick.
match tokio::time::timeout(
Duration::from_secs(15),
hub.send_text(&entry.session_id, &message),
)
.await
{
Ok(result) => result.is_ok(),
Err(_) => {
warn!(
notification_id = %entry.id,
session_id = %entry.session_id,
"Notification delivery timed out"
);
false
}
}
} else {
false
};
if delivered {
self.record_delivered_notification(entry, &sanitized).await;
if let Err(e) = self.state.mark_notification_delivered(&entry.id).await {
error!(notification_id = %entry.id, error = %e, "Failed to mark notification delivered");
}
} else {
// Increment attempt counter — critical notifications will keep retrying
// (no expiry), status_update notifications will eventually expire via TTL
if let Err(e) = self.state.increment_notification_attempt(&entry.id).await {
error!(notification_id = %entry.id, error = %e, "Failed to increment notification attempt");
}
}
}
}
}